blob: 838c38a7b2886c672ff22807fefa0f7c5b8b3b9f [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);
940 printf("]");
941 }
942 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000943
944 {
945 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
946 if (QT != CXObjCDeclQualifier_None) {
947 printf(" [");
948 #define PRINT_OBJC_QUAL(A) \
949 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
950 PRINT_OBJC_QUAL(In);
951 PRINT_OBJC_QUAL(Inout);
952 PRINT_OBJC_QUAL(Out);
953 PRINT_OBJC_QUAL(Bycopy);
954 PRINT_OBJC_QUAL(Byref);
955 PRINT_OBJC_QUAL(Oneway);
956 printf("]");
957 }
958 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000959 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000960}
Steve Naroff1054e602009-08-31 00:59:03 +0000961
Ted Kremenek29004672010-02-17 00:41:32 +0000962static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000963 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000964 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000965 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000966 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000967 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000968 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000969 clang_disposeString(source);
970 return "<invalid loc>";
971 }
972 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000973 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000974 clang_disposeString(source);
975 return b;
976 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000977}
978
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000979/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000980/* Callbacks. */
981/******************************************************************************/
982
983typedef void (*PostVisitTU)(CXTranslationUnit);
984
Douglas Gregor33cdd812010-02-18 18:08:43 +0000985void PrintDiagnostic(CXDiagnostic Diagnostic) {
986 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000987 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000988 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000989 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000990 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
991 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000992 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000993
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000994 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000995 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000996
Douglas Gregord770f732010-02-22 23:17:23 +0000997 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
998 fprintf(stderr, "%s\n", clang_getCString(Msg));
999 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +00001000
Douglas Gregor229bebd2010-11-09 06:24:54 +00001001 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
1002 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001003 if (!file)
1004 return;
Ted Kremenek29004672010-02-17 00:41:32 +00001005
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001006 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +00001007 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001008 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +00001009 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001010 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
1011 CXSourceLocation start = clang_getRangeStart(range);
1012 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +00001013 unsigned start_line, start_column, end_line, end_column;
1014 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001015 clang_getSpellingLocation(start, &start_file, &start_line,
1016 &start_column, 0);
1017 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001018 if (clang_equalLocations(start, end)) {
1019 /* Insertion. */
1020 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001021 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001022 clang_getCString(insertion_text), start_line, start_column);
1023 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1024 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001025 if (start_file == file && end_file == file) {
1026 fprintf(out, "FIX-IT: Remove ");
1027 PrintExtent(out, start_line, start_column, end_line, end_column);
1028 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001029 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001030 } else {
1031 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001032 if (start_file == end_file) {
1033 fprintf(out, "FIX-IT: Replace ");
1034 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001035 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001036 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001037 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001038 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001039 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001040}
1041
Ted Kremenek914c7e62012-02-14 02:46:03 +00001042void PrintDiagnosticSet(CXDiagnosticSet Set) {
1043 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1044 for ( ; i != n ; ++i) {
1045 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1046 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001047 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001048 if (ChildDiags)
1049 PrintDiagnosticSet(ChildDiags);
1050 }
1051}
1052
1053void PrintDiagnostics(CXTranslationUnit TU) {
1054 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1055 PrintDiagnosticSet(TUSet);
1056 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001057}
1058
Ted Kremenek83f642e2011-04-18 22:47:10 +00001059void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001060 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001061 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001062 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001063 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001064 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001065 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001066 unsigned long amount = usage.entries[i].amount;
1067 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001068 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001069 ((double) amount)/(1024*1024));
1070 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001071 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001072 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001073 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001074}
1075
Ted Kremenekb478ff42010-01-26 17:59:48 +00001076/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001077/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001078/******************************************************************************/
1079
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001080static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001081 CXSourceRange extent = clang_getCursorExtent(C);
1082 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001083}
1084
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001085/* Data used by the visitors. */
1086typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001087 CXTranslationUnit TU;
1088 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001089 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001090} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001091
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001092
Ted Kremenek29004672010-02-17 00:41:32 +00001093enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001094 CXCursor Parent,
1095 CXClientData ClientData) {
1096 VisitorData *Data = (VisitorData *)ClientData;
1097 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001098 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001099 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001100 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001101 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001102 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001103 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001104 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001105 if (clang_isDeclaration(Cursor.kind)) {
1106 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1107 const char *accessStr = 0;
1108
1109 switch (access) {
1110 case CX_CXXInvalidAccessSpecifier: break;
1111 case CX_CXXPublic:
1112 accessStr = "public"; break;
1113 case CX_CXXProtected:
1114 accessStr = "protected"; break;
1115 case CX_CXXPrivate:
1116 accessStr = "private"; break;
1117 }
1118
1119 if (accessStr)
1120 printf(" [access=%s]", accessStr);
1121 }
Ted Kremenek29004672010-02-17 00:41:32 +00001122 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001123 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001124 }
Ted Kremenek29004672010-02-17 00:41:32 +00001125
Douglas Gregor720d0052010-01-20 21:32:04 +00001126 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001127}
Steve Naroffa1c72842009-08-28 15:28:48 +00001128
Ted Kremenek29004672010-02-17 00:41:32 +00001129static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001130 CXCursor Parent,
1131 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001132 const char *startBuf, *endBuf;
1133 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1134 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001135 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001136
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001137 if (Cursor.kind != CXCursor_FunctionDecl ||
1138 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001139 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001140
1141 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1142 &startLine, &startColumn,
1143 &endLine, &endColumn);
1144 /* Probe the entire body, looking for both decls and refs. */
1145 curLine = startLine;
1146 curColumn = startColumn;
1147
1148 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001149 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001150 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001151 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001152
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001153 if (*startBuf == '\n') {
1154 startBuf++;
1155 curLine++;
1156 curColumn = 1;
1157 } else if (*startBuf != '\t')
1158 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001159
Douglas Gregor66a58812010-01-18 22:46:11 +00001160 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001161 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001162
Douglas Gregor4f46e782010-01-19 21:36:55 +00001163 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001164 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001165 CXSourceLocation RefLoc
1166 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001167 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001168 if (Ref.kind == CXCursor_NoDeclFound) {
1169 /* Nothing found here; that's fine. */
1170 } else if (Ref.kind != CXCursor_FunctionDecl) {
1171 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1172 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001173 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001174 printf("\n");
1175 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001176 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001177 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001178 startBuf++;
1179 }
Ted Kremenek29004672010-02-17 00:41:32 +00001180
Douglas Gregor720d0052010-01-20 21:32:04 +00001181 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001182}
1183
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001184/******************************************************************************/
1185/* USR testing. */
1186/******************************************************************************/
1187
Douglas Gregor720d0052010-01-20 21:32:04 +00001188enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1189 CXClientData ClientData) {
1190 VisitorData *Data = (VisitorData *)ClientData;
1191 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001192 CXString USR = clang_getCursorUSR(C);
1193 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001194 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001195 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001196 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001197 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001198 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1199
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001200 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001201 printf("\n");
1202 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001203
Douglas Gregor720d0052010-01-20 21:32:04 +00001204 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001205 }
1206
Douglas Gregor720d0052010-01-20 21:32:04 +00001207 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001208}
1209
1210/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001211/* Inclusion stack testing. */
1212/******************************************************************************/
1213
1214void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1215 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001216
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001217 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001218 CXString fname;
1219
1220 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001221 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001222 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001223
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001224 for (i = 0; i < includeStackLen; ++i) {
1225 CXFile includingFile;
1226 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001227 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1228 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001229 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001230 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001231 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001232 }
1233 printf("\n");
1234}
1235
1236void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001237 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001238}
1239
1240/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001241/* Linkage testing. */
1242/******************************************************************************/
1243
1244static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1245 CXClientData d) {
1246 const char *linkage = 0;
1247
1248 if (clang_isInvalid(clang_getCursorKind(cursor)))
1249 return CXChildVisit_Recurse;
1250
1251 switch (clang_getCursorLinkage(cursor)) {
1252 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001253 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1254 case CXLinkage_Internal: linkage = "Internal"; break;
1255 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1256 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001257 }
1258
1259 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001260 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001261 printf("linkage=%s\n", linkage);
1262 }
1263
1264 return CXChildVisit_Recurse;
1265}
1266
1267/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001268/* Typekind testing. */
1269/******************************************************************************/
1270
Dmitri Gribenko00353722013-02-15 21:15:49 +00001271static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1272 CXString TypeSpelling, TypeKindSpelling;
1273
1274 TypeSpelling = clang_getTypeSpelling(T);
1275 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1276 printf(Format,
1277 clang_getCString(TypeSpelling),
1278 clang_getCString(TypeKindSpelling));
1279 clang_disposeString(TypeSpelling);
1280 clang_disposeString(TypeKindSpelling);
1281}
1282
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001283static enum CXVisitorResult FieldVisitor(CXCursor C,
1284 CXClientData client_data) {
1285 (*(int *) client_data)+=1;
1286 return CXVisit_Continue;
1287}
1288
Dmitri Gribenko00353722013-02-15 21:15:49 +00001289static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1290 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001291 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001292 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001293 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001294 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001295 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001296 if (clang_isConstQualifiedType(T))
1297 printf(" const");
1298 if (clang_isVolatileQualifiedType(T))
1299 printf(" volatile");
1300 if (clang_isRestrictQualifiedType(T))
1301 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001302 if (RQ == CXRefQualifier_LValue)
1303 printf(" lvalue-ref-qualifier");
1304 if (RQ == CXRefQualifier_RValue)
1305 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001306 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001307 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001308 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001309 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001310 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001311 }
1312 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001313 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001314 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001315 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001316 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001317 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001318 }
1319 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001320 /* Print the argument types if they exist. */
1321 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001322 int NumArgs = clang_Cursor_getNumArguments(cursor);
1323 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001324 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001325 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001326 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001327 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001328 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001329 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001330 }
1331 }
1332 printf("]");
1333 }
1334 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001335 /* Print the template argument types if they exist. */
1336 {
1337 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1338 if (NumTArgs != -1 && NumTArgs != 0) {
1339 int i;
1340 printf(" [templateargs/%d=", NumTArgs);
1341 for (i = 0; i < NumTArgs; ++i) {
1342 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1343 if (TArg.kind != CXType_Invalid) {
1344 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1345 }
1346 }
1347 printf("]");
1348 }
1349 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001350 /* Print if this is a non-POD type. */
1351 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001352 /* Print the pointee type. */
1353 {
1354 CXType PT = clang_getPointeeType(T);
1355 if (PT.kind != CXType_Invalid) {
1356 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1357 }
1358 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001359 /* Print the number of fields if they exist. */
1360 {
1361 int numFields = 0;
1362 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1363 if (numFields != 0) {
1364 printf(" [nbFields=%d]", numFields);
1365 }
1366 /* Print if it is an anonymous record. */
1367 {
1368 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1369 if (isAnon != 0) {
1370 printf(" [isAnon=%d]", isAnon);
1371 }
1372 }
1373 }
1374 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001375
Ted Kremenek6bca9842010-05-14 21:29:26 +00001376 printf("\n");
1377 }
1378 return CXChildVisit_Recurse;
1379}
1380
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001381static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1382 CXClientData d) {
1383 CXType T;
1384 enum CXCursorKind K = clang_getCursorKind(cursor);
1385 if (clang_isInvalid(K))
1386 return CXChildVisit_Recurse;
1387 T = clang_getCursorType(cursor);
1388 PrintCursor(cursor, NULL);
1389 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1390 /* Print the type sizeof if applicable. */
1391 {
1392 long long Size = clang_Type_getSizeOf(T);
1393 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001394 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001395 }
1396 }
1397 /* Print the type alignof if applicable. */
1398 {
1399 long long Align = clang_Type_getAlignOf(T);
1400 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001401 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001402 }
1403 }
1404 /* Print the record field offset if applicable. */
1405 {
Nico Weber82098cb2014-04-24 04:14:12 +00001406 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1407 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001408 /* recurse to get the first parent record that is not anonymous. */
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001409 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001410 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
David Blaikie263942f2016-05-03 22:14:14 +00001411 CXCursor Record;
1412 CXCursor Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001413 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001414 Record = Parent;
1415 Parent = clang_getCursorSemanticParent(Record);
1416 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1417 /* Recurse as long as the parent is a CXType_Record and the Record
1418 is anonymous */
1419 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1420 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001421 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001422 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001423 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001424 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1425 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001426 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001427 } else {
1428 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001429 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001430 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001431 }
1432 }
Nico Weber82098cb2014-04-24 04:14:12 +00001433 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001434 }
1435 /* Print if its a bitfield */
1436 {
1437 int IsBitfield = clang_Cursor_isBitField(cursor);
1438 if (IsBitfield)
1439 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1440 }
1441 printf("\n");
1442 return CXChildVisit_Recurse;
1443}
1444
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001445/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001446/* Mangling testing. */
1447/******************************************************************************/
1448
1449static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1450 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001451 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001452 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1453 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001454 PrintCursor(cursor, NULL);
1455 MangledName = clang_Cursor_getMangling(cursor);
1456 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001457 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001458 return CXChildVisit_Continue;
1459}
1460
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001461static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1462 CXClientData d) {
1463 unsigned I, E;
1464 CXStringSet *Manglings = NULL;
1465 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1466 return CXChildVisit_Recurse;
1467 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1468 return CXChildVisit_Recurse;
1469 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1470 return CXChildVisit_Continue;
1471 PrintCursor(cursor, NULL);
1472 Manglings = clang_Cursor_getCXXManglings(cursor);
1473 for (I = 0, E = Manglings->Count; I < E; ++I)
1474 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1475 clang_disposeStringSet(Manglings);
1476 printf("\n");
1477 return CXChildVisit_Recurse;
1478}
1479
Eli Bendersky44a206f2014-07-31 18:04:56 +00001480/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001481/* Bitwidth testing. */
1482/******************************************************************************/
1483
1484static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1485 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001486 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001487 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1488 return CXChildVisit_Recurse;
1489
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001490 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001491 if (Bitwidth >= 0) {
1492 PrintCursor(cursor, NULL);
1493 printf(" bitwidth=%d\n", Bitwidth);
1494 }
1495
1496 return CXChildVisit_Recurse;
1497}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001498
1499/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001500/* Type declaration testing */
1501/******************************************************************************/
1502
1503static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1504 CXClientData d) {
1505 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1506
1507 if (clang_isDeclaration(typeDeclaration.kind)) {
1508 PrintCursor(cursor, NULL);
1509 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1510 }
1511
1512 return CXChildVisit_Recurse;
1513}
1514
1515/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001516/* Loading ASTs/source. */
1517/******************************************************************************/
1518
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001519static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001520 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001521 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001522 PostVisitTU PV,
1523 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001524
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001525 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001526 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001527
1528 if (Visitor) {
1529 enum CXCursorKind K = CXCursor_NotImplemented;
1530 enum CXCursorKind *ck = &K;
1531 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001532
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001533 /* Perform some simple filtering. */
1534 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001535 else if (!strcmp(filter, "all-display") ||
1536 !strcmp(filter, "local-display")) {
1537 ck = NULL;
1538 want_display_name = 1;
1539 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001540 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001541 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1542 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1543 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1544 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1545 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1546 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1547 else {
1548 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1549 return 1;
1550 }
Ted Kremenek29004672010-02-17 00:41:32 +00001551
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001552 Data.TU = TU;
1553 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001554 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001555 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001556 }
Ted Kremenek29004672010-02-17 00:41:32 +00001557
Ted Kremenekb478ff42010-01-26 17:59:48 +00001558 if (PV)
1559 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001560
Douglas Gregor33cdd812010-02-18 18:08:43 +00001561 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001562 if (checkForErrors(TU) != 0) {
1563 clang_disposeTranslationUnit(TU);
1564 return -1;
1565 }
1566
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001567 clang_disposeTranslationUnit(TU);
1568 return 0;
1569}
1570
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001571int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001572 const char *prefix, CXCursorVisitor Visitor,
1573 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001574 CXIndex Idx;
1575 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001576 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001577 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001578 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001579 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001580
Ted Kremenek50228be2010-02-11 07:41:25 +00001581 if (!CreateTranslationUnit(Idx, file, &TU)) {
1582 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001583 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001584 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001585
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001586 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001587 clang_disposeIndex(Idx);
1588 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001589}
1590
Ted Kremenekb478ff42010-01-26 17:59:48 +00001591int perform_test_load_source(int argc, const char **argv,
1592 const char *filter, CXCursorVisitor Visitor,
1593 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001594 CXIndex Idx;
1595 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001596 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001597 struct CXUnsavedFile *unsaved_files = 0;
1598 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001599 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001600 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001601 unsigned Repeats = 0;
1602 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001603
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001604 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001605 (!strcmp(filter, "local") ||
1606 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001607 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001608
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001609 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1610 argc--;
1611 argv++;
1612 }
1613
Ted Kremenek50228be2010-02-11 07:41:25 +00001614 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1615 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001616 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001617 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001618
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001619 if (getenv("CINDEXTEST_EDITING"))
1620 Repeats = 5;
1621
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001622 Err = clang_parseTranslationUnit2(Idx, 0,
1623 argv + num_unsaved_files,
1624 argc - num_unsaved_files,
1625 unsaved_files, num_unsaved_files,
1626 getDefaultParsingOptions(), &TU);
1627 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001628 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001629 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001630 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001631 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001632 return 1;
1633 }
1634
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001635 for (I = 0; I != Repeats; ++I) {
1636 if (checkForErrors(TU) != 0)
1637 return -1;
1638
1639 if (Repeats > 1) {
1640 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1641 clang_defaultReparseOptions(TU));
1642 if (Err != CXError_Success) {
1643 describeLibclangFailure(Err);
1644 free_remapped_files(unsaved_files, num_unsaved_files);
1645 clang_disposeIndex(Idx);
1646 return 1;
1647 }
1648 }
1649 }
1650
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001651 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1652 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001653 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001654 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001655 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001656}
1657
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001658int perform_test_reparse_source(int argc, const char **argv, int trials,
1659 const char *filter, CXCursorVisitor Visitor,
1660 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001661 CXIndex Idx;
1662 CXTranslationUnit TU;
1663 struct CXUnsavedFile *unsaved_files = 0;
1664 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001665 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001666 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001667 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001668 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001669 int remap_after_trial = 0;
1670 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001671
1672 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1673 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001674 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001675
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001676 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1677 clang_disposeIndex(Idx);
1678 return -1;
1679 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001680
1681 for (i = 0; i < argc; ++i) {
1682 if (strcmp(argv[i], "--") == 0)
1683 break;
1684 }
1685 if (i < argc)
1686 compiler_arg_idx = i+1;
1687 if (num_unsaved_files > compiler_arg_idx)
1688 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001689
Daniel Dunbarec29d712010-08-18 23:09:16 +00001690 /* Load the initial translation unit -- we do this without honoring remapped
1691 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001692 Err = clang_parseTranslationUnit2(Idx, 0,
1693 argv + compiler_arg_idx,
1694 argc - compiler_arg_idx,
1695 0, 0, getDefaultParsingOptions(), &TU);
1696 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001697 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001698 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001699 free_remapped_files(unsaved_files, num_unsaved_files);
1700 clang_disposeIndex(Idx);
1701 return 1;
1702 }
1703
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001704 if (checkForErrors(TU) != 0)
1705 return -1;
1706
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001707 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1708 remap_after_trial =
1709 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1710 }
1711
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001712 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001713 free_remapped_files(unsaved_files, num_unsaved_files);
1714 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1715 &unsaved_files, &num_unsaved_files)) {
1716 clang_disposeTranslationUnit(TU);
1717 clang_disposeIndex(Idx);
1718 return -1;
1719 }
1720
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001721 Err = clang_reparseTranslationUnit(
1722 TU,
1723 trial >= remap_after_trial ? num_unsaved_files : 0,
1724 trial >= remap_after_trial ? unsaved_files : 0,
1725 clang_defaultReparseOptions(TU));
1726 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001727 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001728 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001729 clang_disposeTranslationUnit(TU);
1730 free_remapped_files(unsaved_files, num_unsaved_files);
1731 clang_disposeIndex(Idx);
1732 return -1;
1733 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001734
1735 if (checkForErrors(TU) != 0)
1736 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001737 }
1738
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001739 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001740
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001741 free_remapped_files(unsaved_files, num_unsaved_files);
1742 clang_disposeIndex(Idx);
1743 return result;
1744}
1745
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001746/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001747/* Logic for testing clang_getCursor(). */
1748/******************************************************************************/
1749
Douglas Gregor37aa4932011-05-04 00:14:37 +00001750static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001751 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001752 unsigned end_line, unsigned end_col,
1753 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001754 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001755 if (prefix)
1756 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001757 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1758 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001759 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001760 printf("\n");
1761}
1762
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001763static int perform_file_scan(const char *ast_file, const char *source_file,
1764 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001765 CXIndex Idx;
1766 CXTranslationUnit TU;
1767 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001768 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001769 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001770 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001771 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001772
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001773 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001774 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001775 fprintf(stderr, "Could not create Index\n");
1776 return 1;
1777 }
Ted Kremenek29004672010-02-17 00:41:32 +00001778
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001779 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1780 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001781
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001782 if ((fp = fopen(source_file, "r")) == NULL) {
1783 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001784 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001785 return 1;
1786 }
Ted Kremenek29004672010-02-17 00:41:32 +00001787
Douglas Gregor816fd362010-01-22 21:44:22 +00001788 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001789 for (;;) {
1790 CXCursor cursor;
1791 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001792
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001793 if (c == '\n') {
1794 ++line;
1795 col = 1;
1796 } else
1797 ++col;
1798
1799 /* Check the cursor at this position, and dump the previous one if we have
1800 * found something new.
1801 */
1802 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1803 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1804 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001805 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001806 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001807 start_line = line;
1808 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001809 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001810 if (c == EOF)
1811 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001812
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001813 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001814 }
Ted Kremenek29004672010-02-17 00:41:32 +00001815
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001816 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001817 clang_disposeTranslationUnit(TU);
1818 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001819 return 0;
1820}
1821
1822/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001823/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001824/******************************************************************************/
1825
Douglas Gregor9eb77012009-11-07 00:00:49 +00001826/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1827 on failure. If successful, the pointer *filename will contain newly-allocated
1828 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001829int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001830 unsigned *column, unsigned *second_line,
1831 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001832 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001833 const char *last_colon = strrchr(input, ':');
1834 unsigned values[4], i;
1835 unsigned num_values = (second_line && second_column)? 4 : 2;
1836
Douglas Gregor9eb77012009-11-07 00:00:49 +00001837 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001838 if (!last_colon || last_colon == input) {
1839 if (num_values == 4)
1840 fprintf(stderr, "could not parse filename:line:column:line:column in "
1841 "'%s'\n", input);
1842 else
1843 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001844 return 1;
1845 }
1846
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001847 for (i = 0; i != num_values; ++i) {
1848 const char *prev_colon;
1849
1850 /* Parse the next line or column. */
1851 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1852 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001853 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001854 (i % 2 ? "column" : "line"), input);
1855 return 1;
1856 }
Ted Kremenek29004672010-02-17 00:41:32 +00001857
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001858 if (i + 1 == num_values)
1859 break;
1860
1861 /* Find the previous colon. */
1862 prev_colon = last_colon - 1;
1863 while (prev_colon != input && *prev_colon != ':')
1864 --prev_colon;
1865 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001866 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001867 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001868 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001869 }
1870
1871 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001872 }
1873
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001874 *line = values[0];
1875 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001876
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001877 if (second_line && second_column) {
1878 *second_line = values[2];
1879 *second_column = values[3];
1880 }
1881
Douglas Gregorf96ea292009-11-09 18:19:57 +00001882 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001883 *filename = (char*)malloc(last_colon - input + 1);
1884 memcpy(*filename, input, last_colon - input);
1885 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001886 return 0;
1887}
1888
1889const char *
1890clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1891 switch (Kind) {
1892 case CXCompletionChunk_Optional: return "Optional";
1893 case CXCompletionChunk_TypedText: return "TypedText";
1894 case CXCompletionChunk_Text: return "Text";
1895 case CXCompletionChunk_Placeholder: return "Placeholder";
1896 case CXCompletionChunk_Informative: return "Informative";
1897 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1898 case CXCompletionChunk_LeftParen: return "LeftParen";
1899 case CXCompletionChunk_RightParen: return "RightParen";
1900 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1901 case CXCompletionChunk_RightBracket: return "RightBracket";
1902 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1903 case CXCompletionChunk_RightBrace: return "RightBrace";
1904 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1905 case CXCompletionChunk_RightAngle: return "RightAngle";
1906 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001907 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001908 case CXCompletionChunk_Colon: return "Colon";
1909 case CXCompletionChunk_SemiColon: return "SemiColon";
1910 case CXCompletionChunk_Equal: return "Equal";
1911 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1912 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001913 }
Ted Kremenek29004672010-02-17 00:41:32 +00001914
Douglas Gregor9eb77012009-11-07 00:00:49 +00001915 return "Unknown";
1916}
1917
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001918static int checkForErrors(CXTranslationUnit TU) {
1919 unsigned Num, i;
1920 CXDiagnostic Diag;
1921 CXString DiagStr;
1922
1923 if (!getenv("CINDEXTEST_FAILONERROR"))
1924 return 0;
1925
1926 Num = clang_getNumDiagnostics(TU);
1927 for (i = 0; i != Num; ++i) {
1928 Diag = clang_getDiagnostic(TU, i);
1929 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1930 DiagStr = clang_formatDiagnostic(Diag,
1931 clang_defaultDiagnosticDisplayOptions());
1932 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1933 clang_disposeString(DiagStr);
1934 clang_disposeDiagnostic(Diag);
1935 return -1;
1936 }
1937 clang_disposeDiagnostic(Diag);
1938 }
1939
1940 return 0;
1941}
1942
Nico Weber8d19dff2014-05-07 21:05:22 +00001943static void print_completion_string(CXCompletionString completion_string,
1944 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001945 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001946
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001947 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001948 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001949 CXString text;
1950 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001951 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001952 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001953
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001954 if (Kind == CXCompletionChunk_Optional) {
1955 fprintf(file, "{Optional ");
1956 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001957 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001958 file);
1959 fprintf(file, "}");
1960 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001961 }
1962
1963 if (Kind == CXCompletionChunk_VerticalSpace) {
1964 fprintf(file, "{VerticalSpace }");
1965 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001966 }
Ted Kremenek29004672010-02-17 00:41:32 +00001967
Douglas Gregorf81f5282009-11-09 17:05:28 +00001968 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001969 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001970 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001971 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001972 cstr ? cstr : "");
1973 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001974 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001975
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001976}
1977
Nico Weber8d19dff2014-05-07 21:05:22 +00001978static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001979 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001980 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001981 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001982 enum CXCursorKind ParentKind;
1983 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001984 CXString BriefComment;
Vedant Kumarf27d2272016-04-03 00:54:46 +00001985 CXString Annotation;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001986 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001987
Ted Kremenek29004672010-02-17 00:41:32 +00001988 fprintf(file, "%s:", clang_getCString(ks));
1989 clang_disposeString(ks);
1990
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001991 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001992 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001993 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001994 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1995 case CXAvailability_Available:
1996 break;
1997
1998 case CXAvailability_Deprecated:
1999 fprintf(file, " (deprecated)");
2000 break;
2001
2002 case CXAvailability_NotAvailable:
2003 fprintf(file, " (unavailable)");
2004 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002005
2006 case CXAvailability_NotAccessible:
2007 fprintf(file, " (inaccessible)");
2008 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002009 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002010
2011 annotationCount = clang_getCompletionNumAnnotations(
2012 completion_result->CompletionString);
2013 if (annotationCount) {
2014 unsigned i;
2015 fprintf(file, " (");
2016 for (i = 0; i < annotationCount; ++i) {
2017 if (i != 0)
2018 fprintf(file, ", ");
Vedant Kumarf27d2272016-04-03 00:54:46 +00002019 Annotation =
2020 clang_getCompletionAnnotation(completion_result->CompletionString, i);
2021 fprintf(file, "\"%s\"", clang_getCString(Annotation));
2022 clang_disposeString(Annotation);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002023 }
2024 fprintf(file, ")");
2025 }
2026
Douglas Gregor78254c82012-03-27 23:34:16 +00002027 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2028 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2029 &ParentKind);
2030 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002031 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002032 fprintf(file, " (parent: %s '%s')",
2033 clang_getCString(KindSpelling),
2034 clang_getCString(ParentName));
2035 clang_disposeString(KindSpelling);
2036 }
2037 clang_disposeString(ParentName);
2038 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002039
2040 BriefComment = clang_getCompletionBriefComment(
2041 completion_result->CompletionString);
2042 BriefCommentCString = clang_getCString(BriefComment);
2043 if (BriefCommentCString && *BriefCommentCString != '\0') {
2044 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2045 }
2046 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002047
Douglas Gregorf757a122010-08-23 23:00:57 +00002048 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002049}
2050
Douglas Gregor21325842011-07-07 16:03:39 +00002051void print_completion_contexts(unsigned long long contexts, FILE *file) {
2052 fprintf(file, "Completion contexts:\n");
2053 if (contexts == CXCompletionContext_Unknown) {
2054 fprintf(file, "Unknown\n");
2055 }
2056 if (contexts & CXCompletionContext_AnyType) {
2057 fprintf(file, "Any type\n");
2058 }
2059 if (contexts & CXCompletionContext_AnyValue) {
2060 fprintf(file, "Any value\n");
2061 }
2062 if (contexts & CXCompletionContext_ObjCObjectValue) {
2063 fprintf(file, "Objective-C object value\n");
2064 }
2065 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2066 fprintf(file, "Objective-C selector value\n");
2067 }
2068 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2069 fprintf(file, "C++ class type value\n");
2070 }
2071 if (contexts & CXCompletionContext_DotMemberAccess) {
2072 fprintf(file, "Dot member access\n");
2073 }
2074 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2075 fprintf(file, "Arrow member access\n");
2076 }
2077 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2078 fprintf(file, "Objective-C property access\n");
2079 }
2080 if (contexts & CXCompletionContext_EnumTag) {
2081 fprintf(file, "Enum tag\n");
2082 }
2083 if (contexts & CXCompletionContext_UnionTag) {
2084 fprintf(file, "Union tag\n");
2085 }
2086 if (contexts & CXCompletionContext_StructTag) {
2087 fprintf(file, "Struct tag\n");
2088 }
2089 if (contexts & CXCompletionContext_ClassTag) {
2090 fprintf(file, "Class name\n");
2091 }
2092 if (contexts & CXCompletionContext_Namespace) {
2093 fprintf(file, "Namespace or namespace alias\n");
2094 }
2095 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2096 fprintf(file, "Nested name specifier\n");
2097 }
2098 if (contexts & CXCompletionContext_ObjCInterface) {
2099 fprintf(file, "Objective-C interface\n");
2100 }
2101 if (contexts & CXCompletionContext_ObjCProtocol) {
2102 fprintf(file, "Objective-C protocol\n");
2103 }
2104 if (contexts & CXCompletionContext_ObjCCategory) {
2105 fprintf(file, "Objective-C category\n");
2106 }
2107 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2108 fprintf(file, "Objective-C instance method\n");
2109 }
2110 if (contexts & CXCompletionContext_ObjCClassMessage) {
2111 fprintf(file, "Objective-C class method\n");
2112 }
2113 if (contexts & CXCompletionContext_ObjCSelectorName) {
2114 fprintf(file, "Objective-C selector name\n");
2115 }
2116 if (contexts & CXCompletionContext_MacroName) {
2117 fprintf(file, "Macro name\n");
2118 }
2119 if (contexts & CXCompletionContext_NaturalLanguage) {
2120 fprintf(file, "Natural language\n");
2121 }
2122}
2123
Douglas Gregor47815d52010-07-12 18:38:41 +00002124int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002125 const char *input = argv[1];
2126 char *filename = 0;
2127 unsigned line;
2128 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002129 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002130 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002131 struct CXUnsavedFile *unsaved_files = 0;
2132 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002133 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002134 enum CXErrorCode Err;
2135 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002136 unsigned I, Repeats = 1;
2137 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2138
2139 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2140 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002141 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2142 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002143
Douglas Gregor47815d52010-07-12 18:38:41 +00002144 if (timing_only)
2145 input += strlen("-code-completion-timing=");
2146 else
2147 input += strlen("-code-completion-at=");
2148
Ted Kremenek29004672010-02-17 00:41:32 +00002149 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002150 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002151 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002152
Douglas Gregor9485bf92009-12-02 09:21:34 +00002153 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2154 return -1;
2155
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002156 CIdx = clang_createIndex(0, 0);
2157
2158 if (getenv("CINDEXTEST_EDITING"))
2159 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002160
2161 Err = clang_parseTranslationUnit2(CIdx, 0,
2162 argv + num_unsaved_files + 2,
2163 argc - num_unsaved_files - 2,
2164 0, 0, getDefaultParsingOptions(), &TU);
2165 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002166 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002167 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002168 return 1;
2169 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002170
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002171 Err = clang_reparseTranslationUnit(TU, 0, 0,
2172 clang_defaultReparseOptions(TU));
2173
2174 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002175 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002176 describeLibclangFailure(Err);
2177 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002178 return 1;
2179 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002180
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002181 for (I = 0; I != Repeats; ++I) {
2182 results = clang_codeCompleteAt(TU, filename, line, column,
2183 unsaved_files, num_unsaved_files,
2184 completionOptions);
2185 if (!results) {
2186 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002187 return 1;
2188 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002189 if (I != Repeats-1)
2190 clang_disposeCodeCompleteResults(results);
2191 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002192
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002193 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002194 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002195 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002196 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002197 CXString objCSelector;
2198 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002199 if (!timing_only) {
2200 /* Sort the code-completion results based on the typed text. */
2201 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2202
Douglas Gregor47815d52010-07-12 18:38:41 +00002203 for (i = 0; i != n; ++i)
2204 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002205 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002206 n = clang_codeCompleteGetNumDiagnostics(results);
2207 for (i = 0; i != n; ++i) {
2208 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2209 PrintDiagnostic(diag);
2210 clang_disposeDiagnostic(diag);
2211 }
Douglas Gregor21325842011-07-07 16:03:39 +00002212
2213 contexts = clang_codeCompleteGetContexts(results);
2214 print_completion_contexts(contexts, stdout);
2215
Douglas Gregorea777402011-07-26 15:24:30 +00002216 containerKind = clang_codeCompleteGetContainerKind(results,
2217 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002218
2219 if (containerKind != CXCursor_InvalidCode) {
2220 /* We have found a container */
2221 CXString containerUSR, containerKindSpelling;
2222 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2223 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2224 clang_disposeString(containerKindSpelling);
2225
2226 if (containerIsIncomplete) {
2227 printf("Container is incomplete\n");
2228 }
2229 else {
2230 printf("Container is complete\n");
2231 }
2232
2233 containerUSR = clang_codeCompleteGetContainerUSR(results);
2234 printf("Container USR: %s\n", clang_getCString(containerUSR));
2235 clang_disposeString(containerUSR);
2236 }
2237
Douglas Gregorea777402011-07-26 15:24:30 +00002238 objCSelector = clang_codeCompleteGetObjCSelector(results);
2239 selectorString = clang_getCString(objCSelector);
2240 if (selectorString && strlen(selectorString) > 0) {
2241 printf("Objective-C selector: %s\n", selectorString);
2242 }
2243 clang_disposeString(objCSelector);
2244
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002245 clang_disposeCodeCompleteResults(results);
2246 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002247 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002248 clang_disposeIndex(CIdx);
2249 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002250
Douglas Gregor9485bf92009-12-02 09:21:34 +00002251 free_remapped_files(unsaved_files, num_unsaved_files);
2252
Ted Kremenekef3339b2009-11-17 18:09:14 +00002253 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002254}
2255
Douglas Gregor082c3e62010-01-15 19:40:17 +00002256typedef struct {
2257 char *filename;
2258 unsigned line;
2259 unsigned column;
2260} CursorSourceLocation;
2261
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002262typedef void (*cursor_handler_t)(CXCursor cursor);
2263
2264static int inspect_cursor_at(int argc, const char **argv,
2265 const char *locations_flag,
2266 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002267 CXIndex CIdx;
2268 int errorCode;
2269 struct CXUnsavedFile *unsaved_files = 0;
2270 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002271 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002272 CXTranslationUnit TU;
2273 CXCursor Cursor;
2274 CursorSourceLocation *Locations = 0;
2275 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002276 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002277 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002278
Ted Kremenek29004672010-02-17 00:41:32 +00002279 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002280 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002281 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002282
Douglas Gregor082c3e62010-01-15 19:40:17 +00002283 /* Parse the locations. */
2284 assert(NumLocations > 0 && "Unable to count locations?");
2285 Locations = (CursorSourceLocation *)malloc(
2286 NumLocations * sizeof(CursorSourceLocation));
2287 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002288 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002289 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2290 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002291 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002292 return errorCode;
2293 }
Ted Kremenek29004672010-02-17 00:41:32 +00002294
2295 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002296 &num_unsaved_files))
2297 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002298
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002299 if (getenv("CINDEXTEST_EDITING"))
2300 Repeats = 5;
2301
2302 /* Parse the translation unit. When we're testing clang_getCursor() after
2303 reparsing, don't remap unsaved files until the second parse. */
2304 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002305 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2306 argv + num_unsaved_files + 1 + NumLocations,
2307 argc - num_unsaved_files - 2 - NumLocations,
2308 unsaved_files,
2309 Repeats > 1? 0 : num_unsaved_files,
2310 getDefaultParsingOptions(), &TU);
2311 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002312 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002313 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002314 return -1;
2315 }
Ted Kremenek29004672010-02-17 00:41:32 +00002316
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002317 if (checkForErrors(TU) != 0)
2318 return -1;
2319
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002320 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002321 if (Repeats > 1) {
2322 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2323 clang_defaultReparseOptions(TU));
2324 if (Err != CXError_Success) {
2325 describeLibclangFailure(Err);
2326 clang_disposeTranslationUnit(TU);
2327 return 1;
2328 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002329 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002330
2331 if (checkForErrors(TU) != 0)
2332 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002333
2334 for (Loc = 0; Loc < NumLocations; ++Loc) {
2335 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2336 if (!file)
2337 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002338
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002339 Cursor = clang_getCursor(TU,
2340 clang_getLocation(TU, file, Locations[Loc].line,
2341 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002342
2343 if (checkForErrors(TU) != 0)
2344 return -1;
2345
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002346 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002347 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002348 free(Locations[Loc].filename);
2349 }
2350 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002351 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002352
Douglas Gregor33cdd812010-02-18 18:08:43 +00002353 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002354 clang_disposeTranslationUnit(TU);
2355 clang_disposeIndex(CIdx);
2356 free(Locations);
2357 free_remapped_files(unsaved_files, num_unsaved_files);
2358 return 0;
2359}
2360
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002361static void inspect_print_cursor(CXCursor Cursor) {
2362 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2363 CXCompletionString completionString = clang_getCursorCompletionString(
2364 Cursor);
2365 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2366 CXString Spelling;
2367 const char *cspell;
2368 unsigned line, column;
2369 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2370 printf("%d:%d ", line, column);
2371 PrintCursor(Cursor, NULL);
2372 PrintCursorExtent(Cursor);
2373 Spelling = clang_getCursorSpelling(Cursor);
2374 cspell = clang_getCString(Spelling);
2375 if (cspell && strlen(cspell) != 0) {
2376 unsigned pieceIndex;
2377 printf(" Spelling=%s (", cspell);
2378 for (pieceIndex = 0; ; ++pieceIndex) {
2379 CXSourceRange range =
2380 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2381 if (clang_Range_isNull(range))
2382 break;
2383 PrintRange(range, 0);
2384 }
2385 printf(")");
2386 }
2387 clang_disposeString(Spelling);
2388 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2389 printf(" Selector index=%d",
2390 clang_Cursor_getObjCSelectorIndex(Cursor));
2391 if (clang_Cursor_isDynamicCall(Cursor))
2392 printf(" Dynamic-call");
2393 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2394 CXType T = clang_Cursor_getReceiverType(Cursor);
2395 CXString S = clang_getTypeKindSpelling(T.kind);
2396 printf(" Receiver-type=%s", clang_getCString(S));
2397 clang_disposeString(S);
2398 }
2399
2400 {
2401 CXModule mod = clang_Cursor_getModule(Cursor);
2402 CXFile astFile;
2403 CXString name, astFilename;
2404 unsigned i, numHeaders;
2405 if (mod) {
2406 astFile = clang_Module_getASTFile(mod);
2407 astFilename = clang_getFileName(astFile);
2408 name = clang_Module_getFullName(mod);
2409 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2410 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2411 clang_getCString(name), clang_getCString(astFilename),
2412 clang_Module_isSystem(mod), numHeaders);
2413 clang_disposeString(name);
2414 clang_disposeString(astFilename);
2415 for (i = 0; i < numHeaders; ++i) {
2416 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2417 CXString filename = clang_getFileName(file);
2418 printf("\n%s", clang_getCString(filename));
2419 clang_disposeString(filename);
2420 }
2421 }
2422 }
2423
2424 if (completionString != NULL) {
2425 printf("\nCompletion string: ");
2426 print_completion_string(completionString, stdout);
2427 }
2428 printf("\n");
2429}
2430
2431static void display_evaluate_results(CXEvalResult result) {
2432 switch (clang_EvalResult_getKind(result)) {
2433 case CXEval_Int:
2434 {
2435 int val = clang_EvalResult_getAsInt(result);
2436 printf("Kind: Int , Value: %d", val);
2437 break;
2438 }
2439 case CXEval_Float:
2440 {
2441 double val = clang_EvalResult_getAsDouble(result);
2442 printf("Kind: Float , Value: %f", val);
2443 break;
2444 }
2445 case CXEval_ObjCStrLiteral:
2446 {
2447 const char* str = clang_EvalResult_getAsStr(result);
2448 printf("Kind: ObjCString , Value: %s", str);
2449 break;
2450 }
2451 case CXEval_StrLiteral:
2452 {
2453 const char* str = clang_EvalResult_getAsStr(result);
2454 printf("Kind: CString , Value: %s", str);
2455 break;
2456 }
2457 case CXEval_CFStr:
2458 {
2459 const char* str = clang_EvalResult_getAsStr(result);
2460 printf("Kind: CFString , Value: %s", str);
2461 break;
2462 }
2463 default:
2464 printf("Unexposed");
2465 break;
2466 }
2467}
2468
2469static void inspect_evaluate_cursor(CXCursor Cursor) {
2470 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2471 CXString Spelling;
2472 const char *cspell;
2473 unsigned line, column;
2474 CXEvalResult ER;
2475
2476 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2477 printf("%d:%d ", line, column);
2478 PrintCursor(Cursor, NULL);
2479 PrintCursorExtent(Cursor);
2480 Spelling = clang_getCursorSpelling(Cursor);
2481 cspell = clang_getCString(Spelling);
2482 if (cspell && strlen(cspell) != 0) {
2483 unsigned pieceIndex;
2484 printf(" Spelling=%s (", cspell);
2485 for (pieceIndex = 0; ; ++pieceIndex) {
2486 CXSourceRange range =
2487 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2488 if (clang_Range_isNull(range))
2489 break;
2490 PrintRange(range, 0);
2491 }
2492 printf(")");
2493 }
2494 clang_disposeString(Spelling);
2495
2496 ER = clang_Cursor_Evaluate(Cursor);
2497 if (!ER) {
2498 printf("Not Evaluatable");
2499 } else {
2500 display_evaluate_results(ER);
2501 clang_EvalResult_dispose(ER);
2502 }
2503 printf("\n");
2504}
2505
2506static void inspect_macroinfo_cursor(CXCursor Cursor) {
2507 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2508 CXString Spelling;
2509 const char *cspell;
2510 unsigned line, column;
2511 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2512 printf("%d:%d ", line, column);
2513 PrintCursor(Cursor, NULL);
2514 PrintCursorExtent(Cursor);
2515 Spelling = clang_getCursorSpelling(Cursor);
2516 cspell = clang_getCString(Spelling);
2517 if (cspell && strlen(cspell) != 0) {
2518 unsigned pieceIndex;
2519 printf(" Spelling=%s (", cspell);
2520 for (pieceIndex = 0; ; ++pieceIndex) {
2521 CXSourceRange range =
2522 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2523 if (clang_Range_isNull(range))
2524 break;
2525 PrintRange(range, 0);
2526 }
2527 printf(")");
2528 }
2529 clang_disposeString(Spelling);
2530
2531 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2532 printf("[builtin macro]");
2533 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2534 printf("[function macro]");
2535 }
2536 printf("\n");
2537}
2538
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002539static enum CXVisitorResult findFileRefsVisit(void *context,
2540 CXCursor cursor, CXSourceRange range) {
2541 if (clang_Range_isNull(range))
2542 return CXVisit_Continue;
2543
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002544 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002545 PrintRange(range, "");
2546 printf("\n");
2547 return CXVisit_Continue;
2548}
2549
2550static int find_file_refs_at(int argc, const char **argv) {
2551 CXIndex CIdx;
2552 int errorCode;
2553 struct CXUnsavedFile *unsaved_files = 0;
2554 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002555 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002556 CXTranslationUnit TU;
2557 CXCursor Cursor;
2558 CursorSourceLocation *Locations = 0;
2559 unsigned NumLocations = 0, Loc;
2560 unsigned Repeats = 1;
2561 unsigned I;
2562
2563 /* Count the number of locations. */
2564 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2565 ++NumLocations;
2566
2567 /* Parse the locations. */
2568 assert(NumLocations > 0 && "Unable to count locations?");
2569 Locations = (CursorSourceLocation *)malloc(
2570 NumLocations * sizeof(CursorSourceLocation));
2571 for (Loc = 0; Loc < NumLocations; ++Loc) {
2572 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2573 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2574 &Locations[Loc].line,
2575 &Locations[Loc].column, 0, 0)))
2576 return errorCode;
2577 }
2578
2579 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2580 &num_unsaved_files))
2581 return -1;
2582
2583 if (getenv("CINDEXTEST_EDITING"))
2584 Repeats = 5;
2585
2586 /* Parse the translation unit. When we're testing clang_getCursor() after
2587 reparsing, don't remap unsaved files until the second parse. */
2588 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002589 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2590 argv + num_unsaved_files + 1 + NumLocations,
2591 argc - num_unsaved_files - 2 - NumLocations,
2592 unsaved_files,
2593 Repeats > 1? 0 : num_unsaved_files,
2594 getDefaultParsingOptions(), &TU);
2595 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002596 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002597 describeLibclangFailure(Err);
2598 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002599 return -1;
2600 }
2601
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002602 if (checkForErrors(TU) != 0)
2603 return -1;
2604
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002605 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002606 if (Repeats > 1) {
2607 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2608 clang_defaultReparseOptions(TU));
2609 if (Err != CXError_Success) {
2610 describeLibclangFailure(Err);
2611 clang_disposeTranslationUnit(TU);
2612 return 1;
2613 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002614 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002615
2616 if (checkForErrors(TU) != 0)
2617 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002618
2619 for (Loc = 0; Loc < NumLocations; ++Loc) {
2620 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2621 if (!file)
2622 continue;
2623
2624 Cursor = clang_getCursor(TU,
2625 clang_getLocation(TU, file, Locations[Loc].line,
2626 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002627
2628 if (checkForErrors(TU) != 0)
2629 return -1;
2630
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002631 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002632 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002633 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002634 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002635 clang_findReferencesInFile(Cursor, file, visitor);
2636 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002637
2638 if (checkForErrors(TU) != 0)
2639 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002640 }
2641 }
2642 }
2643
2644 PrintDiagnostics(TU);
2645 clang_disposeTranslationUnit(TU);
2646 clang_disposeIndex(CIdx);
2647 free(Locations);
2648 free_remapped_files(unsaved_files, num_unsaved_files);
2649 return 0;
2650}
2651
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002652static enum CXVisitorResult findFileIncludesVisit(void *context,
2653 CXCursor cursor, CXSourceRange range) {
2654 PrintCursor(cursor, NULL);
2655 PrintRange(range, "");
2656 printf("\n");
2657 return CXVisit_Continue;
2658}
2659
2660static int find_file_includes_in(int argc, const char **argv) {
2661 CXIndex CIdx;
2662 struct CXUnsavedFile *unsaved_files = 0;
2663 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002664 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002665 CXTranslationUnit TU;
2666 const char **Filenames = 0;
2667 unsigned NumFilenames = 0;
2668 unsigned Repeats = 1;
2669 unsigned I, FI;
2670
2671 /* Count the number of locations. */
2672 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2673 ++NumFilenames;
2674
2675 /* Parse the locations. */
2676 assert(NumFilenames > 0 && "Unable to count filenames?");
2677 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2678 for (I = 0; I < NumFilenames; ++I) {
2679 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2680 /* Copy the file name. */
2681 Filenames[I] = input;
2682 }
2683
2684 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2685 &num_unsaved_files))
2686 return -1;
2687
2688 if (getenv("CINDEXTEST_EDITING"))
2689 Repeats = 2;
2690
2691 /* Parse the translation unit. When we're testing clang_getCursor() after
2692 reparsing, don't remap unsaved files until the second parse. */
2693 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002694 Err = clang_parseTranslationUnit2(
2695 CIdx, argv[argc - 1],
2696 argv + num_unsaved_files + 1 + NumFilenames,
2697 argc - num_unsaved_files - 2 - NumFilenames,
2698 unsaved_files,
2699 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002700
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002701 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002702 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002703 describeLibclangFailure(Err);
2704 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002705 return -1;
2706 }
2707
2708 if (checkForErrors(TU) != 0)
2709 return -1;
2710
2711 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002712 if (Repeats > 1) {
2713 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2714 clang_defaultReparseOptions(TU));
2715 if (Err != CXError_Success) {
2716 describeLibclangFailure(Err);
2717 clang_disposeTranslationUnit(TU);
2718 return 1;
2719 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002720 }
2721
2722 if (checkForErrors(TU) != 0)
2723 return -1;
2724
2725 for (FI = 0; FI < NumFilenames; ++FI) {
2726 CXFile file = clang_getFile(TU, Filenames[FI]);
2727 if (!file)
2728 continue;
2729
2730 if (checkForErrors(TU) != 0)
2731 return -1;
2732
2733 if (I + 1 == Repeats) {
2734 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2735 clang_findIncludesInFile(TU, file, visitor);
2736
2737 if (checkForErrors(TU) != 0)
2738 return -1;
2739 }
2740 }
2741 }
2742
2743 PrintDiagnostics(TU);
2744 clang_disposeTranslationUnit(TU);
2745 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002746 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002747 free_remapped_files(unsaved_files, num_unsaved_files);
2748 return 0;
2749}
2750
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002751#define MAX_IMPORTED_ASTFILES 200
2752
2753typedef struct {
2754 char **filenames;
2755 unsigned num_files;
2756} ImportedASTFilesData;
2757
2758static ImportedASTFilesData *importedASTs_create() {
2759 ImportedASTFilesData *p;
2760 p = malloc(sizeof(ImportedASTFilesData));
2761 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2762 p->num_files = 0;
2763 return p;
2764}
2765
2766static void importedASTs_dispose(ImportedASTFilesData *p) {
2767 unsigned i;
2768 if (!p)
2769 return;
2770
2771 for (i = 0; i < p->num_files; ++i)
2772 free(p->filenames[i]);
2773 free(p->filenames);
2774 free(p);
2775}
2776
2777static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2778 unsigned i;
2779 assert(p && file);
2780 for (i = 0; i < p->num_files; ++i)
2781 if (strcmp(file, p->filenames[i]) == 0)
2782 return;
2783 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2784 p->filenames[p->num_files++] = strdup(file);
2785}
2786
Nico Weberdf686022014-05-07 21:09:42 +00002787typedef struct IndexDataStringList_ {
2788 struct IndexDataStringList_ *next;
2789 char data[1]; /* Dynamically sized. */
2790} IndexDataStringList;
2791
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002792typedef struct {
2793 const char *check_prefix;
2794 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002795 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002796 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002797 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002798 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002799 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002800 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002801} IndexData;
2802
Nico Weberdf686022014-05-07 21:09:42 +00002803static void free_client_data(IndexData *index_data) {
2804 IndexDataStringList *node = index_data->strings;
2805 while (node) {
2806 IndexDataStringList *next = node->next;
2807 free(node);
2808 node = next;
2809 }
2810 index_data->strings = NULL;
2811}
2812
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002813static void printCheck(IndexData *data) {
2814 if (data->check_prefix) {
2815 if (data->first_check_printed) {
2816 printf("// %s-NEXT: ", data->check_prefix);
2817 } else {
2818 printf("// %s : ", data->check_prefix);
2819 data->first_check_printed = 1;
2820 }
2821 }
2822}
2823
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002824static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002825 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002826 printf("%s", clang_getCString(filename));
2827 clang_disposeString(filename);
2828}
2829
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002830static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2831 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002832 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002833 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002834 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002835 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002836 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002837
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002838 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002839 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2840 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002841 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002842 return;
2843 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002844 if (!file) {
2845 printf("<no idxfile>");
2846 return;
2847 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002848 filename = clang_getFileName((CXFile)file);
2849 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002850 if (strcmp(cname, index_data->main_filename) == 0)
2851 isMainFile = 1;
2852 else
2853 isMainFile = 0;
2854 clang_disposeString(filename);
2855
2856 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002857 printCXIndexFile(file);
2858 printf(":");
2859 }
2860 printf("%d:%d", line, column);
2861}
2862
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002863static unsigned digitCount(unsigned val) {
2864 unsigned c = 1;
2865 while (1) {
2866 if (val < 10)
2867 return c;
2868 ++c;
2869 val /= 10;
2870 }
2871}
2872
Nico Weberdf686022014-05-07 21:09:42 +00002873static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2874 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002875 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002876 IndexData *index_data;
2877 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002878 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002879 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002880 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002881 unsigned line, column;
2882
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002883 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002884 if (!name)
2885 name = "<anon-tag>";
2886
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002887 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002888
2889 node =
2890 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2891 digitCount(line) + digitCount(column) + 2);
2892 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002893 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002894
2895 /* Remember string so it can be freed later. */
2896 index_data = (IndexData *)client_data;
2897 node->next = index_data->strings;
2898 index_data->strings = node;
2899
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002900 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002901}
2902
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002903static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2904 CXIdxClientContainer container;
2905 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002906 if (!container)
2907 printf("[<<NULL>>]");
2908 else
2909 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002910}
2911
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002912static const char *getEntityKindString(CXIdxEntityKind kind) {
2913 switch (kind) {
2914 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2915 case CXIdxEntity_Typedef: return "typedef";
2916 case CXIdxEntity_Function: return "function";
2917 case CXIdxEntity_Variable: return "variable";
2918 case CXIdxEntity_Field: return "field";
2919 case CXIdxEntity_EnumConstant: return "enumerator";
2920 case CXIdxEntity_ObjCClass: return "objc-class";
2921 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2922 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002923 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2924 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002925 case CXIdxEntity_ObjCProperty: return "objc-property";
2926 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2927 case CXIdxEntity_Enum: return "enum";
2928 case CXIdxEntity_Struct: return "struct";
2929 case CXIdxEntity_Union: return "union";
2930 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002931 case CXIdxEntity_CXXNamespace: return "namespace";
2932 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2933 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2934 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2935 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2936 case CXIdxEntity_CXXConstructor: return "constructor";
2937 case CXIdxEntity_CXXDestructor: return "destructor";
2938 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2939 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002940 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002941 }
2942 assert(0 && "Garbage entity kind");
2943 return 0;
2944}
2945
2946static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2947 switch (kind) {
2948 case CXIdxEntity_NonTemplate: return "";
2949 case CXIdxEntity_Template: return "-template";
2950 case CXIdxEntity_TemplatePartialSpecialization:
2951 return "-template-partial-spec";
2952 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002953 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002954 assert(0 && "Garbage entity kind");
2955 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002956}
2957
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002958static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2959 switch (kind) {
2960 case CXIdxEntityLang_None: return "<none>";
2961 case CXIdxEntityLang_C: return "C";
2962 case CXIdxEntityLang_ObjC: return "ObjC";
2963 case CXIdxEntityLang_CXX: return "C++";
2964 }
2965 assert(0 && "Garbage language kind");
2966 return 0;
2967}
2968
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002969static void printEntityInfo(const char *cb,
2970 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002971 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002972 const char *name;
2973 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002974 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002975 index_data = (IndexData *)client_data;
2976 printCheck(index_data);
2977
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002978 if (!info) {
2979 printf("%s: <<NULL>>", cb);
2980 return;
2981 }
2982
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002983 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002984 if (!name)
2985 name = "<anon-tag>";
2986
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002987 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2988 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002989 printf(" | name: %s", name);
2990 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002991 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002992
2993 for (i = 0; i != info->numAttributes; ++i) {
2994 const CXIdxAttrInfo *Attr = info->attributes[i];
2995 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002996 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002997 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002998}
2999
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003000static void printBaseClassInfo(CXClientData client_data,
3001 const CXIdxBaseClassInfo *info) {
3002 printEntityInfo(" <base>", client_data, info->base);
3003 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003004 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003005 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003006 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003007}
3008
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003009static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3010 CXClientData client_data) {
3011 unsigned i;
3012 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3013 printEntityInfo(" <protocol>", client_data,
3014 ProtoInfo->protocols[i]->protocol);
3015 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003016 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003017 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003018 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003019 printf("\n");
3020 }
3021}
3022
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003023static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003024 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003025 CXString str;
3026 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003027 unsigned numDiags, i;
3028 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003029 IndexData *index_data;
3030 index_data = (IndexData *)client_data;
3031 printCheck(index_data);
3032
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003033 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3034 for (i = 0; i != numDiags; ++i) {
3035 diag = clang_getDiagnosticInSet(diagSet, i);
3036 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3037 cstr = clang_getCString(str);
3038 printf("[diagnostic]: %s\n", cstr);
3039 clang_disposeString(str);
3040
3041 if (getenv("CINDEXTEST_FAILONERROR") &&
3042 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3043 index_data->fail_for_error = 1;
3044 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003045 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003046}
3047
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003048static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3049 CXFile file, void *reserved) {
3050 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003051 CXString filename;
3052
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003053 index_data = (IndexData *)client_data;
3054 printCheck(index_data);
3055
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003056 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003057 index_data->main_filename = clang_getCString(filename);
3058 clang_disposeString(filename);
3059
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003060 printf("[enteredMainFile]: ");
3061 printCXIndexFile((CXIdxClientFile)file);
3062 printf("\n");
3063
3064 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003065}
3066
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003067static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003068 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003069 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003070 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003071 index_data = (IndexData *)client_data;
3072 printCheck(index_data);
3073
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003074 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003075 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003076 printf(" | name: \"%s\"", info->filename);
3077 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003078 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003079 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003080 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003081
3082 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3083 if (Mod) {
3084 CXString str = clang_Module_getFullName(Mod);
3085 const char *cstr = clang_getCString(str);
3086 printf(" | module: %s", cstr);
3087 clang_disposeString(str);
3088 }
3089
3090 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003091
3092 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003093}
3094
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003095static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3096 const CXIdxImportedASTFileInfo *info) {
3097 IndexData *index_data;
3098 index_data = (IndexData *)client_data;
3099 printCheck(index_data);
3100
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003101 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003102 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003103 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3104 clang_disposeString(filename);
3105 }
3106
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003107 printf("[importedASTFile]: ");
3108 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003109 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003110 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003111 printf(" | loc: ");
3112 printCXIndexLoc(info->loc, client_data);
3113 printf(" | name: \"%s\"", clang_getCString(name));
3114 printf(" | isImplicit: %d\n", info->isImplicit);
3115 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003116 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003117 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003118 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003119 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003120
3121 return (CXIdxClientFile)info->file;
3122}
3123
Nico Weber8d19dff2014-05-07 21:05:22 +00003124static CXIdxClientContainer
3125index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003126 IndexData *index_data;
3127 index_data = (IndexData *)client_data;
3128 printCheck(index_data);
3129
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003130 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003131 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003132}
3133
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003134static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003135 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003136 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003137 const CXIdxObjCCategoryDeclInfo *CatInfo;
3138 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003139 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003140 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003141 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003142 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003143 index_data = (IndexData *)client_data;
3144
3145 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3146 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003147 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003148 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003149 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003150 printf(" | semantic-container: ");
3151 printCXIndexContainer(info->semanticContainer);
3152 printf(" | lexical-container: ");
3153 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003154 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003155 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003156 if (info->flags & CXIdxDeclFlag_Skipped) {
3157 assert(!info->isContainer);
3158 printf(" | isContainer: skipped");
3159 } else {
3160 printf(" | isContainer: %d", info->isContainer);
3161 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003162 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003163
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003164 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003165 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003166 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003167 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003168 printf("\n");
3169 }
3170
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003171 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3172 const char *kindName = 0;
3173 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3174 switch (K) {
3175 case CXIdxObjCContainer_ForwardRef:
3176 kindName = "forward-ref"; break;
3177 case CXIdxObjCContainer_Interface:
3178 kindName = "interface"; break;
3179 case CXIdxObjCContainer_Implementation:
3180 kindName = "implementation"; break;
3181 }
3182 printCheck(index_data);
3183 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3184 }
3185
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003186 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003187 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3188 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003189 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003190 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003191 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003192 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003193 printf("\n");
3194 }
3195
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003196 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3197 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003198 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003199 printf("\n");
3200 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003201 }
3202
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003203 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3204 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003205 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003206
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003207 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3208 if (PropInfo->getter) {
3209 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3210 printf("\n");
3211 }
3212 if (PropInfo->setter) {
3213 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3214 printf("\n");
3215 }
3216 }
3217
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003218 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3219 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3220 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3221 printf("\n");
3222 }
3223 }
3224
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003225 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003226 clang_index_setClientContainer(
3227 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003228 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003229}
3230
3231static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003232 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003233 printEntityInfo("[indexEntityReference]", client_data,
3234 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003235 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003236 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003237 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003238 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003239 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003240 printf(" | container: ");
3241 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003242 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003243 switch (info->kind) {
3244 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003245 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003246 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003247 printf("\n");
3248}
3249
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003250static int index_abortQuery(CXClientData client_data, void *reserved) {
3251 IndexData *index_data;
3252 index_data = (IndexData *)client_data;
3253 return index_data->abort;
3254}
3255
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003256static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003257 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003258 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003259 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003260 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003261 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003262 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003263 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003264 index_indexEntityReference
3265};
3266
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003267static unsigned getIndexOptions(void) {
3268 unsigned index_opts;
3269 index_opts = 0;
3270 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3271 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3272 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3273 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003274 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3275 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003276
3277 return index_opts;
3278}
3279
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003280static int index_compile_args(int num_args, const char **args,
3281 CXIndexAction idxAction,
3282 ImportedASTFilesData *importedASTs,
3283 const char *check_prefix) {
3284 IndexData index_data;
3285 unsigned index_opts;
3286 int result;
3287
3288 if (num_args == 0) {
3289 fprintf(stderr, "no compiler arguments\n");
3290 return -1;
3291 }
3292
3293 index_data.check_prefix = check_prefix;
3294 index_data.first_check_printed = 0;
3295 index_data.fail_for_error = 0;
3296 index_data.abort = 0;
3297 index_data.main_filename = "";
3298 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003299 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003300 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003301
3302 index_opts = getIndexOptions();
3303 result = clang_indexSourceFile(idxAction, &index_data,
3304 &IndexCB,sizeof(IndexCB), index_opts,
3305 0, args, num_args, 0, 0, 0,
3306 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003307 if (result != CXError_Success)
3308 describeLibclangFailure(result);
3309
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003310 if (index_data.fail_for_error)
3311 result = -1;
3312
Nico Weberdf686022014-05-07 21:09:42 +00003313 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003314 return result;
3315}
3316
3317static int index_ast_file(const char *ast_file,
3318 CXIndex Idx,
3319 CXIndexAction idxAction,
3320 ImportedASTFilesData *importedASTs,
3321 const char *check_prefix) {
3322 CXTranslationUnit TU;
3323 IndexData index_data;
3324 unsigned index_opts;
3325 int result;
3326
3327 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3328 return -1;
3329
3330 index_data.check_prefix = check_prefix;
3331 index_data.first_check_printed = 0;
3332 index_data.fail_for_error = 0;
3333 index_data.abort = 0;
3334 index_data.main_filename = "";
3335 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003336 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003337 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003338
3339 index_opts = getIndexOptions();
3340 result = clang_indexTranslationUnit(idxAction, &index_data,
3341 &IndexCB,sizeof(IndexCB),
3342 index_opts, TU);
3343 if (index_data.fail_for_error)
3344 result = -1;
3345
3346 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003347 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003348 return result;
3349}
3350
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003351static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003352 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003353 CXIndex Idx;
3354 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003355 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003356 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003357
3358 check_prefix = 0;
3359 if (argc > 0) {
3360 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3361 check_prefix = argv[0] + strlen("-check-prefix=");
3362 ++argv;
3363 --argc;
3364 }
3365 }
3366
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003367 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003368 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003369 fprintf(stderr, "Could not create Index\n");
3370 return 1;
3371 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003372 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003373 importedASTs = 0;
3374 if (full)
3375 importedASTs = importedASTs_create();
3376
3377 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3378 if (result != 0)
3379 goto finished;
3380
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003381 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003382 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003383 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3384 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3385 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003386 }
3387 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003388
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003389finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003390 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003391 clang_IndexAction_dispose(idxAction);
3392 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003393 return result;
3394}
3395
3396static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003397 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003398 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003399 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003400 int result;
3401
3402 check_prefix = 0;
3403 if (argc > 0) {
3404 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3405 check_prefix = argv[0] + strlen("-check-prefix=");
3406 ++argv;
3407 --argc;
3408 }
3409 }
3410
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003411 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003412 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003413 fprintf(stderr, "Could not create Index\n");
3414 return 1;
3415 }
3416 idxAction = clang_IndexAction_create(Idx);
3417
3418 result = index_ast_file(argv[0], Idx, idxAction,
3419 /*importedASTs=*/0, check_prefix);
3420
3421 clang_IndexAction_dispose(idxAction);
3422 clang_disposeIndex(Idx);
3423 return result;
3424}
3425
3426static int index_compile_db(int argc, const char **argv) {
3427 const char *check_prefix;
3428 CXIndex Idx;
3429 CXIndexAction idxAction;
3430 int errorCode = 0;
3431
3432 check_prefix = 0;
3433 if (argc > 0) {
3434 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3435 check_prefix = argv[0] + strlen("-check-prefix=");
3436 ++argv;
3437 --argc;
3438 }
3439 }
3440
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003441 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003442 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003443 return -1;
3444 }
3445
3446 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003447 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003448 fprintf(stderr, "Could not create Index\n");
3449 return 1;
3450 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003451 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003452
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003453 {
3454 const char *database = argv[0];
3455 CXCompilationDatabase db = 0;
3456 CXCompileCommands CCmds = 0;
3457 CXCompileCommand CCmd;
3458 CXCompilationDatabase_Error ec;
3459 CXString wd;
3460#define MAX_COMPILE_ARGS 512
3461 CXString cxargs[MAX_COMPILE_ARGS];
3462 const char *args[MAX_COMPILE_ARGS];
3463 char *tmp;
3464 unsigned len;
3465 char *buildDir;
3466 int i, a, numCmds, numArgs;
3467
3468 len = strlen(database);
3469 tmp = (char *) malloc(len+1);
3470 memcpy(tmp, database, len+1);
3471 buildDir = dirname(tmp);
3472
3473 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3474
3475 if (db) {
3476
3477 if (ec!=CXCompilationDatabase_NoError) {
3478 printf("unexpected error %d code while loading compilation database\n", ec);
3479 errorCode = -1;
3480 goto cdb_end;
3481 }
3482
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003483 if (chdir(buildDir) != 0) {
3484 printf("Could not chdir to %s\n", buildDir);
3485 errorCode = -1;
3486 goto cdb_end;
3487 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003488
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003489 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003490 if (!CCmds) {
3491 printf("compilation db is empty\n");
3492 errorCode = -1;
3493 goto cdb_end;
3494 }
3495
3496 numCmds = clang_CompileCommands_getSize(CCmds);
3497
3498 if (numCmds==0) {
3499 fprintf(stderr, "should not get an empty compileCommand set\n");
3500 errorCode = -1;
3501 goto cdb_end;
3502 }
3503
3504 for (i=0; i<numCmds && errorCode == 0; ++i) {
3505 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3506
3507 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003508 if (chdir(clang_getCString(wd)) != 0) {
3509 printf("Could not chdir to %s\n", clang_getCString(wd));
3510 errorCode = -1;
3511 goto cdb_end;
3512 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003513 clang_disposeString(wd);
3514
3515 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3516 if (numArgs > MAX_COMPILE_ARGS){
3517 fprintf(stderr, "got more compile arguments than maximum\n");
3518 errorCode = -1;
3519 goto cdb_end;
3520 }
3521 for (a=0; a<numArgs; ++a) {
3522 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3523 args[a] = clang_getCString(cxargs[a]);
3524 }
3525
3526 errorCode = index_compile_args(numArgs, args, idxAction,
3527 /*importedASTs=*/0, check_prefix);
3528
3529 for (a=0; a<numArgs; ++a)
3530 clang_disposeString(cxargs[a]);
3531 }
3532 } else {
3533 printf("database loading failed with error code %d.\n", ec);
3534 errorCode = -1;
3535 }
3536
3537 cdb_end:
3538 clang_CompileCommands_dispose(CCmds);
3539 clang_CompilationDatabase_dispose(db);
3540 free(tmp);
3541
3542 }
3543
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003544 clang_IndexAction_dispose(idxAction);
3545 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003546 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003547}
3548
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003549int perform_token_annotation(int argc, const char **argv) {
3550 const char *input = argv[1];
3551 char *filename = 0;
3552 unsigned line, second_line;
3553 unsigned column, second_column;
3554 CXIndex CIdx;
3555 CXTranslationUnit TU = 0;
3556 int errorCode;
3557 struct CXUnsavedFile *unsaved_files = 0;
3558 int num_unsaved_files = 0;
3559 CXToken *tokens;
3560 unsigned num_tokens;
3561 CXSourceRange range;
3562 CXSourceLocation startLoc, endLoc;
3563 CXFile file = 0;
3564 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003565 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003566 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003567 unsigned i;
3568
3569 input += strlen("-test-annotate-tokens=");
3570 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3571 &second_line, &second_column)))
3572 return errorCode;
3573
Richard Smith1ea42eb2012-07-05 08:20:49 +00003574 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3575 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003576 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003577 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003578
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003579 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003580 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3581 argv + num_unsaved_files + 2,
3582 argc - num_unsaved_files - 3,
3583 unsaved_files,
3584 num_unsaved_files,
3585 getDefaultParsingOptions(), &TU);
3586 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003587 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003588 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003589 clang_disposeIndex(CIdx);
3590 free(filename);
3591 free_remapped_files(unsaved_files, num_unsaved_files);
3592 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003593 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003594 errorCode = 0;
3595
Richard Smith1ea42eb2012-07-05 08:20:49 +00003596 if (checkForErrors(TU) != 0) {
3597 errorCode = -1;
3598 goto teardown;
3599 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003600
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003601 if (getenv("CINDEXTEST_EDITING")) {
3602 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003603 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3604 clang_defaultReparseOptions(TU));
3605 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003606 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003607 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003608 errorCode = -1;
3609 goto teardown;
3610 }
3611 }
3612 }
3613
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003614 if (checkForErrors(TU) != 0) {
3615 errorCode = -1;
3616 goto teardown;
3617 }
3618
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003619 file = clang_getFile(TU, filename);
3620 if (!file) {
3621 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3622 errorCode = -1;
3623 goto teardown;
3624 }
3625
3626 startLoc = clang_getLocation(TU, file, line, column);
3627 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003628 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003629 column);
3630 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003631 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003632 }
3633
3634 endLoc = clang_getLocation(TU, file, second_line, second_column);
3635 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003636 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003637 second_line, second_column);
3638 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003639 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003640 }
3641
3642 range = clang_getRange(startLoc, endLoc);
3643 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003644
3645 if (checkForErrors(TU) != 0) {
3646 errorCode = -1;
3647 goto teardown;
3648 }
3649
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003650 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3651 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003652
3653 if (checkForErrors(TU) != 0) {
3654 errorCode = -1;
3655 goto teardown;
3656 }
3657
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003658 skipped_ranges = clang_getSkippedRanges(TU, file);
3659 for (i = 0; i != skipped_ranges->count; ++i) {
3660 unsigned start_line, start_column, end_line, end_column;
3661 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3662 0, &start_line, &start_column, 0);
3663 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3664 0, &end_line, &end_column, 0);
3665 printf("Skipping: ");
3666 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3667 printf("\n");
3668 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003669 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003670
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003671 for (i = 0; i != num_tokens; ++i) {
3672 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003673 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3674 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003675 unsigned start_line, start_column, end_line, end_column;
3676
3677 switch (clang_getTokenKind(tokens[i])) {
3678 case CXToken_Punctuation: kind = "Punctuation"; break;
3679 case CXToken_Keyword: kind = "Keyword"; break;
3680 case CXToken_Identifier: kind = "Identifier"; break;
3681 case CXToken_Literal: kind = "Literal"; break;
3682 case CXToken_Comment: kind = "Comment"; break;
3683 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003684 clang_getSpellingLocation(clang_getRangeStart(extent),
3685 0, &start_line, &start_column, 0);
3686 clang_getSpellingLocation(clang_getRangeEnd(extent),
3687 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003688 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003689 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003690 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003691 if (!clang_isInvalid(cursors[i].kind)) {
3692 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003693 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003694 }
3695 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003696 }
3697 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003698 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003699
3700 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003701 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003702 clang_disposeTranslationUnit(TU);
3703 clang_disposeIndex(CIdx);
3704 free(filename);
3705 free_remapped_files(unsaved_files, num_unsaved_files);
3706 return errorCode;
3707}
3708
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003709static int
3710perform_test_compilation_db(const char *database, int argc, const char **argv) {
3711 CXCompilationDatabase db;
3712 CXCompileCommands CCmds;
3713 CXCompileCommand CCmd;
3714 CXCompilationDatabase_Error ec;
3715 CXString wd;
3716 CXString arg;
3717 int errorCode = 0;
3718 char *tmp;
3719 unsigned len;
3720 char *buildDir;
3721 int i, j, a, numCmds, numArgs;
3722
3723 len = strlen(database);
3724 tmp = (char *) malloc(len+1);
3725 memcpy(tmp, database, len+1);
3726 buildDir = dirname(tmp);
3727
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003728 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003729
3730 if (db) {
3731
3732 if (ec!=CXCompilationDatabase_NoError) {
3733 printf("unexpected error %d code while loading compilation database\n", ec);
3734 errorCode = -1;
3735 goto cdb_end;
3736 }
3737
3738 for (i=0; i<argc && errorCode==0; ) {
3739 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003740 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003741
3742 if (!CCmds) {
3743 printf("file %s not found in compilation db\n", argv[i+1]);
3744 errorCode = -1;
3745 break;
3746 }
3747
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003748 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003749
3750 if (numCmds==0) {
3751 fprintf(stderr, "should not get an empty compileCommand set for file"
3752 " '%s'\n", argv[i+1]);
3753 errorCode = -1;
3754 break;
3755 }
3756
3757 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003758 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003759
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003760 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003761 printf("workdir:'%s'", clang_getCString(wd));
3762 clang_disposeString(wd);
3763
3764 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003765 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003766 for (a=0; a<numArgs; ++a) {
3767 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003768 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003769 printf("%s", clang_getCString(arg));
3770 clang_disposeString(arg);
3771 }
3772 printf("'\n");
3773 }
3774
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003775 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003776
3777 i += 2;
3778 }
3779 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003780 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003781 } else {
3782 printf("database loading failed with error code %d.\n", ec);
3783 errorCode = -1;
3784 }
3785
3786cdb_end:
3787 free(tmp);
3788
3789 return errorCode;
3790}
3791
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003792/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003793/* USR printing. */
3794/******************************************************************************/
3795
3796static int insufficient_usr(const char *kind, const char *usage) {
3797 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3798 return 1;
3799}
3800
3801static unsigned isUSR(const char *s) {
3802 return s[0] == 'c' && s[1] == ':';
3803}
3804
3805static int not_usr(const char *s, const char *arg) {
3806 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3807 return 1;
3808}
3809
3810static void print_usr(CXString usr) {
3811 const char *s = clang_getCString(usr);
3812 printf("%s\n", s);
3813 clang_disposeString(usr);
3814}
3815
3816static void display_usrs() {
3817 fprintf(stderr, "-print-usrs options:\n"
3818 " ObjCCategory <class name> <category name>\n"
3819 " ObjCClass <class name>\n"
3820 " ObjCIvar <ivar name> <class USR>\n"
3821 " ObjCMethod <selector> [0=class method|1=instance method] "
3822 "<class USR>\n"
3823 " ObjCProperty <property name> <class USR>\n"
3824 " ObjCProtocol <protocol name>\n");
3825}
3826
3827int print_usrs(const char **I, const char **E) {
3828 while (I != E) {
3829 const char *kind = *I;
3830 unsigned len = strlen(kind);
3831 switch (len) {
3832 case 8:
3833 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3834 if (I + 2 >= E)
3835 return insufficient_usr(kind, "<ivar name> <class USR>");
3836 if (!isUSR(I[2]))
3837 return not_usr("<class USR>", I[2]);
3838 else {
3839 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003840 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003841 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003842 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3843 }
3844
3845 I += 3;
3846 continue;
3847 }
3848 break;
3849 case 9:
3850 if (memcmp(kind, "ObjCClass", 9) == 0) {
3851 if (I + 1 >= E)
3852 return insufficient_usr(kind, "<class name>");
3853 print_usr(clang_constructUSR_ObjCClass(I[1]));
3854 I += 2;
3855 continue;
3856 }
3857 break;
3858 case 10:
3859 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3860 if (I + 3 >= E)
3861 return insufficient_usr(kind, "<method selector> "
3862 "[0=class method|1=instance method] <class USR>");
3863 if (!isUSR(I[3]))
3864 return not_usr("<class USR>", I[3]);
3865 else {
3866 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003867 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003868 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003869 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3870 }
3871 I += 4;
3872 continue;
3873 }
3874 break;
3875 case 12:
3876 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3877 if (I + 2 >= E)
3878 return insufficient_usr(kind, "<class name> <category name>");
3879 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3880 I += 3;
3881 continue;
3882 }
3883 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3884 if (I + 1 >= E)
3885 return insufficient_usr(kind, "<protocol name>");
3886 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3887 I += 2;
3888 continue;
3889 }
3890 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3891 if (I + 2 >= E)
3892 return insufficient_usr(kind, "<property name> <class USR>");
3893 if (!isUSR(I[2]))
3894 return not_usr("<class USR>", I[2]);
3895 else {
3896 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003897 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003898 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003899 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3900 }
3901 I += 3;
3902 continue;
3903 }
3904 break;
3905 default:
3906 break;
3907 }
3908 break;
3909 }
3910
3911 if (I != E) {
3912 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3913 display_usrs();
3914 return 1;
3915 }
3916 return 0;
3917}
3918
3919int print_usrs_file(const char *file_name) {
3920 char line[2048];
3921 const char *args[128];
3922 unsigned numChars = 0;
3923
3924 FILE *fp = fopen(file_name, "r");
3925 if (!fp) {
3926 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3927 return 1;
3928 }
3929
3930 /* This code is not really all that safe, but it works fine for testing. */
3931 while (!feof(fp)) {
3932 char c = fgetc(fp);
3933 if (c == '\n') {
3934 unsigned i = 0;
3935 const char *s = 0;
3936
3937 if (numChars == 0)
3938 continue;
3939
3940 line[numChars] = '\0';
3941 numChars = 0;
3942
3943 if (line[0] == '/' && line[1] == '/')
3944 continue;
3945
3946 s = strtok(line, " ");
3947 while (s) {
3948 args[i] = s;
3949 ++i;
3950 s = strtok(0, " ");
3951 }
3952 if (print_usrs(&args[0], &args[i]))
3953 return 1;
3954 }
3955 else
3956 line[numChars++] = c;
3957 }
3958
3959 fclose(fp);
3960 return 0;
3961}
3962
3963/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003964/* Command line processing. */
3965/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003966int write_pch_file(const char *filename, int argc, const char *argv[]) {
3967 CXIndex Idx;
3968 CXTranslationUnit TU;
3969 struct CXUnsavedFile *unsaved_files = 0;
3970 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003971 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003972 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003973
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003974 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003975
3976 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3977 clang_disposeIndex(Idx);
3978 return -1;
3979 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003980
3981 Err = clang_parseTranslationUnit2(
3982 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3983 unsaved_files, num_unsaved_files,
3984 CXTranslationUnit_Incomplete |
3985 CXTranslationUnit_DetailedPreprocessingRecord |
3986 CXTranslationUnit_ForSerialization,
3987 &TU);
3988 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003989 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003990 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003991 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003992 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003993 clang_disposeIndex(Idx);
3994 return 1;
3995 }
3996
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003997 switch (clang_saveTranslationUnit(TU, filename,
3998 clang_defaultSaveOptions(TU))) {
3999 case CXSaveError_None:
4000 break;
4001
4002 case CXSaveError_TranslationErrors:
4003 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4004 filename);
4005 result = 2;
4006 break;
4007
4008 case CXSaveError_InvalidTU:
4009 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4010 filename);
4011 result = 3;
4012 break;
4013
4014 case CXSaveError_Unknown:
4015 default:
4016 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4017 result = 1;
4018 break;
4019 }
4020
Douglas Gregore9386682010-08-13 05:36:37 +00004021 clang_disposeTranslationUnit(TU);
4022 free_remapped_files(unsaved_files, num_unsaved_files);
4023 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004024 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004025}
4026
4027/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004028/* Serialized diagnostics. */
4029/******************************************************************************/
4030
4031static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4032 switch (error) {
4033 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4034 case CXLoadDiag_None: break;
4035 case CXLoadDiag_Unknown: return "Unknown";
4036 case CXLoadDiag_InvalidFile: return "Invalid File";
4037 }
4038 return "None";
4039}
4040
4041static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4042 switch (severity) {
4043 case CXDiagnostic_Note: return "note";
4044 case CXDiagnostic_Error: return "error";
4045 case CXDiagnostic_Fatal: return "fatal";
4046 case CXDiagnostic_Ignored: return "ignored";
4047 case CXDiagnostic_Warning: return "warning";
4048 }
4049 return "unknown";
4050}
4051
4052static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004053 if (indent == 0)
4054 return;
4055 fprintf(stderr, "+");
4056 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004057 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004058 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004059 --indent;
4060 }
4061}
4062
4063static void printLocation(CXSourceLocation L) {
4064 CXFile File;
4065 CXString FileName;
4066 unsigned line, column, offset;
4067
4068 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4069 FileName = clang_getFileName(File);
4070
4071 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4072 clang_disposeString(FileName);
4073}
4074
4075static void printRanges(CXDiagnostic D, unsigned indent) {
4076 unsigned i, n = clang_getDiagnosticNumRanges(D);
4077
4078 for (i = 0; i < n; ++i) {
4079 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004080 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004081 Start = clang_getRangeStart(SR);
4082 End = clang_getRangeEnd(SR);
4083
4084 printIndent(indent);
4085 fprintf(stderr, "Range: ");
4086 printLocation(Start);
4087 fprintf(stderr, " ");
4088 printLocation(End);
4089 fprintf(stderr, "\n");
4090 }
4091}
4092
4093static void printFixIts(CXDiagnostic D, unsigned indent) {
4094 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004095 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004096 for (i = 0 ; i < n; ++i) {
4097 CXSourceRange ReplacementRange;
4098 CXString text;
4099 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4100
4101 printIndent(indent);
4102 fprintf(stderr, "FIXIT: (");
4103 printLocation(clang_getRangeStart(ReplacementRange));
4104 fprintf(stderr, " - ");
4105 printLocation(clang_getRangeEnd(ReplacementRange));
4106 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4107 clang_disposeString(text);
4108 }
4109}
4110
4111static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004112 unsigned i, n;
4113
Ted Kremenekd010ba42011-11-10 08:43:12 +00004114 if (!Diags)
4115 return;
4116
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004117 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004118 for (i = 0; i < n; ++i) {
4119 CXSourceLocation DiagLoc;
4120 CXDiagnostic D;
4121 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004122 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004123 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004124 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004125
4126 D = clang_getDiagnosticInSet(Diags, i);
4127 DiagLoc = clang_getDiagnosticLocation(D);
4128 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4129 FileName = clang_getFileName(File);
4130 DiagSpelling = clang_getDiagnosticSpelling(D);
4131
4132 printIndent(indent);
4133
4134 fprintf(stderr, "%s:%d:%d: %s: %s",
4135 clang_getCString(FileName),
4136 line,
4137 column,
4138 getSeverityString(clang_getDiagnosticSeverity(D)),
4139 clang_getCString(DiagSpelling));
4140
4141 DiagOption = clang_getDiagnosticOption(D, 0);
4142 DiagOptionStr = clang_getCString(DiagOption);
4143 if (DiagOptionStr) {
4144 fprintf(stderr, " [%s]", DiagOptionStr);
4145 }
4146
Ted Kremenek26a6d492012-04-12 00:03:31 +00004147 DiagCat = clang_getDiagnosticCategoryText(D);
4148 DiagCatStr = clang_getCString(DiagCat);
4149 if (DiagCatStr) {
4150 fprintf(stderr, " [%s]", DiagCatStr);
4151 }
4152
Ted Kremenekd010ba42011-11-10 08:43:12 +00004153 fprintf(stderr, "\n");
4154
4155 printRanges(D, indent);
4156 printFixIts(D, indent);
4157
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004158 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004159 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4160
4161 clang_disposeString(FileName);
4162 clang_disposeString(DiagSpelling);
4163 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004164 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004165 }
4166}
4167
4168static int read_diagnostics(const char *filename) {
4169 enum CXLoadDiag_Error error;
4170 CXString errorString;
4171 CXDiagnosticSet Diags = 0;
4172
4173 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4174 if (!Diags) {
4175 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4176 getDiagnosticCodeStr(error),
4177 clang_getCString(errorString));
4178 clang_disposeString(errorString);
4179 return 1;
4180 }
4181
4182 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004183 fprintf(stderr, "Number of diagnostics: %d\n",
4184 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004185 clang_disposeDiagnosticSet(Diags);
4186 return 0;
4187}
4188
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004189static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004190 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004191 return 0;
4192}
4193
Ted Kremenekd010ba42011-11-10 08:43:12 +00004194/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004195/* Command line processing. */
4196/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004197
Douglas Gregor720d0052010-01-20 21:32:04 +00004198static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004199 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004200 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004201 if (strcmp(s, "-usrs") == 0)
4202 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004203 if (strncmp(s, "-memory-usage", 13) == 0)
4204 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004205 return NULL;
4206}
4207
Ted Kremenekef3339b2009-11-17 18:09:14 +00004208static void print_usage(void) {
4209 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004210 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004211 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004212 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004213 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4214 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004215 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4216 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004217 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004218 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004219 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004220 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004221 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004222 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004223 "[FileCheck prefix]\n");
4224 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004225 " c-index-test -test-load-tu <AST file> <symbol filter> "
4226 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004227 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4228 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004229 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004230 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004231 " c-index-test -test-load-source-memory-usage "
4232 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004233 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4234 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004235 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004236 " c-index-test -test-load-source-usrs-memory-usage "
4237 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004238 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4239 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004240 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004241 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004242 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004243 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004244 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004245 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004246 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004247 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004248 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004249 " c-index-test -write-pch <file> <compiler arguments>\n");
4250 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004251 " c-index-test -compilation-db [lookup <filename>] database\n");
4252 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004253 " c-index-test -print-build-session-timestamp\n");
4254 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004255 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004256 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004257 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004258 " all - load all symbols, including those from PCH\n"
4259 " local - load all symbols except those in PCH\n"
4260 " category - only load ObjC categories (non-PCH)\n"
4261 " interface - only load ObjC interfaces (non-PCH)\n"
4262 " protocol - only load ObjC protocols (non-PCH)\n"
4263 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004264 " typedef - only load typdefs (non-PCH)\n"
4265 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004266}
4267
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004268/***/
4269
4270int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004271 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004272 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4273 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004274 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004275 return perform_code_completion(argc, argv, 0);
4276 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4277 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004278 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004279 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4280 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4281 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4282 inspect_evaluate_cursor);
4283 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4284 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4285 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004286 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4287 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004288 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4289 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004290 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004291 return index_file(argc - 2, argv + 2, /*full=*/0);
4292 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4293 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004294 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4295 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004296 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4297 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004298 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004299 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004300 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004301 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4302 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004303 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004304 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4305 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4306 if (I) {
4307 int trials = atoi(argv[2]);
4308 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4309 NULL);
4310 }
4311 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004312 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004313 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004314
4315 PostVisitTU postVisit = 0;
4316 if (strstr(argv[1], "-memory-usage"))
4317 postVisit = PrintMemoryUsage;
4318
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004319 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004320 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4321 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004322 }
4323 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004324 return perform_file_scan(argv[2], argv[3],
4325 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004326 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4327 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004328 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4329 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4330 PrintInclusionStack);
4331 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4332 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4333 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004334 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4335 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4336 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004337 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004338 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004339 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004340 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4341 return perform_test_load_source(argc - 2, argv + 2, "all",
4342 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004343 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4344 return perform_test_load_source(argc - 2, argv + 2, "all",
4345 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004346 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4347 return perform_test_load_source(argc - 2, argv + 2, "all",
4348 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004349 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4350 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004351 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4352 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004353 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4354 if (argc > 2)
4355 return print_usrs(argv + 2, argv + argc);
4356 else {
4357 display_usrs();
4358 return 1;
4359 }
4360 }
4361 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4362 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004363 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4364 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004365 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4366 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004367 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4368 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004369
Ted Kremenekef3339b2009-11-17 18:09:14 +00004370 print_usage();
4371 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004372}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004373
4374/***/
4375
4376/* We intentionally run in a separate thread to ensure we at least minimal
4377 * testing of a multithreaded environment (for example, having a reduced stack
4378 * size). */
4379
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004380typedef struct thread_info {
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004381 int (*main_func)(int argc, const char **argv);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004382 int argc;
4383 const char **argv;
4384 int result;
4385} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004386void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004387 thread_info *client_data = client_data_v;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004388 client_data->result = client_data->main_func(client_data->argc,
4389 client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004390}
4391
4392static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004393 /* stdout, and surprisingly even stderr, are not always flushed on process
4394 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004395 fflush(stdout);
4396 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004397}
4398
4399int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004400 thread_info client_data;
4401
Reid Klecknere931c062014-06-05 00:13:43 +00004402 atexit(flush_atexit);
4403
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004404#ifdef CLANG_HAVE_LIBXML
4405 LIBXML_TEST_VERSION
4406#endif
4407
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004408 client_data.main_func = cindextest_main;
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004409 client_data.argc = argc;
4410 client_data.argv = argv;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004411
4412 if (argc > 1 && strcmp(argv[1], "core") == 0) {
4413 client_data.main_func = indextest_core_main;
4414 --client_data.argc;
4415 ++client_data.argv;
4416 }
4417
4418 if (getenv("CINDEXTEST_NOTHREADS"))
4419 return client_data.main_func(client_data.argc, client_data.argv);
4420
Daniel Dunbar23397c32010-11-04 01:26:31 +00004421 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004422 return client_data.result;
4423}