blob: 802140a350fc146cb22f6db30aa69eff423a3a9e [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/******************************************************************************/
Ehsan Akhgarib743de72016-05-31 15:55:51 +00001268/* Visibility testing. */
1269/******************************************************************************/
1270
1271static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1272 CXClientData d) {
1273 const char *visibility = 0;
1274
1275 if (clang_isInvalid(clang_getCursorKind(cursor)))
1276 return CXChildVisit_Recurse;
1277
1278 switch (clang_getCursorVisibility(cursor)) {
1279 case CXVisibility_Invalid: break;
1280 case CXVisibility_Hidden: visibility = "Hidden"; break;
1281 case CXVisibility_Protected: visibility = "Protected"; break;
1282 case CXVisibility_Default: visibility = "Default"; break;
1283 }
1284
1285 if (visibility) {
1286 PrintCursor(cursor, NULL);
1287 printf("visibility=%s\n", visibility);
1288 }
1289
1290 return CXChildVisit_Recurse;
1291}
1292
1293/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001294/* Typekind testing. */
1295/******************************************************************************/
1296
Dmitri Gribenko00353722013-02-15 21:15:49 +00001297static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1298 CXString TypeSpelling, TypeKindSpelling;
1299
1300 TypeSpelling = clang_getTypeSpelling(T);
1301 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1302 printf(Format,
1303 clang_getCString(TypeSpelling),
1304 clang_getCString(TypeKindSpelling));
1305 clang_disposeString(TypeSpelling);
1306 clang_disposeString(TypeKindSpelling);
1307}
1308
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001309static enum CXVisitorResult FieldVisitor(CXCursor C,
1310 CXClientData client_data) {
1311 (*(int *) client_data)+=1;
1312 return CXVisit_Continue;
1313}
1314
Dmitri Gribenko00353722013-02-15 21:15:49 +00001315static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1316 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001317 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001318 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001319 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001320 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001321 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001322 if (clang_isConstQualifiedType(T))
1323 printf(" const");
1324 if (clang_isVolatileQualifiedType(T))
1325 printf(" volatile");
1326 if (clang_isRestrictQualifiedType(T))
1327 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001328 if (RQ == CXRefQualifier_LValue)
1329 printf(" lvalue-ref-qualifier");
1330 if (RQ == CXRefQualifier_RValue)
1331 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001332 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001333 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001334 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001335 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001336 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001337 }
1338 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001339 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001340 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001341 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001342 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001343 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001344 }
1345 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001346 /* Print the argument types if they exist. */
1347 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001348 int NumArgs = clang_Cursor_getNumArguments(cursor);
1349 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001350 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001351 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001352 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001353 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001354 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001355 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001356 }
1357 }
1358 printf("]");
1359 }
1360 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001361 /* Print the template argument types if they exist. */
1362 {
1363 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1364 if (NumTArgs != -1 && NumTArgs != 0) {
1365 int i;
1366 printf(" [templateargs/%d=", NumTArgs);
1367 for (i = 0; i < NumTArgs; ++i) {
1368 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1369 if (TArg.kind != CXType_Invalid) {
1370 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1371 }
1372 }
1373 printf("]");
1374 }
1375 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001376 /* Print if this is a non-POD type. */
1377 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001378 /* Print the pointee type. */
1379 {
1380 CXType PT = clang_getPointeeType(T);
1381 if (PT.kind != CXType_Invalid) {
1382 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1383 }
1384 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001385 /* Print the number of fields if they exist. */
1386 {
1387 int numFields = 0;
1388 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1389 if (numFields != 0) {
1390 printf(" [nbFields=%d]", numFields);
1391 }
1392 /* Print if it is an anonymous record. */
1393 {
1394 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1395 if (isAnon != 0) {
1396 printf(" [isAnon=%d]", isAnon);
1397 }
1398 }
1399 }
1400 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001401
Ted Kremenek6bca9842010-05-14 21:29:26 +00001402 printf("\n");
1403 }
1404 return CXChildVisit_Recurse;
1405}
1406
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001407static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1408 CXClientData d) {
1409 CXType T;
1410 enum CXCursorKind K = clang_getCursorKind(cursor);
1411 if (clang_isInvalid(K))
1412 return CXChildVisit_Recurse;
1413 T = clang_getCursorType(cursor);
1414 PrintCursor(cursor, NULL);
1415 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1416 /* Print the type sizeof if applicable. */
1417 {
1418 long long Size = clang_Type_getSizeOf(T);
1419 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001420 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001421 }
1422 }
1423 /* Print the type alignof if applicable. */
1424 {
1425 long long Align = clang_Type_getAlignOf(T);
1426 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001427 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001428 }
1429 }
1430 /* Print the record field offset if applicable. */
1431 {
Nico Weber82098cb2014-04-24 04:14:12 +00001432 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1433 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001434 /* recurse to get the first parent record that is not anonymous. */
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001435 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001436 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
David Blaikie263942f2016-05-03 22:14:14 +00001437 CXCursor Record;
1438 CXCursor Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001439 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001440 Record = Parent;
1441 Parent = clang_getCursorSemanticParent(Record);
1442 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1443 /* Recurse as long as the parent is a CXType_Record and the Record
1444 is anonymous */
1445 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1446 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001447 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001448 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001449 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001450 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1451 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001452 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001453 } else {
1454 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001455 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001456 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001457 }
1458 }
Nico Weber82098cb2014-04-24 04:14:12 +00001459 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001460 }
1461 /* Print if its a bitfield */
1462 {
1463 int IsBitfield = clang_Cursor_isBitField(cursor);
1464 if (IsBitfield)
1465 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1466 }
1467 printf("\n");
1468 return CXChildVisit_Recurse;
1469}
1470
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001471/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001472/* Mangling testing. */
1473/******************************************************************************/
1474
1475static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1476 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001477 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001478 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1479 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001480 PrintCursor(cursor, NULL);
1481 MangledName = clang_Cursor_getMangling(cursor);
1482 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001483 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001484 return CXChildVisit_Continue;
1485}
1486
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001487static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1488 CXClientData d) {
1489 unsigned I, E;
1490 CXStringSet *Manglings = NULL;
1491 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1492 return CXChildVisit_Recurse;
1493 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1494 return CXChildVisit_Recurse;
1495 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1496 return CXChildVisit_Continue;
1497 PrintCursor(cursor, NULL);
1498 Manglings = clang_Cursor_getCXXManglings(cursor);
1499 for (I = 0, E = Manglings->Count; I < E; ++I)
1500 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1501 clang_disposeStringSet(Manglings);
1502 printf("\n");
1503 return CXChildVisit_Recurse;
1504}
1505
Eli Bendersky44a206f2014-07-31 18:04:56 +00001506/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001507/* Bitwidth testing. */
1508/******************************************************************************/
1509
1510static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1511 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001512 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001513 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1514 return CXChildVisit_Recurse;
1515
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001516 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001517 if (Bitwidth >= 0) {
1518 PrintCursor(cursor, NULL);
1519 printf(" bitwidth=%d\n", Bitwidth);
1520 }
1521
1522 return CXChildVisit_Recurse;
1523}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001524
1525/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001526/* Type declaration testing */
1527/******************************************************************************/
1528
1529static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1530 CXClientData d) {
1531 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1532
1533 if (clang_isDeclaration(typeDeclaration.kind)) {
1534 PrintCursor(cursor, NULL);
1535 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1536 }
1537
1538 return CXChildVisit_Recurse;
1539}
1540
1541/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001542/* Loading ASTs/source. */
1543/******************************************************************************/
1544
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001545static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001546 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001547 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001548 PostVisitTU PV,
1549 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001550
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001551 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001552 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001553
1554 if (Visitor) {
1555 enum CXCursorKind K = CXCursor_NotImplemented;
1556 enum CXCursorKind *ck = &K;
1557 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001558
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001559 /* Perform some simple filtering. */
1560 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001561 else if (!strcmp(filter, "all-display") ||
1562 !strcmp(filter, "local-display")) {
1563 ck = NULL;
1564 want_display_name = 1;
1565 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001566 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001567 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1568 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1569 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1570 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1571 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1572 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1573 else {
1574 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1575 return 1;
1576 }
Ted Kremenek29004672010-02-17 00:41:32 +00001577
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001578 Data.TU = TU;
1579 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001580 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001581 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001582 }
Ted Kremenek29004672010-02-17 00:41:32 +00001583
Ted Kremenekb478ff42010-01-26 17:59:48 +00001584 if (PV)
1585 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001586
Douglas Gregor33cdd812010-02-18 18:08:43 +00001587 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001588 if (checkForErrors(TU) != 0) {
1589 clang_disposeTranslationUnit(TU);
1590 return -1;
1591 }
1592
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001593 clang_disposeTranslationUnit(TU);
1594 return 0;
1595}
1596
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001597int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001598 const char *prefix, CXCursorVisitor Visitor,
1599 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001600 CXIndex Idx;
1601 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001602 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001603 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001604 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001605 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001606
Ted Kremenek50228be2010-02-11 07:41:25 +00001607 if (!CreateTranslationUnit(Idx, file, &TU)) {
1608 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001609 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001610 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001611
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001612 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001613 clang_disposeIndex(Idx);
1614 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001615}
1616
Ted Kremenekb478ff42010-01-26 17:59:48 +00001617int perform_test_load_source(int argc, const char **argv,
1618 const char *filter, CXCursorVisitor Visitor,
1619 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001620 CXIndex Idx;
1621 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001622 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001623 struct CXUnsavedFile *unsaved_files = 0;
1624 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001625 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001626 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001627 unsigned Repeats = 0;
1628 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001629
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001630 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001631 (!strcmp(filter, "local") ||
1632 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001633 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001634
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001635 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1636 argc--;
1637 argv++;
1638 }
1639
Ted Kremenek50228be2010-02-11 07:41:25 +00001640 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1641 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001642 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001643 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001644
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001645 if (getenv("CINDEXTEST_EDITING"))
1646 Repeats = 5;
1647
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001648 Err = clang_parseTranslationUnit2(Idx, 0,
1649 argv + num_unsaved_files,
1650 argc - num_unsaved_files,
1651 unsaved_files, num_unsaved_files,
1652 getDefaultParsingOptions(), &TU);
1653 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001654 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001655 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001656 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001657 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001658 return 1;
1659 }
1660
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001661 for (I = 0; I != Repeats; ++I) {
1662 if (checkForErrors(TU) != 0)
1663 return -1;
1664
1665 if (Repeats > 1) {
1666 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1667 clang_defaultReparseOptions(TU));
1668 if (Err != CXError_Success) {
1669 describeLibclangFailure(Err);
1670 free_remapped_files(unsaved_files, num_unsaved_files);
1671 clang_disposeIndex(Idx);
1672 return 1;
1673 }
1674 }
1675 }
1676
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001677 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1678 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001679 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001680 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001681 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001682}
1683
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001684int perform_test_reparse_source(int argc, const char **argv, int trials,
1685 const char *filter, CXCursorVisitor Visitor,
1686 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001687 CXIndex Idx;
1688 CXTranslationUnit TU;
1689 struct CXUnsavedFile *unsaved_files = 0;
1690 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001691 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001692 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001693 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001694 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001695 int remap_after_trial = 0;
1696 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001697
1698 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1699 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001700 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001701
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001702 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1703 clang_disposeIndex(Idx);
1704 return -1;
1705 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001706
1707 for (i = 0; i < argc; ++i) {
1708 if (strcmp(argv[i], "--") == 0)
1709 break;
1710 }
1711 if (i < argc)
1712 compiler_arg_idx = i+1;
1713 if (num_unsaved_files > compiler_arg_idx)
1714 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001715
Daniel Dunbarec29d712010-08-18 23:09:16 +00001716 /* Load the initial translation unit -- we do this without honoring remapped
1717 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001718 Err = clang_parseTranslationUnit2(Idx, 0,
1719 argv + compiler_arg_idx,
1720 argc - compiler_arg_idx,
1721 0, 0, getDefaultParsingOptions(), &TU);
1722 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001723 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001724 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001725 free_remapped_files(unsaved_files, num_unsaved_files);
1726 clang_disposeIndex(Idx);
1727 return 1;
1728 }
1729
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001730 if (checkForErrors(TU) != 0)
1731 return -1;
1732
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001733 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1734 remap_after_trial =
1735 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1736 }
1737
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001738 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001739 free_remapped_files(unsaved_files, num_unsaved_files);
1740 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1741 &unsaved_files, &num_unsaved_files)) {
1742 clang_disposeTranslationUnit(TU);
1743 clang_disposeIndex(Idx);
1744 return -1;
1745 }
1746
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001747 Err = clang_reparseTranslationUnit(
1748 TU,
1749 trial >= remap_after_trial ? num_unsaved_files : 0,
1750 trial >= remap_after_trial ? unsaved_files : 0,
1751 clang_defaultReparseOptions(TU));
1752 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001753 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001754 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001755 clang_disposeTranslationUnit(TU);
1756 free_remapped_files(unsaved_files, num_unsaved_files);
1757 clang_disposeIndex(Idx);
1758 return -1;
1759 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001760
1761 if (checkForErrors(TU) != 0)
1762 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001763 }
1764
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001765 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001766
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001767 free_remapped_files(unsaved_files, num_unsaved_files);
1768 clang_disposeIndex(Idx);
1769 return result;
1770}
1771
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001772/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001773/* Logic for testing clang_getCursor(). */
1774/******************************************************************************/
1775
Douglas Gregor37aa4932011-05-04 00:14:37 +00001776static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001777 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001778 unsigned end_line, unsigned end_col,
1779 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001780 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001781 if (prefix)
1782 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001783 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1784 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001785 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001786 printf("\n");
1787}
1788
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001789static int perform_file_scan(const char *ast_file, const char *source_file,
1790 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001791 CXIndex Idx;
1792 CXTranslationUnit TU;
1793 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001794 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001795 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001796 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001797 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001798
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001799 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001800 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001801 fprintf(stderr, "Could not create Index\n");
1802 return 1;
1803 }
Ted Kremenek29004672010-02-17 00:41:32 +00001804
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001805 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1806 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001807
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001808 if ((fp = fopen(source_file, "r")) == NULL) {
1809 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001810 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001811 return 1;
1812 }
Ted Kremenek29004672010-02-17 00:41:32 +00001813
Douglas Gregor816fd362010-01-22 21:44:22 +00001814 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001815 for (;;) {
1816 CXCursor cursor;
1817 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001818
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001819 if (c == '\n') {
1820 ++line;
1821 col = 1;
1822 } else
1823 ++col;
1824
1825 /* Check the cursor at this position, and dump the previous one if we have
1826 * found something new.
1827 */
1828 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1829 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1830 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001831 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001832 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001833 start_line = line;
1834 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001835 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001836 if (c == EOF)
1837 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001838
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001839 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001840 }
Ted Kremenek29004672010-02-17 00:41:32 +00001841
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001842 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001843 clang_disposeTranslationUnit(TU);
1844 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001845 return 0;
1846}
1847
1848/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001849/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001850/******************************************************************************/
1851
Douglas Gregor9eb77012009-11-07 00:00:49 +00001852/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1853 on failure. If successful, the pointer *filename will contain newly-allocated
1854 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001855int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001856 unsigned *column, unsigned *second_line,
1857 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001858 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001859 const char *last_colon = strrchr(input, ':');
1860 unsigned values[4], i;
1861 unsigned num_values = (second_line && second_column)? 4 : 2;
1862
Douglas Gregor9eb77012009-11-07 00:00:49 +00001863 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001864 if (!last_colon || last_colon == input) {
1865 if (num_values == 4)
1866 fprintf(stderr, "could not parse filename:line:column:line:column in "
1867 "'%s'\n", input);
1868 else
1869 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001870 return 1;
1871 }
1872
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001873 for (i = 0; i != num_values; ++i) {
1874 const char *prev_colon;
1875
1876 /* Parse the next line or column. */
1877 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1878 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001879 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001880 (i % 2 ? "column" : "line"), input);
1881 return 1;
1882 }
Ted Kremenek29004672010-02-17 00:41:32 +00001883
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001884 if (i + 1 == num_values)
1885 break;
1886
1887 /* Find the previous colon. */
1888 prev_colon = last_colon - 1;
1889 while (prev_colon != input && *prev_colon != ':')
1890 --prev_colon;
1891 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001892 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001893 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001894 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001895 }
1896
1897 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001898 }
1899
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001900 *line = values[0];
1901 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001902
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001903 if (second_line && second_column) {
1904 *second_line = values[2];
1905 *second_column = values[3];
1906 }
1907
Douglas Gregorf96ea292009-11-09 18:19:57 +00001908 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001909 *filename = (char*)malloc(last_colon - input + 1);
1910 memcpy(*filename, input, last_colon - input);
1911 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001912 return 0;
1913}
1914
1915const char *
1916clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1917 switch (Kind) {
1918 case CXCompletionChunk_Optional: return "Optional";
1919 case CXCompletionChunk_TypedText: return "TypedText";
1920 case CXCompletionChunk_Text: return "Text";
1921 case CXCompletionChunk_Placeholder: return "Placeholder";
1922 case CXCompletionChunk_Informative: return "Informative";
1923 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1924 case CXCompletionChunk_LeftParen: return "LeftParen";
1925 case CXCompletionChunk_RightParen: return "RightParen";
1926 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1927 case CXCompletionChunk_RightBracket: return "RightBracket";
1928 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1929 case CXCompletionChunk_RightBrace: return "RightBrace";
1930 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1931 case CXCompletionChunk_RightAngle: return "RightAngle";
1932 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001933 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001934 case CXCompletionChunk_Colon: return "Colon";
1935 case CXCompletionChunk_SemiColon: return "SemiColon";
1936 case CXCompletionChunk_Equal: return "Equal";
1937 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1938 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001939 }
Ted Kremenek29004672010-02-17 00:41:32 +00001940
Douglas Gregor9eb77012009-11-07 00:00:49 +00001941 return "Unknown";
1942}
1943
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001944static int checkForErrors(CXTranslationUnit TU) {
1945 unsigned Num, i;
1946 CXDiagnostic Diag;
1947 CXString DiagStr;
1948
1949 if (!getenv("CINDEXTEST_FAILONERROR"))
1950 return 0;
1951
1952 Num = clang_getNumDiagnostics(TU);
1953 for (i = 0; i != Num; ++i) {
1954 Diag = clang_getDiagnostic(TU, i);
1955 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1956 DiagStr = clang_formatDiagnostic(Diag,
1957 clang_defaultDiagnosticDisplayOptions());
1958 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1959 clang_disposeString(DiagStr);
1960 clang_disposeDiagnostic(Diag);
1961 return -1;
1962 }
1963 clang_disposeDiagnostic(Diag);
1964 }
1965
1966 return 0;
1967}
1968
Nico Weber8d19dff2014-05-07 21:05:22 +00001969static void print_completion_string(CXCompletionString completion_string,
1970 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001971 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001972
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001973 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001974 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001975 CXString text;
1976 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001977 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001978 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001979
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001980 if (Kind == CXCompletionChunk_Optional) {
1981 fprintf(file, "{Optional ");
1982 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001983 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001984 file);
1985 fprintf(file, "}");
1986 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001987 }
1988
1989 if (Kind == CXCompletionChunk_VerticalSpace) {
1990 fprintf(file, "{VerticalSpace }");
1991 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001992 }
Ted Kremenek29004672010-02-17 00:41:32 +00001993
Douglas Gregorf81f5282009-11-09 17:05:28 +00001994 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001995 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001996 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001997 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001998 cstr ? cstr : "");
1999 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002000 }
Ted Kremenekf602f962010-02-17 01:42:24 +00002001
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002002}
2003
Nico Weber8d19dff2014-05-07 21:05:22 +00002004static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00002005 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002006 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002007 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00002008 enum CXCursorKind ParentKind;
2009 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002010 CXString BriefComment;
Vedant Kumarf27d2272016-04-03 00:54:46 +00002011 CXString Annotation;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002012 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00002013
Ted Kremenek29004672010-02-17 00:41:32 +00002014 fprintf(file, "%s:", clang_getCString(ks));
2015 clang_disposeString(ks);
2016
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002017 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00002018 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00002019 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00002020 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
2021 case CXAvailability_Available:
2022 break;
2023
2024 case CXAvailability_Deprecated:
2025 fprintf(file, " (deprecated)");
2026 break;
2027
2028 case CXAvailability_NotAvailable:
2029 fprintf(file, " (unavailable)");
2030 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002031
2032 case CXAvailability_NotAccessible:
2033 fprintf(file, " (inaccessible)");
2034 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002035 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002036
2037 annotationCount = clang_getCompletionNumAnnotations(
2038 completion_result->CompletionString);
2039 if (annotationCount) {
2040 unsigned i;
2041 fprintf(file, " (");
2042 for (i = 0; i < annotationCount; ++i) {
2043 if (i != 0)
2044 fprintf(file, ", ");
Vedant Kumarf27d2272016-04-03 00:54:46 +00002045 Annotation =
2046 clang_getCompletionAnnotation(completion_result->CompletionString, i);
2047 fprintf(file, "\"%s\"", clang_getCString(Annotation));
2048 clang_disposeString(Annotation);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002049 }
2050 fprintf(file, ")");
2051 }
2052
Douglas Gregor78254c82012-03-27 23:34:16 +00002053 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2054 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2055 &ParentKind);
2056 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002057 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002058 fprintf(file, " (parent: %s '%s')",
2059 clang_getCString(KindSpelling),
2060 clang_getCString(ParentName));
2061 clang_disposeString(KindSpelling);
2062 }
2063 clang_disposeString(ParentName);
2064 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002065
2066 BriefComment = clang_getCompletionBriefComment(
2067 completion_result->CompletionString);
2068 BriefCommentCString = clang_getCString(BriefComment);
2069 if (BriefCommentCString && *BriefCommentCString != '\0') {
2070 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2071 }
2072 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002073
Douglas Gregorf757a122010-08-23 23:00:57 +00002074 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002075}
2076
Douglas Gregor21325842011-07-07 16:03:39 +00002077void print_completion_contexts(unsigned long long contexts, FILE *file) {
2078 fprintf(file, "Completion contexts:\n");
2079 if (contexts == CXCompletionContext_Unknown) {
2080 fprintf(file, "Unknown\n");
2081 }
2082 if (contexts & CXCompletionContext_AnyType) {
2083 fprintf(file, "Any type\n");
2084 }
2085 if (contexts & CXCompletionContext_AnyValue) {
2086 fprintf(file, "Any value\n");
2087 }
2088 if (contexts & CXCompletionContext_ObjCObjectValue) {
2089 fprintf(file, "Objective-C object value\n");
2090 }
2091 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2092 fprintf(file, "Objective-C selector value\n");
2093 }
2094 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2095 fprintf(file, "C++ class type value\n");
2096 }
2097 if (contexts & CXCompletionContext_DotMemberAccess) {
2098 fprintf(file, "Dot member access\n");
2099 }
2100 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2101 fprintf(file, "Arrow member access\n");
2102 }
2103 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2104 fprintf(file, "Objective-C property access\n");
2105 }
2106 if (contexts & CXCompletionContext_EnumTag) {
2107 fprintf(file, "Enum tag\n");
2108 }
2109 if (contexts & CXCompletionContext_UnionTag) {
2110 fprintf(file, "Union tag\n");
2111 }
2112 if (contexts & CXCompletionContext_StructTag) {
2113 fprintf(file, "Struct tag\n");
2114 }
2115 if (contexts & CXCompletionContext_ClassTag) {
2116 fprintf(file, "Class name\n");
2117 }
2118 if (contexts & CXCompletionContext_Namespace) {
2119 fprintf(file, "Namespace or namespace alias\n");
2120 }
2121 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2122 fprintf(file, "Nested name specifier\n");
2123 }
2124 if (contexts & CXCompletionContext_ObjCInterface) {
2125 fprintf(file, "Objective-C interface\n");
2126 }
2127 if (contexts & CXCompletionContext_ObjCProtocol) {
2128 fprintf(file, "Objective-C protocol\n");
2129 }
2130 if (contexts & CXCompletionContext_ObjCCategory) {
2131 fprintf(file, "Objective-C category\n");
2132 }
2133 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2134 fprintf(file, "Objective-C instance method\n");
2135 }
2136 if (contexts & CXCompletionContext_ObjCClassMessage) {
2137 fprintf(file, "Objective-C class method\n");
2138 }
2139 if (contexts & CXCompletionContext_ObjCSelectorName) {
2140 fprintf(file, "Objective-C selector name\n");
2141 }
2142 if (contexts & CXCompletionContext_MacroName) {
2143 fprintf(file, "Macro name\n");
2144 }
2145 if (contexts & CXCompletionContext_NaturalLanguage) {
2146 fprintf(file, "Natural language\n");
2147 }
2148}
2149
Douglas Gregor47815d52010-07-12 18:38:41 +00002150int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002151 const char *input = argv[1];
2152 char *filename = 0;
2153 unsigned line;
2154 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002155 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002156 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002157 struct CXUnsavedFile *unsaved_files = 0;
2158 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002159 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002160 enum CXErrorCode Err;
2161 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002162 unsigned I, Repeats = 1;
2163 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2164
2165 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2166 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002167 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2168 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002169
Douglas Gregor47815d52010-07-12 18:38:41 +00002170 if (timing_only)
2171 input += strlen("-code-completion-timing=");
2172 else
2173 input += strlen("-code-completion-at=");
2174
Ted Kremenek29004672010-02-17 00:41:32 +00002175 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002176 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002177 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002178
Douglas Gregor9485bf92009-12-02 09:21:34 +00002179 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2180 return -1;
2181
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002182 CIdx = clang_createIndex(0, 0);
2183
2184 if (getenv("CINDEXTEST_EDITING"))
2185 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002186
2187 Err = clang_parseTranslationUnit2(CIdx, 0,
2188 argv + num_unsaved_files + 2,
2189 argc - num_unsaved_files - 2,
2190 0, 0, getDefaultParsingOptions(), &TU);
2191 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002192 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002193 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002194 return 1;
2195 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002196
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002197 Err = clang_reparseTranslationUnit(TU, 0, 0,
2198 clang_defaultReparseOptions(TU));
2199
2200 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002201 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002202 describeLibclangFailure(Err);
2203 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002204 return 1;
2205 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002206
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002207 for (I = 0; I != Repeats; ++I) {
2208 results = clang_codeCompleteAt(TU, filename, line, column,
2209 unsaved_files, num_unsaved_files,
2210 completionOptions);
2211 if (!results) {
2212 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002213 return 1;
2214 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002215 if (I != Repeats-1)
2216 clang_disposeCodeCompleteResults(results);
2217 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002218
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002219 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002220 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002221 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002222 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002223 CXString objCSelector;
2224 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002225 if (!timing_only) {
2226 /* Sort the code-completion results based on the typed text. */
2227 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2228
Douglas Gregor47815d52010-07-12 18:38:41 +00002229 for (i = 0; i != n; ++i)
2230 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002231 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002232 n = clang_codeCompleteGetNumDiagnostics(results);
2233 for (i = 0; i != n; ++i) {
2234 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2235 PrintDiagnostic(diag);
2236 clang_disposeDiagnostic(diag);
2237 }
Douglas Gregor21325842011-07-07 16:03:39 +00002238
2239 contexts = clang_codeCompleteGetContexts(results);
2240 print_completion_contexts(contexts, stdout);
2241
Douglas Gregorea777402011-07-26 15:24:30 +00002242 containerKind = clang_codeCompleteGetContainerKind(results,
2243 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002244
2245 if (containerKind != CXCursor_InvalidCode) {
2246 /* We have found a container */
2247 CXString containerUSR, containerKindSpelling;
2248 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2249 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2250 clang_disposeString(containerKindSpelling);
2251
2252 if (containerIsIncomplete) {
2253 printf("Container is incomplete\n");
2254 }
2255 else {
2256 printf("Container is complete\n");
2257 }
2258
2259 containerUSR = clang_codeCompleteGetContainerUSR(results);
2260 printf("Container USR: %s\n", clang_getCString(containerUSR));
2261 clang_disposeString(containerUSR);
2262 }
2263
Douglas Gregorea777402011-07-26 15:24:30 +00002264 objCSelector = clang_codeCompleteGetObjCSelector(results);
2265 selectorString = clang_getCString(objCSelector);
2266 if (selectorString && strlen(selectorString) > 0) {
2267 printf("Objective-C selector: %s\n", selectorString);
2268 }
2269 clang_disposeString(objCSelector);
2270
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002271 clang_disposeCodeCompleteResults(results);
2272 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002273 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002274 clang_disposeIndex(CIdx);
2275 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002276
Douglas Gregor9485bf92009-12-02 09:21:34 +00002277 free_remapped_files(unsaved_files, num_unsaved_files);
2278
Ted Kremenekef3339b2009-11-17 18:09:14 +00002279 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002280}
2281
Douglas Gregor082c3e62010-01-15 19:40:17 +00002282typedef struct {
2283 char *filename;
2284 unsigned line;
2285 unsigned column;
2286} CursorSourceLocation;
2287
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002288typedef void (*cursor_handler_t)(CXCursor cursor);
2289
2290static int inspect_cursor_at(int argc, const char **argv,
2291 const char *locations_flag,
2292 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002293 CXIndex CIdx;
2294 int errorCode;
2295 struct CXUnsavedFile *unsaved_files = 0;
2296 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002297 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002298 CXTranslationUnit TU;
2299 CXCursor Cursor;
2300 CursorSourceLocation *Locations = 0;
2301 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002302 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002303 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002304
Ted Kremenek29004672010-02-17 00:41:32 +00002305 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002306 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002307 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002308
Douglas Gregor082c3e62010-01-15 19:40:17 +00002309 /* Parse the locations. */
2310 assert(NumLocations > 0 && "Unable to count locations?");
2311 Locations = (CursorSourceLocation *)malloc(
2312 NumLocations * sizeof(CursorSourceLocation));
2313 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002314 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002315 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2316 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002317 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002318 return errorCode;
2319 }
Ted Kremenek29004672010-02-17 00:41:32 +00002320
2321 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002322 &num_unsaved_files))
2323 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002324
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002325 if (getenv("CINDEXTEST_EDITING"))
2326 Repeats = 5;
2327
2328 /* Parse the translation unit. When we're testing clang_getCursor() after
2329 reparsing, don't remap unsaved files until the second parse. */
2330 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002331 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2332 argv + num_unsaved_files + 1 + NumLocations,
2333 argc - num_unsaved_files - 2 - NumLocations,
2334 unsaved_files,
2335 Repeats > 1? 0 : num_unsaved_files,
2336 getDefaultParsingOptions(), &TU);
2337 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002338 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002339 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002340 return -1;
2341 }
Ted Kremenek29004672010-02-17 00:41:32 +00002342
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002343 if (checkForErrors(TU) != 0)
2344 return -1;
2345
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002346 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002347 if (Repeats > 1) {
2348 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2349 clang_defaultReparseOptions(TU));
2350 if (Err != CXError_Success) {
2351 describeLibclangFailure(Err);
2352 clang_disposeTranslationUnit(TU);
2353 return 1;
2354 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002355 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002356
2357 if (checkForErrors(TU) != 0)
2358 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002359
2360 for (Loc = 0; Loc < NumLocations; ++Loc) {
2361 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2362 if (!file)
2363 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002364
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002365 Cursor = clang_getCursor(TU,
2366 clang_getLocation(TU, file, Locations[Loc].line,
2367 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002368
2369 if (checkForErrors(TU) != 0)
2370 return -1;
2371
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002372 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002373 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002374 free(Locations[Loc].filename);
2375 }
2376 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002377 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002378
Douglas Gregor33cdd812010-02-18 18:08:43 +00002379 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002380 clang_disposeTranslationUnit(TU);
2381 clang_disposeIndex(CIdx);
2382 free(Locations);
2383 free_remapped_files(unsaved_files, num_unsaved_files);
2384 return 0;
2385}
2386
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002387static void inspect_print_cursor(CXCursor Cursor) {
2388 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2389 CXCompletionString completionString = clang_getCursorCompletionString(
2390 Cursor);
2391 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2392 CXString Spelling;
2393 const char *cspell;
2394 unsigned line, column;
2395 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2396 printf("%d:%d ", line, column);
2397 PrintCursor(Cursor, NULL);
2398 PrintCursorExtent(Cursor);
2399 Spelling = clang_getCursorSpelling(Cursor);
2400 cspell = clang_getCString(Spelling);
2401 if (cspell && strlen(cspell) != 0) {
2402 unsigned pieceIndex;
2403 printf(" Spelling=%s (", cspell);
2404 for (pieceIndex = 0; ; ++pieceIndex) {
2405 CXSourceRange range =
2406 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2407 if (clang_Range_isNull(range))
2408 break;
2409 PrintRange(range, 0);
2410 }
2411 printf(")");
2412 }
2413 clang_disposeString(Spelling);
2414 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2415 printf(" Selector index=%d",
2416 clang_Cursor_getObjCSelectorIndex(Cursor));
2417 if (clang_Cursor_isDynamicCall(Cursor))
2418 printf(" Dynamic-call");
2419 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2420 CXType T = clang_Cursor_getReceiverType(Cursor);
2421 CXString S = clang_getTypeKindSpelling(T.kind);
2422 printf(" Receiver-type=%s", clang_getCString(S));
2423 clang_disposeString(S);
2424 }
2425
2426 {
2427 CXModule mod = clang_Cursor_getModule(Cursor);
2428 CXFile astFile;
2429 CXString name, astFilename;
2430 unsigned i, numHeaders;
2431 if (mod) {
2432 astFile = clang_Module_getASTFile(mod);
2433 astFilename = clang_getFileName(astFile);
2434 name = clang_Module_getFullName(mod);
2435 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2436 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2437 clang_getCString(name), clang_getCString(astFilename),
2438 clang_Module_isSystem(mod), numHeaders);
2439 clang_disposeString(name);
2440 clang_disposeString(astFilename);
2441 for (i = 0; i < numHeaders; ++i) {
2442 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2443 CXString filename = clang_getFileName(file);
2444 printf("\n%s", clang_getCString(filename));
2445 clang_disposeString(filename);
2446 }
2447 }
2448 }
2449
2450 if (completionString != NULL) {
2451 printf("\nCompletion string: ");
2452 print_completion_string(completionString, stdout);
2453 }
2454 printf("\n");
2455}
2456
2457static void display_evaluate_results(CXEvalResult result) {
2458 switch (clang_EvalResult_getKind(result)) {
2459 case CXEval_Int:
2460 {
2461 int val = clang_EvalResult_getAsInt(result);
2462 printf("Kind: Int , Value: %d", val);
2463 break;
2464 }
2465 case CXEval_Float:
2466 {
2467 double val = clang_EvalResult_getAsDouble(result);
2468 printf("Kind: Float , Value: %f", val);
2469 break;
2470 }
2471 case CXEval_ObjCStrLiteral:
2472 {
2473 const char* str = clang_EvalResult_getAsStr(result);
2474 printf("Kind: ObjCString , Value: %s", str);
2475 break;
2476 }
2477 case CXEval_StrLiteral:
2478 {
2479 const char* str = clang_EvalResult_getAsStr(result);
2480 printf("Kind: CString , Value: %s", str);
2481 break;
2482 }
2483 case CXEval_CFStr:
2484 {
2485 const char* str = clang_EvalResult_getAsStr(result);
2486 printf("Kind: CFString , Value: %s", str);
2487 break;
2488 }
2489 default:
2490 printf("Unexposed");
2491 break;
2492 }
2493}
2494
2495static void inspect_evaluate_cursor(CXCursor Cursor) {
2496 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2497 CXString Spelling;
2498 const char *cspell;
2499 unsigned line, column;
2500 CXEvalResult ER;
2501
2502 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2503 printf("%d:%d ", line, column);
2504 PrintCursor(Cursor, NULL);
2505 PrintCursorExtent(Cursor);
2506 Spelling = clang_getCursorSpelling(Cursor);
2507 cspell = clang_getCString(Spelling);
2508 if (cspell && strlen(cspell) != 0) {
2509 unsigned pieceIndex;
2510 printf(" Spelling=%s (", cspell);
2511 for (pieceIndex = 0; ; ++pieceIndex) {
2512 CXSourceRange range =
2513 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2514 if (clang_Range_isNull(range))
2515 break;
2516 PrintRange(range, 0);
2517 }
2518 printf(")");
2519 }
2520 clang_disposeString(Spelling);
2521
2522 ER = clang_Cursor_Evaluate(Cursor);
2523 if (!ER) {
2524 printf("Not Evaluatable");
2525 } else {
2526 display_evaluate_results(ER);
2527 clang_EvalResult_dispose(ER);
2528 }
2529 printf("\n");
2530}
2531
2532static void inspect_macroinfo_cursor(CXCursor Cursor) {
2533 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2534 CXString Spelling;
2535 const char *cspell;
2536 unsigned line, column;
2537 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2538 printf("%d:%d ", line, column);
2539 PrintCursor(Cursor, NULL);
2540 PrintCursorExtent(Cursor);
2541 Spelling = clang_getCursorSpelling(Cursor);
2542 cspell = clang_getCString(Spelling);
2543 if (cspell && strlen(cspell) != 0) {
2544 unsigned pieceIndex;
2545 printf(" Spelling=%s (", cspell);
2546 for (pieceIndex = 0; ; ++pieceIndex) {
2547 CXSourceRange range =
2548 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2549 if (clang_Range_isNull(range))
2550 break;
2551 PrintRange(range, 0);
2552 }
2553 printf(")");
2554 }
2555 clang_disposeString(Spelling);
2556
2557 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2558 printf("[builtin macro]");
2559 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2560 printf("[function macro]");
2561 }
2562 printf("\n");
2563}
2564
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002565static enum CXVisitorResult findFileRefsVisit(void *context,
2566 CXCursor cursor, CXSourceRange range) {
2567 if (clang_Range_isNull(range))
2568 return CXVisit_Continue;
2569
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002570 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002571 PrintRange(range, "");
2572 printf("\n");
2573 return CXVisit_Continue;
2574}
2575
2576static int find_file_refs_at(int argc, const char **argv) {
2577 CXIndex CIdx;
2578 int errorCode;
2579 struct CXUnsavedFile *unsaved_files = 0;
2580 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002581 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002582 CXTranslationUnit TU;
2583 CXCursor Cursor;
2584 CursorSourceLocation *Locations = 0;
2585 unsigned NumLocations = 0, Loc;
2586 unsigned Repeats = 1;
2587 unsigned I;
2588
2589 /* Count the number of locations. */
2590 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2591 ++NumLocations;
2592
2593 /* Parse the locations. */
2594 assert(NumLocations > 0 && "Unable to count locations?");
2595 Locations = (CursorSourceLocation *)malloc(
2596 NumLocations * sizeof(CursorSourceLocation));
2597 for (Loc = 0; Loc < NumLocations; ++Loc) {
2598 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2599 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2600 &Locations[Loc].line,
2601 &Locations[Loc].column, 0, 0)))
2602 return errorCode;
2603 }
2604
2605 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2606 &num_unsaved_files))
2607 return -1;
2608
2609 if (getenv("CINDEXTEST_EDITING"))
2610 Repeats = 5;
2611
2612 /* Parse the translation unit. When we're testing clang_getCursor() after
2613 reparsing, don't remap unsaved files until the second parse. */
2614 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002615 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2616 argv + num_unsaved_files + 1 + NumLocations,
2617 argc - num_unsaved_files - 2 - NumLocations,
2618 unsaved_files,
2619 Repeats > 1? 0 : num_unsaved_files,
2620 getDefaultParsingOptions(), &TU);
2621 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002622 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002623 describeLibclangFailure(Err);
2624 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002625 return -1;
2626 }
2627
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002628 if (checkForErrors(TU) != 0)
2629 return -1;
2630
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002631 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002632 if (Repeats > 1) {
2633 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2634 clang_defaultReparseOptions(TU));
2635 if (Err != CXError_Success) {
2636 describeLibclangFailure(Err);
2637 clang_disposeTranslationUnit(TU);
2638 return 1;
2639 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002640 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002641
2642 if (checkForErrors(TU) != 0)
2643 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002644
2645 for (Loc = 0; Loc < NumLocations; ++Loc) {
2646 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2647 if (!file)
2648 continue;
2649
2650 Cursor = clang_getCursor(TU,
2651 clang_getLocation(TU, file, Locations[Loc].line,
2652 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002653
2654 if (checkForErrors(TU) != 0)
2655 return -1;
2656
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002657 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002658 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002659 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002660 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002661 clang_findReferencesInFile(Cursor, file, visitor);
2662 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002663
2664 if (checkForErrors(TU) != 0)
2665 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002666 }
2667 }
2668 }
2669
2670 PrintDiagnostics(TU);
2671 clang_disposeTranslationUnit(TU);
2672 clang_disposeIndex(CIdx);
2673 free(Locations);
2674 free_remapped_files(unsaved_files, num_unsaved_files);
2675 return 0;
2676}
2677
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002678static enum CXVisitorResult findFileIncludesVisit(void *context,
2679 CXCursor cursor, CXSourceRange range) {
2680 PrintCursor(cursor, NULL);
2681 PrintRange(range, "");
2682 printf("\n");
2683 return CXVisit_Continue;
2684}
2685
2686static int find_file_includes_in(int argc, const char **argv) {
2687 CXIndex CIdx;
2688 struct CXUnsavedFile *unsaved_files = 0;
2689 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002690 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002691 CXTranslationUnit TU;
2692 const char **Filenames = 0;
2693 unsigned NumFilenames = 0;
2694 unsigned Repeats = 1;
2695 unsigned I, FI;
2696
2697 /* Count the number of locations. */
2698 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2699 ++NumFilenames;
2700
2701 /* Parse the locations. */
2702 assert(NumFilenames > 0 && "Unable to count filenames?");
2703 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2704 for (I = 0; I < NumFilenames; ++I) {
2705 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2706 /* Copy the file name. */
2707 Filenames[I] = input;
2708 }
2709
2710 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2711 &num_unsaved_files))
2712 return -1;
2713
2714 if (getenv("CINDEXTEST_EDITING"))
2715 Repeats = 2;
2716
2717 /* Parse the translation unit. When we're testing clang_getCursor() after
2718 reparsing, don't remap unsaved files until the second parse. */
2719 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002720 Err = clang_parseTranslationUnit2(
2721 CIdx, argv[argc - 1],
2722 argv + num_unsaved_files + 1 + NumFilenames,
2723 argc - num_unsaved_files - 2 - NumFilenames,
2724 unsaved_files,
2725 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002726
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002727 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002728 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002729 describeLibclangFailure(Err);
2730 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002731 return -1;
2732 }
2733
2734 if (checkForErrors(TU) != 0)
2735 return -1;
2736
2737 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002738 if (Repeats > 1) {
2739 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2740 clang_defaultReparseOptions(TU));
2741 if (Err != CXError_Success) {
2742 describeLibclangFailure(Err);
2743 clang_disposeTranslationUnit(TU);
2744 return 1;
2745 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002746 }
2747
2748 if (checkForErrors(TU) != 0)
2749 return -1;
2750
2751 for (FI = 0; FI < NumFilenames; ++FI) {
2752 CXFile file = clang_getFile(TU, Filenames[FI]);
2753 if (!file)
2754 continue;
2755
2756 if (checkForErrors(TU) != 0)
2757 return -1;
2758
2759 if (I + 1 == Repeats) {
2760 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2761 clang_findIncludesInFile(TU, file, visitor);
2762
2763 if (checkForErrors(TU) != 0)
2764 return -1;
2765 }
2766 }
2767 }
2768
2769 PrintDiagnostics(TU);
2770 clang_disposeTranslationUnit(TU);
2771 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002772 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002773 free_remapped_files(unsaved_files, num_unsaved_files);
2774 return 0;
2775}
2776
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002777#define MAX_IMPORTED_ASTFILES 200
2778
2779typedef struct {
2780 char **filenames;
2781 unsigned num_files;
2782} ImportedASTFilesData;
2783
2784static ImportedASTFilesData *importedASTs_create() {
2785 ImportedASTFilesData *p;
2786 p = malloc(sizeof(ImportedASTFilesData));
2787 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2788 p->num_files = 0;
2789 return p;
2790}
2791
2792static void importedASTs_dispose(ImportedASTFilesData *p) {
2793 unsigned i;
2794 if (!p)
2795 return;
2796
2797 for (i = 0; i < p->num_files; ++i)
2798 free(p->filenames[i]);
2799 free(p->filenames);
2800 free(p);
2801}
2802
2803static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2804 unsigned i;
2805 assert(p && file);
2806 for (i = 0; i < p->num_files; ++i)
2807 if (strcmp(file, p->filenames[i]) == 0)
2808 return;
2809 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2810 p->filenames[p->num_files++] = strdup(file);
2811}
2812
Nico Weberdf686022014-05-07 21:09:42 +00002813typedef struct IndexDataStringList_ {
2814 struct IndexDataStringList_ *next;
2815 char data[1]; /* Dynamically sized. */
2816} IndexDataStringList;
2817
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002818typedef struct {
2819 const char *check_prefix;
2820 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002821 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002822 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002823 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002824 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002825 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002826 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002827} IndexData;
2828
Nico Weberdf686022014-05-07 21:09:42 +00002829static void free_client_data(IndexData *index_data) {
2830 IndexDataStringList *node = index_data->strings;
2831 while (node) {
2832 IndexDataStringList *next = node->next;
2833 free(node);
2834 node = next;
2835 }
2836 index_data->strings = NULL;
2837}
2838
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002839static void printCheck(IndexData *data) {
2840 if (data->check_prefix) {
2841 if (data->first_check_printed) {
2842 printf("// %s-NEXT: ", data->check_prefix);
2843 } else {
2844 printf("// %s : ", data->check_prefix);
2845 data->first_check_printed = 1;
2846 }
2847 }
2848}
2849
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002850static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002851 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002852 printf("%s", clang_getCString(filename));
2853 clang_disposeString(filename);
2854}
2855
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002856static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2857 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002858 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002859 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002860 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002861 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002862 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002863
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002864 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002865 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2866 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002867 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002868 return;
2869 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002870 if (!file) {
2871 printf("<no idxfile>");
2872 return;
2873 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002874 filename = clang_getFileName((CXFile)file);
2875 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002876 if (strcmp(cname, index_data->main_filename) == 0)
2877 isMainFile = 1;
2878 else
2879 isMainFile = 0;
2880 clang_disposeString(filename);
2881
2882 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002883 printCXIndexFile(file);
2884 printf(":");
2885 }
2886 printf("%d:%d", line, column);
2887}
2888
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002889static unsigned digitCount(unsigned val) {
2890 unsigned c = 1;
2891 while (1) {
2892 if (val < 10)
2893 return c;
2894 ++c;
2895 val /= 10;
2896 }
2897}
2898
Nico Weberdf686022014-05-07 21:09:42 +00002899static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2900 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002901 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002902 IndexData *index_data;
2903 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002904 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002905 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002906 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002907 unsigned line, column;
2908
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002909 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002910 if (!name)
2911 name = "<anon-tag>";
2912
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002913 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002914
2915 node =
2916 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2917 digitCount(line) + digitCount(column) + 2);
2918 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002919 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002920
2921 /* Remember string so it can be freed later. */
2922 index_data = (IndexData *)client_data;
2923 node->next = index_data->strings;
2924 index_data->strings = node;
2925
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002926 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002927}
2928
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002929static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2930 CXIdxClientContainer container;
2931 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002932 if (!container)
2933 printf("[<<NULL>>]");
2934 else
2935 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002936}
2937
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002938static const char *getEntityKindString(CXIdxEntityKind kind) {
2939 switch (kind) {
2940 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2941 case CXIdxEntity_Typedef: return "typedef";
2942 case CXIdxEntity_Function: return "function";
2943 case CXIdxEntity_Variable: return "variable";
2944 case CXIdxEntity_Field: return "field";
2945 case CXIdxEntity_EnumConstant: return "enumerator";
2946 case CXIdxEntity_ObjCClass: return "objc-class";
2947 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2948 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002949 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2950 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002951 case CXIdxEntity_ObjCProperty: return "objc-property";
2952 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2953 case CXIdxEntity_Enum: return "enum";
2954 case CXIdxEntity_Struct: return "struct";
2955 case CXIdxEntity_Union: return "union";
2956 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002957 case CXIdxEntity_CXXNamespace: return "namespace";
2958 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2959 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2960 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2961 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2962 case CXIdxEntity_CXXConstructor: return "constructor";
2963 case CXIdxEntity_CXXDestructor: return "destructor";
2964 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2965 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002966 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002967 }
2968 assert(0 && "Garbage entity kind");
2969 return 0;
2970}
2971
2972static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2973 switch (kind) {
2974 case CXIdxEntity_NonTemplate: return "";
2975 case CXIdxEntity_Template: return "-template";
2976 case CXIdxEntity_TemplatePartialSpecialization:
2977 return "-template-partial-spec";
2978 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002979 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002980 assert(0 && "Garbage entity kind");
2981 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002982}
2983
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002984static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2985 switch (kind) {
2986 case CXIdxEntityLang_None: return "<none>";
2987 case CXIdxEntityLang_C: return "C";
2988 case CXIdxEntityLang_ObjC: return "ObjC";
2989 case CXIdxEntityLang_CXX: return "C++";
2990 }
2991 assert(0 && "Garbage language kind");
2992 return 0;
2993}
2994
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002995static void printEntityInfo(const char *cb,
2996 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002997 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002998 const char *name;
2999 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003000 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003001 index_data = (IndexData *)client_data;
3002 printCheck(index_data);
3003
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00003004 if (!info) {
3005 printf("%s: <<NULL>>", cb);
3006 return;
3007 }
3008
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003009 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003010 if (!name)
3011 name = "<anon-tag>";
3012
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003013 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
3014 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003015 printf(" | name: %s", name);
3016 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00003017 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003018
3019 for (i = 0; i != info->numAttributes; ++i) {
3020 const CXIdxAttrInfo *Attr = info->attributes[i];
3021 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003022 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003023 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003024}
3025
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003026static void printBaseClassInfo(CXClientData client_data,
3027 const CXIdxBaseClassInfo *info) {
3028 printEntityInfo(" <base>", client_data, info->base);
3029 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003030 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003031 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003032 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003033}
3034
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003035static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3036 CXClientData client_data) {
3037 unsigned i;
3038 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3039 printEntityInfo(" <protocol>", client_data,
3040 ProtoInfo->protocols[i]->protocol);
3041 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003042 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003043 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003044 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003045 printf("\n");
3046 }
3047}
3048
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003049static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003050 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003051 CXString str;
3052 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003053 unsigned numDiags, i;
3054 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003055 IndexData *index_data;
3056 index_data = (IndexData *)client_data;
3057 printCheck(index_data);
3058
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003059 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3060 for (i = 0; i != numDiags; ++i) {
3061 diag = clang_getDiagnosticInSet(diagSet, i);
3062 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3063 cstr = clang_getCString(str);
3064 printf("[diagnostic]: %s\n", cstr);
3065 clang_disposeString(str);
3066
3067 if (getenv("CINDEXTEST_FAILONERROR") &&
3068 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3069 index_data->fail_for_error = 1;
3070 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003071 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003072}
3073
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003074static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3075 CXFile file, void *reserved) {
3076 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003077 CXString filename;
3078
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003079 index_data = (IndexData *)client_data;
3080 printCheck(index_data);
3081
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003082 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003083 index_data->main_filename = clang_getCString(filename);
3084 clang_disposeString(filename);
3085
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003086 printf("[enteredMainFile]: ");
3087 printCXIndexFile((CXIdxClientFile)file);
3088 printf("\n");
3089
3090 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003091}
3092
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003093static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003094 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003095 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003096 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003097 index_data = (IndexData *)client_data;
3098 printCheck(index_data);
3099
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003100 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003101 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003102 printf(" | name: \"%s\"", info->filename);
3103 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003104 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003105 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003106 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003107
3108 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3109 if (Mod) {
3110 CXString str = clang_Module_getFullName(Mod);
3111 const char *cstr = clang_getCString(str);
3112 printf(" | module: %s", cstr);
3113 clang_disposeString(str);
3114 }
3115
3116 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003117
3118 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003119}
3120
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003121static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3122 const CXIdxImportedASTFileInfo *info) {
3123 IndexData *index_data;
3124 index_data = (IndexData *)client_data;
3125 printCheck(index_data);
3126
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003127 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003128 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003129 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3130 clang_disposeString(filename);
3131 }
3132
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003133 printf("[importedASTFile]: ");
3134 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003135 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003136 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003137 printf(" | loc: ");
3138 printCXIndexLoc(info->loc, client_data);
3139 printf(" | name: \"%s\"", clang_getCString(name));
3140 printf(" | isImplicit: %d\n", info->isImplicit);
3141 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003142 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003143 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003144 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003145 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003146
3147 return (CXIdxClientFile)info->file;
3148}
3149
Nico Weber8d19dff2014-05-07 21:05:22 +00003150static CXIdxClientContainer
3151index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003152 IndexData *index_data;
3153 index_data = (IndexData *)client_data;
3154 printCheck(index_data);
3155
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003156 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003157 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003158}
3159
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003160static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003161 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003162 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003163 const CXIdxObjCCategoryDeclInfo *CatInfo;
3164 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003165 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003166 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003167 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003168 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003169 index_data = (IndexData *)client_data;
3170
3171 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3172 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003173 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003174 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003175 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003176 printf(" | semantic-container: ");
3177 printCXIndexContainer(info->semanticContainer);
3178 printf(" | lexical-container: ");
3179 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003180 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003181 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003182 if (info->flags & CXIdxDeclFlag_Skipped) {
3183 assert(!info->isContainer);
3184 printf(" | isContainer: skipped");
3185 } else {
3186 printf(" | isContainer: %d", info->isContainer);
3187 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003188 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003189
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003190 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003191 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003192 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003193 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003194 printf("\n");
3195 }
3196
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003197 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3198 const char *kindName = 0;
3199 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3200 switch (K) {
3201 case CXIdxObjCContainer_ForwardRef:
3202 kindName = "forward-ref"; break;
3203 case CXIdxObjCContainer_Interface:
3204 kindName = "interface"; break;
3205 case CXIdxObjCContainer_Implementation:
3206 kindName = "implementation"; break;
3207 }
3208 printCheck(index_data);
3209 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3210 }
3211
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003212 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003213 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3214 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003215 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003216 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003217 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003218 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003219 printf("\n");
3220 }
3221
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003222 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3223 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003224 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003225 printf("\n");
3226 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003227 }
3228
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003229 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3230 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003231 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003232
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003233 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3234 if (PropInfo->getter) {
3235 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3236 printf("\n");
3237 }
3238 if (PropInfo->setter) {
3239 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3240 printf("\n");
3241 }
3242 }
3243
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003244 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3245 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3246 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3247 printf("\n");
3248 }
3249 }
3250
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003251 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003252 clang_index_setClientContainer(
3253 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003254 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003255}
3256
3257static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003258 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003259 printEntityInfo("[indexEntityReference]", client_data,
3260 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003261 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003262 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003263 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003264 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003265 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003266 printf(" | container: ");
3267 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003268 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003269 switch (info->kind) {
3270 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003271 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003272 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003273 printf("\n");
3274}
3275
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003276static int index_abortQuery(CXClientData client_data, void *reserved) {
3277 IndexData *index_data;
3278 index_data = (IndexData *)client_data;
3279 return index_data->abort;
3280}
3281
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003282static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003283 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003284 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003285 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003286 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003287 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003288 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003289 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003290 index_indexEntityReference
3291};
3292
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003293static unsigned getIndexOptions(void) {
3294 unsigned index_opts;
3295 index_opts = 0;
3296 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3297 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3298 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3299 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003300 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3301 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003302
3303 return index_opts;
3304}
3305
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003306static int index_compile_args(int num_args, const char **args,
3307 CXIndexAction idxAction,
3308 ImportedASTFilesData *importedASTs,
3309 const char *check_prefix) {
3310 IndexData index_data;
3311 unsigned index_opts;
3312 int result;
3313
3314 if (num_args == 0) {
3315 fprintf(stderr, "no compiler arguments\n");
3316 return -1;
3317 }
3318
3319 index_data.check_prefix = check_prefix;
3320 index_data.first_check_printed = 0;
3321 index_data.fail_for_error = 0;
3322 index_data.abort = 0;
3323 index_data.main_filename = "";
3324 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003325 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003326 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003327
3328 index_opts = getIndexOptions();
3329 result = clang_indexSourceFile(idxAction, &index_data,
3330 &IndexCB,sizeof(IndexCB), index_opts,
3331 0, args, num_args, 0, 0, 0,
3332 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003333 if (result != CXError_Success)
3334 describeLibclangFailure(result);
3335
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003336 if (index_data.fail_for_error)
3337 result = -1;
3338
Nico Weberdf686022014-05-07 21:09:42 +00003339 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003340 return result;
3341}
3342
3343static int index_ast_file(const char *ast_file,
3344 CXIndex Idx,
3345 CXIndexAction idxAction,
3346 ImportedASTFilesData *importedASTs,
3347 const char *check_prefix) {
3348 CXTranslationUnit TU;
3349 IndexData index_data;
3350 unsigned index_opts;
3351 int result;
3352
3353 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3354 return -1;
3355
3356 index_data.check_prefix = check_prefix;
3357 index_data.first_check_printed = 0;
3358 index_data.fail_for_error = 0;
3359 index_data.abort = 0;
3360 index_data.main_filename = "";
3361 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003362 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003363 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003364
3365 index_opts = getIndexOptions();
3366 result = clang_indexTranslationUnit(idxAction, &index_data,
3367 &IndexCB,sizeof(IndexCB),
3368 index_opts, TU);
3369 if (index_data.fail_for_error)
3370 result = -1;
3371
3372 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003373 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003374 return result;
3375}
3376
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003377static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003378 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003379 CXIndex Idx;
3380 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003381 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003382 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003383
3384 check_prefix = 0;
3385 if (argc > 0) {
3386 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3387 check_prefix = argv[0] + strlen("-check-prefix=");
3388 ++argv;
3389 --argc;
3390 }
3391 }
3392
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003393 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003394 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003395 fprintf(stderr, "Could not create Index\n");
3396 return 1;
3397 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003398 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003399 importedASTs = 0;
3400 if (full)
3401 importedASTs = importedASTs_create();
3402
3403 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3404 if (result != 0)
3405 goto finished;
3406
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003407 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003408 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003409 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3410 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3411 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003412 }
3413 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003414
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003415finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003416 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003417 clang_IndexAction_dispose(idxAction);
3418 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003419 return result;
3420}
3421
3422static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003423 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003424 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003425 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003426 int result;
3427
3428 check_prefix = 0;
3429 if (argc > 0) {
3430 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3431 check_prefix = argv[0] + strlen("-check-prefix=");
3432 ++argv;
3433 --argc;
3434 }
3435 }
3436
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003437 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003438 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003439 fprintf(stderr, "Could not create Index\n");
3440 return 1;
3441 }
3442 idxAction = clang_IndexAction_create(Idx);
3443
3444 result = index_ast_file(argv[0], Idx, idxAction,
3445 /*importedASTs=*/0, check_prefix);
3446
3447 clang_IndexAction_dispose(idxAction);
3448 clang_disposeIndex(Idx);
3449 return result;
3450}
3451
3452static int index_compile_db(int argc, const char **argv) {
3453 const char *check_prefix;
3454 CXIndex Idx;
3455 CXIndexAction idxAction;
3456 int errorCode = 0;
3457
3458 check_prefix = 0;
3459 if (argc > 0) {
3460 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3461 check_prefix = argv[0] + strlen("-check-prefix=");
3462 ++argv;
3463 --argc;
3464 }
3465 }
3466
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003467 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003468 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003469 return -1;
3470 }
3471
3472 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003473 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003474 fprintf(stderr, "Could not create Index\n");
3475 return 1;
3476 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003477 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003478
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003479 {
3480 const char *database = argv[0];
3481 CXCompilationDatabase db = 0;
3482 CXCompileCommands CCmds = 0;
3483 CXCompileCommand CCmd;
3484 CXCompilationDatabase_Error ec;
3485 CXString wd;
3486#define MAX_COMPILE_ARGS 512
3487 CXString cxargs[MAX_COMPILE_ARGS];
3488 const char *args[MAX_COMPILE_ARGS];
3489 char *tmp;
3490 unsigned len;
3491 char *buildDir;
3492 int i, a, numCmds, numArgs;
3493
3494 len = strlen(database);
3495 tmp = (char *) malloc(len+1);
3496 memcpy(tmp, database, len+1);
3497 buildDir = dirname(tmp);
3498
3499 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3500
3501 if (db) {
3502
3503 if (ec!=CXCompilationDatabase_NoError) {
3504 printf("unexpected error %d code while loading compilation database\n", ec);
3505 errorCode = -1;
3506 goto cdb_end;
3507 }
3508
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003509 if (chdir(buildDir) != 0) {
3510 printf("Could not chdir to %s\n", buildDir);
3511 errorCode = -1;
3512 goto cdb_end;
3513 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003514
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003515 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003516 if (!CCmds) {
3517 printf("compilation db is empty\n");
3518 errorCode = -1;
3519 goto cdb_end;
3520 }
3521
3522 numCmds = clang_CompileCommands_getSize(CCmds);
3523
3524 if (numCmds==0) {
3525 fprintf(stderr, "should not get an empty compileCommand set\n");
3526 errorCode = -1;
3527 goto cdb_end;
3528 }
3529
3530 for (i=0; i<numCmds && errorCode == 0; ++i) {
3531 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3532
3533 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003534 if (chdir(clang_getCString(wd)) != 0) {
3535 printf("Could not chdir to %s\n", clang_getCString(wd));
3536 errorCode = -1;
3537 goto cdb_end;
3538 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003539 clang_disposeString(wd);
3540
3541 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3542 if (numArgs > MAX_COMPILE_ARGS){
3543 fprintf(stderr, "got more compile arguments than maximum\n");
3544 errorCode = -1;
3545 goto cdb_end;
3546 }
3547 for (a=0; a<numArgs; ++a) {
3548 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3549 args[a] = clang_getCString(cxargs[a]);
3550 }
3551
3552 errorCode = index_compile_args(numArgs, args, idxAction,
3553 /*importedASTs=*/0, check_prefix);
3554
3555 for (a=0; a<numArgs; ++a)
3556 clang_disposeString(cxargs[a]);
3557 }
3558 } else {
3559 printf("database loading failed with error code %d.\n", ec);
3560 errorCode = -1;
3561 }
3562
3563 cdb_end:
3564 clang_CompileCommands_dispose(CCmds);
3565 clang_CompilationDatabase_dispose(db);
3566 free(tmp);
3567
3568 }
3569
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003570 clang_IndexAction_dispose(idxAction);
3571 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003572 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003573}
3574
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003575int perform_token_annotation(int argc, const char **argv) {
3576 const char *input = argv[1];
3577 char *filename = 0;
3578 unsigned line, second_line;
3579 unsigned column, second_column;
3580 CXIndex CIdx;
3581 CXTranslationUnit TU = 0;
3582 int errorCode;
3583 struct CXUnsavedFile *unsaved_files = 0;
3584 int num_unsaved_files = 0;
3585 CXToken *tokens;
3586 unsigned num_tokens;
3587 CXSourceRange range;
3588 CXSourceLocation startLoc, endLoc;
3589 CXFile file = 0;
3590 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003591 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003592 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003593 unsigned i;
3594
3595 input += strlen("-test-annotate-tokens=");
3596 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3597 &second_line, &second_column)))
3598 return errorCode;
3599
Richard Smith1ea42eb2012-07-05 08:20:49 +00003600 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3601 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003602 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003603 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003604
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003605 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003606 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3607 argv + num_unsaved_files + 2,
3608 argc - num_unsaved_files - 3,
3609 unsaved_files,
3610 num_unsaved_files,
3611 getDefaultParsingOptions(), &TU);
3612 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003613 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003614 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003615 clang_disposeIndex(CIdx);
3616 free(filename);
3617 free_remapped_files(unsaved_files, num_unsaved_files);
3618 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003619 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003620 errorCode = 0;
3621
Richard Smith1ea42eb2012-07-05 08:20:49 +00003622 if (checkForErrors(TU) != 0) {
3623 errorCode = -1;
3624 goto teardown;
3625 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003626
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003627 if (getenv("CINDEXTEST_EDITING")) {
3628 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003629 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3630 clang_defaultReparseOptions(TU));
3631 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003632 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003633 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003634 errorCode = -1;
3635 goto teardown;
3636 }
3637 }
3638 }
3639
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003640 if (checkForErrors(TU) != 0) {
3641 errorCode = -1;
3642 goto teardown;
3643 }
3644
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003645 file = clang_getFile(TU, filename);
3646 if (!file) {
3647 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3648 errorCode = -1;
3649 goto teardown;
3650 }
3651
3652 startLoc = clang_getLocation(TU, file, line, column);
3653 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003654 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003655 column);
3656 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003657 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003658 }
3659
3660 endLoc = clang_getLocation(TU, file, second_line, second_column);
3661 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003662 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003663 second_line, second_column);
3664 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003665 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003666 }
3667
3668 range = clang_getRange(startLoc, endLoc);
3669 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003670
3671 if (checkForErrors(TU) != 0) {
3672 errorCode = -1;
3673 goto teardown;
3674 }
3675
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003676 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3677 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003678
3679 if (checkForErrors(TU) != 0) {
3680 errorCode = -1;
3681 goto teardown;
3682 }
3683
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003684 skipped_ranges = clang_getSkippedRanges(TU, file);
3685 for (i = 0; i != skipped_ranges->count; ++i) {
3686 unsigned start_line, start_column, end_line, end_column;
3687 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3688 0, &start_line, &start_column, 0);
3689 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3690 0, &end_line, &end_column, 0);
3691 printf("Skipping: ");
3692 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3693 printf("\n");
3694 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003695 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003696
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003697 for (i = 0; i != num_tokens; ++i) {
3698 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003699 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3700 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003701 unsigned start_line, start_column, end_line, end_column;
3702
3703 switch (clang_getTokenKind(tokens[i])) {
3704 case CXToken_Punctuation: kind = "Punctuation"; break;
3705 case CXToken_Keyword: kind = "Keyword"; break;
3706 case CXToken_Identifier: kind = "Identifier"; break;
3707 case CXToken_Literal: kind = "Literal"; break;
3708 case CXToken_Comment: kind = "Comment"; break;
3709 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003710 clang_getSpellingLocation(clang_getRangeStart(extent),
3711 0, &start_line, &start_column, 0);
3712 clang_getSpellingLocation(clang_getRangeEnd(extent),
3713 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003714 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003715 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003716 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003717 if (!clang_isInvalid(cursors[i].kind)) {
3718 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003719 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003720 }
3721 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003722 }
3723 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003724 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003725
3726 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003727 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003728 clang_disposeTranslationUnit(TU);
3729 clang_disposeIndex(CIdx);
3730 free(filename);
3731 free_remapped_files(unsaved_files, num_unsaved_files);
3732 return errorCode;
3733}
3734
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003735static int
3736perform_test_compilation_db(const char *database, int argc, const char **argv) {
3737 CXCompilationDatabase db;
3738 CXCompileCommands CCmds;
3739 CXCompileCommand CCmd;
3740 CXCompilationDatabase_Error ec;
3741 CXString wd;
3742 CXString arg;
3743 int errorCode = 0;
3744 char *tmp;
3745 unsigned len;
3746 char *buildDir;
3747 int i, j, a, numCmds, numArgs;
3748
3749 len = strlen(database);
3750 tmp = (char *) malloc(len+1);
3751 memcpy(tmp, database, len+1);
3752 buildDir = dirname(tmp);
3753
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003754 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003755
3756 if (db) {
3757
3758 if (ec!=CXCompilationDatabase_NoError) {
3759 printf("unexpected error %d code while loading compilation database\n", ec);
3760 errorCode = -1;
3761 goto cdb_end;
3762 }
3763
3764 for (i=0; i<argc && errorCode==0; ) {
3765 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003766 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003767
3768 if (!CCmds) {
3769 printf("file %s not found in compilation db\n", argv[i+1]);
3770 errorCode = -1;
3771 break;
3772 }
3773
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003774 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003775
3776 if (numCmds==0) {
3777 fprintf(stderr, "should not get an empty compileCommand set for file"
3778 " '%s'\n", argv[i+1]);
3779 errorCode = -1;
3780 break;
3781 }
3782
3783 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003784 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003785
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003786 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003787 printf("workdir:'%s'", clang_getCString(wd));
3788 clang_disposeString(wd);
3789
3790 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003791 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003792 for (a=0; a<numArgs; ++a) {
3793 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003794 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003795 printf("%s", clang_getCString(arg));
3796 clang_disposeString(arg);
3797 }
3798 printf("'\n");
3799 }
3800
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003801 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003802
3803 i += 2;
3804 }
3805 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003806 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003807 } else {
3808 printf("database loading failed with error code %d.\n", ec);
3809 errorCode = -1;
3810 }
3811
3812cdb_end:
3813 free(tmp);
3814
3815 return errorCode;
3816}
3817
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003818/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003819/* USR printing. */
3820/******************************************************************************/
3821
3822static int insufficient_usr(const char *kind, const char *usage) {
3823 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3824 return 1;
3825}
3826
3827static unsigned isUSR(const char *s) {
3828 return s[0] == 'c' && s[1] == ':';
3829}
3830
3831static int not_usr(const char *s, const char *arg) {
3832 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3833 return 1;
3834}
3835
3836static void print_usr(CXString usr) {
3837 const char *s = clang_getCString(usr);
3838 printf("%s\n", s);
3839 clang_disposeString(usr);
3840}
3841
3842static void display_usrs() {
3843 fprintf(stderr, "-print-usrs options:\n"
3844 " ObjCCategory <class name> <category name>\n"
3845 " ObjCClass <class name>\n"
3846 " ObjCIvar <ivar name> <class USR>\n"
3847 " ObjCMethod <selector> [0=class method|1=instance method] "
3848 "<class USR>\n"
3849 " ObjCProperty <property name> <class USR>\n"
3850 " ObjCProtocol <protocol name>\n");
3851}
3852
3853int print_usrs(const char **I, const char **E) {
3854 while (I != E) {
3855 const char *kind = *I;
3856 unsigned len = strlen(kind);
3857 switch (len) {
3858 case 8:
3859 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3860 if (I + 2 >= E)
3861 return insufficient_usr(kind, "<ivar name> <class USR>");
3862 if (!isUSR(I[2]))
3863 return not_usr("<class USR>", I[2]);
3864 else {
3865 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003866 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003867 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003868 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3869 }
3870
3871 I += 3;
3872 continue;
3873 }
3874 break;
3875 case 9:
3876 if (memcmp(kind, "ObjCClass", 9) == 0) {
3877 if (I + 1 >= E)
3878 return insufficient_usr(kind, "<class name>");
3879 print_usr(clang_constructUSR_ObjCClass(I[1]));
3880 I += 2;
3881 continue;
3882 }
3883 break;
3884 case 10:
3885 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3886 if (I + 3 >= E)
3887 return insufficient_usr(kind, "<method selector> "
3888 "[0=class method|1=instance method] <class USR>");
3889 if (!isUSR(I[3]))
3890 return not_usr("<class USR>", I[3]);
3891 else {
3892 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003893 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003894 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003895 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3896 }
3897 I += 4;
3898 continue;
3899 }
3900 break;
3901 case 12:
3902 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3903 if (I + 2 >= E)
3904 return insufficient_usr(kind, "<class name> <category name>");
3905 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3906 I += 3;
3907 continue;
3908 }
3909 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3910 if (I + 1 >= E)
3911 return insufficient_usr(kind, "<protocol name>");
3912 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3913 I += 2;
3914 continue;
3915 }
3916 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3917 if (I + 2 >= E)
3918 return insufficient_usr(kind, "<property name> <class USR>");
3919 if (!isUSR(I[2]))
3920 return not_usr("<class USR>", I[2]);
3921 else {
3922 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003923 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003924 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003925 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3926 }
3927 I += 3;
3928 continue;
3929 }
3930 break;
3931 default:
3932 break;
3933 }
3934 break;
3935 }
3936
3937 if (I != E) {
3938 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3939 display_usrs();
3940 return 1;
3941 }
3942 return 0;
3943}
3944
3945int print_usrs_file(const char *file_name) {
3946 char line[2048];
3947 const char *args[128];
3948 unsigned numChars = 0;
3949
3950 FILE *fp = fopen(file_name, "r");
3951 if (!fp) {
3952 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3953 return 1;
3954 }
3955
3956 /* This code is not really all that safe, but it works fine for testing. */
3957 while (!feof(fp)) {
3958 char c = fgetc(fp);
3959 if (c == '\n') {
3960 unsigned i = 0;
3961 const char *s = 0;
3962
3963 if (numChars == 0)
3964 continue;
3965
3966 line[numChars] = '\0';
3967 numChars = 0;
3968
3969 if (line[0] == '/' && line[1] == '/')
3970 continue;
3971
3972 s = strtok(line, " ");
3973 while (s) {
3974 args[i] = s;
3975 ++i;
3976 s = strtok(0, " ");
3977 }
3978 if (print_usrs(&args[0], &args[i]))
3979 return 1;
3980 }
3981 else
3982 line[numChars++] = c;
3983 }
3984
3985 fclose(fp);
3986 return 0;
3987}
3988
3989/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003990/* Command line processing. */
3991/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003992int write_pch_file(const char *filename, int argc, const char *argv[]) {
3993 CXIndex Idx;
3994 CXTranslationUnit TU;
3995 struct CXUnsavedFile *unsaved_files = 0;
3996 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003997 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003998 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003999
Stefanus Du Toitb3318502013-03-01 21:41:22 +00004000 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00004001
4002 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
4003 clang_disposeIndex(Idx);
4004 return -1;
4005 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004006
4007 Err = clang_parseTranslationUnit2(
4008 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
4009 unsaved_files, num_unsaved_files,
4010 CXTranslationUnit_Incomplete |
4011 CXTranslationUnit_DetailedPreprocessingRecord |
4012 CXTranslationUnit_ForSerialization,
4013 &TU);
4014 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00004015 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004016 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00004017 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004018 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00004019 clang_disposeIndex(Idx);
4020 return 1;
4021 }
4022
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004023 switch (clang_saveTranslationUnit(TU, filename,
4024 clang_defaultSaveOptions(TU))) {
4025 case CXSaveError_None:
4026 break;
4027
4028 case CXSaveError_TranslationErrors:
4029 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4030 filename);
4031 result = 2;
4032 break;
4033
4034 case CXSaveError_InvalidTU:
4035 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4036 filename);
4037 result = 3;
4038 break;
4039
4040 case CXSaveError_Unknown:
4041 default:
4042 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4043 result = 1;
4044 break;
4045 }
4046
Douglas Gregore9386682010-08-13 05:36:37 +00004047 clang_disposeTranslationUnit(TU);
4048 free_remapped_files(unsaved_files, num_unsaved_files);
4049 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004050 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004051}
4052
4053/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004054/* Serialized diagnostics. */
4055/******************************************************************************/
4056
4057static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4058 switch (error) {
4059 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4060 case CXLoadDiag_None: break;
4061 case CXLoadDiag_Unknown: return "Unknown";
4062 case CXLoadDiag_InvalidFile: return "Invalid File";
4063 }
4064 return "None";
4065}
4066
4067static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4068 switch (severity) {
4069 case CXDiagnostic_Note: return "note";
4070 case CXDiagnostic_Error: return "error";
4071 case CXDiagnostic_Fatal: return "fatal";
4072 case CXDiagnostic_Ignored: return "ignored";
4073 case CXDiagnostic_Warning: return "warning";
4074 }
4075 return "unknown";
4076}
4077
4078static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004079 if (indent == 0)
4080 return;
4081 fprintf(stderr, "+");
4082 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004083 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004084 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004085 --indent;
4086 }
4087}
4088
4089static void printLocation(CXSourceLocation L) {
4090 CXFile File;
4091 CXString FileName;
4092 unsigned line, column, offset;
4093
4094 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4095 FileName = clang_getFileName(File);
4096
4097 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4098 clang_disposeString(FileName);
4099}
4100
4101static void printRanges(CXDiagnostic D, unsigned indent) {
4102 unsigned i, n = clang_getDiagnosticNumRanges(D);
4103
4104 for (i = 0; i < n; ++i) {
4105 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004106 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004107 Start = clang_getRangeStart(SR);
4108 End = clang_getRangeEnd(SR);
4109
4110 printIndent(indent);
4111 fprintf(stderr, "Range: ");
4112 printLocation(Start);
4113 fprintf(stderr, " ");
4114 printLocation(End);
4115 fprintf(stderr, "\n");
4116 }
4117}
4118
4119static void printFixIts(CXDiagnostic D, unsigned indent) {
4120 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004121 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004122 for (i = 0 ; i < n; ++i) {
4123 CXSourceRange ReplacementRange;
4124 CXString text;
4125 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4126
4127 printIndent(indent);
4128 fprintf(stderr, "FIXIT: (");
4129 printLocation(clang_getRangeStart(ReplacementRange));
4130 fprintf(stderr, " - ");
4131 printLocation(clang_getRangeEnd(ReplacementRange));
4132 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4133 clang_disposeString(text);
4134 }
4135}
4136
4137static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004138 unsigned i, n;
4139
Ted Kremenekd010ba42011-11-10 08:43:12 +00004140 if (!Diags)
4141 return;
4142
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004143 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004144 for (i = 0; i < n; ++i) {
4145 CXSourceLocation DiagLoc;
4146 CXDiagnostic D;
4147 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004148 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004149 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004150 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004151
4152 D = clang_getDiagnosticInSet(Diags, i);
4153 DiagLoc = clang_getDiagnosticLocation(D);
4154 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4155 FileName = clang_getFileName(File);
4156 DiagSpelling = clang_getDiagnosticSpelling(D);
4157
4158 printIndent(indent);
4159
4160 fprintf(stderr, "%s:%d:%d: %s: %s",
4161 clang_getCString(FileName),
4162 line,
4163 column,
4164 getSeverityString(clang_getDiagnosticSeverity(D)),
4165 clang_getCString(DiagSpelling));
4166
4167 DiagOption = clang_getDiagnosticOption(D, 0);
4168 DiagOptionStr = clang_getCString(DiagOption);
4169 if (DiagOptionStr) {
4170 fprintf(stderr, " [%s]", DiagOptionStr);
4171 }
4172
Ted Kremenek26a6d492012-04-12 00:03:31 +00004173 DiagCat = clang_getDiagnosticCategoryText(D);
4174 DiagCatStr = clang_getCString(DiagCat);
4175 if (DiagCatStr) {
4176 fprintf(stderr, " [%s]", DiagCatStr);
4177 }
4178
Ted Kremenekd010ba42011-11-10 08:43:12 +00004179 fprintf(stderr, "\n");
4180
4181 printRanges(D, indent);
4182 printFixIts(D, indent);
4183
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004184 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004185 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4186
4187 clang_disposeString(FileName);
4188 clang_disposeString(DiagSpelling);
4189 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004190 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004191 }
4192}
4193
4194static int read_diagnostics(const char *filename) {
4195 enum CXLoadDiag_Error error;
4196 CXString errorString;
4197 CXDiagnosticSet Diags = 0;
4198
4199 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4200 if (!Diags) {
4201 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4202 getDiagnosticCodeStr(error),
4203 clang_getCString(errorString));
4204 clang_disposeString(errorString);
4205 return 1;
4206 }
4207
4208 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004209 fprintf(stderr, "Number of diagnostics: %d\n",
4210 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004211 clang_disposeDiagnosticSet(Diags);
4212 return 0;
4213}
4214
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004215static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004216 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004217 return 0;
4218}
4219
Ted Kremenekd010ba42011-11-10 08:43:12 +00004220/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004221/* Command line processing. */
4222/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004223
Douglas Gregor720d0052010-01-20 21:32:04 +00004224static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004225 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004226 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004227 if (strcmp(s, "-usrs") == 0)
4228 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004229 if (strncmp(s, "-memory-usage", 13) == 0)
4230 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004231 return NULL;
4232}
4233
Ted Kremenekef3339b2009-11-17 18:09:14 +00004234static void print_usage(void) {
4235 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004236 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004237 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004238 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004239 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4240 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004241 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4242 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004243 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004244 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004245 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004246 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004247 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004248 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004249 "[FileCheck prefix]\n");
4250 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004251 " c-index-test -test-load-tu <AST file> <symbol filter> "
4252 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004253 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4254 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004255 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004256 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004257 " c-index-test -test-load-source-memory-usage "
4258 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004259 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4260 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004261 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004262 " c-index-test -test-load-source-usrs-memory-usage "
4263 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004264 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4265 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004266 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004267 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004268 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004269 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004270 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004271 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004272 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004273 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004274 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004275 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004276 " c-index-test -write-pch <file> <compiler arguments>\n");
4277 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004278 " c-index-test -compilation-db [lookup <filename>] database\n");
4279 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004280 " c-index-test -print-build-session-timestamp\n");
4281 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004282 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004283 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004284 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004285 " all - load all symbols, including those from PCH\n"
4286 " local - load all symbols except those in PCH\n"
4287 " category - only load ObjC categories (non-PCH)\n"
4288 " interface - only load ObjC interfaces (non-PCH)\n"
4289 " protocol - only load ObjC protocols (non-PCH)\n"
4290 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004291 " typedef - only load typdefs (non-PCH)\n"
4292 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004293}
4294
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004295/***/
4296
4297int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004298 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004299 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4300 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004301 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004302 return perform_code_completion(argc, argv, 0);
4303 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4304 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004305 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004306 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4307 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4308 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4309 inspect_evaluate_cursor);
4310 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4311 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4312 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004313 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4314 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004315 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4316 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004317 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004318 return index_file(argc - 2, argv + 2, /*full=*/0);
4319 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4320 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004321 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4322 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004323 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4324 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004325 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004326 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004327 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004328 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4329 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004330 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004331 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4332 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4333 if (I) {
4334 int trials = atoi(argv[2]);
4335 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4336 NULL);
4337 }
4338 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004339 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004340 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004341
4342 PostVisitTU postVisit = 0;
4343 if (strstr(argv[1], "-memory-usage"))
4344 postVisit = PrintMemoryUsage;
4345
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004346 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004347 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4348 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004349 }
4350 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004351 return perform_file_scan(argv[2], argv[3],
4352 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004353 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4354 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004355 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4356 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4357 PrintInclusionStack);
4358 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4359 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4360 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004361 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4362 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4363 NULL);
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004364 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4365 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4366 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004367 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004368 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004369 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004370 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4371 return perform_test_load_source(argc - 2, argv + 2, "all",
4372 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004373 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4374 return perform_test_load_source(argc - 2, argv + 2, "all",
4375 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004376 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4377 return perform_test_load_source(argc - 2, argv + 2, "all",
4378 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004379 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4380 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004381 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4382 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004383 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4384 if (argc > 2)
4385 return print_usrs(argv + 2, argv + argc);
4386 else {
4387 display_usrs();
4388 return 1;
4389 }
4390 }
4391 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4392 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004393 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4394 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004395 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4396 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004397 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4398 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004399
Ted Kremenekef3339b2009-11-17 18:09:14 +00004400 print_usage();
4401 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004402}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004403
4404/***/
4405
4406/* We intentionally run in a separate thread to ensure we at least minimal
4407 * testing of a multithreaded environment (for example, having a reduced stack
4408 * size). */
4409
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004410typedef struct thread_info {
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004411 int (*main_func)(int argc, const char **argv);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004412 int argc;
4413 const char **argv;
4414 int result;
4415} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004416void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004417 thread_info *client_data = client_data_v;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004418 client_data->result = client_data->main_func(client_data->argc,
4419 client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004420}
4421
4422static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004423 /* stdout, and surprisingly even stderr, are not always flushed on process
4424 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004425 fflush(stdout);
4426 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004427}
4428
4429int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004430 thread_info client_data;
4431
Reid Klecknere931c062014-06-05 00:13:43 +00004432 atexit(flush_atexit);
4433
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004434#ifdef CLANG_HAVE_LIBXML
4435 LIBXML_TEST_VERSION
4436#endif
4437
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004438 client_data.main_func = cindextest_main;
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004439 client_data.argc = argc;
4440 client_data.argv = argv;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004441
4442 if (argc > 1 && strcmp(argv[1], "core") == 0) {
4443 client_data.main_func = indextest_core_main;
4444 --client_data.argc;
4445 ++client_data.argv;
4446 }
4447
4448 if (getenv("CINDEXTEST_NOTHREADS"))
4449 return client_data.main_func(client_data.argc, client_data.argv);
4450
Daniel Dunbar23397c32010-11-04 01:26:31 +00004451 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004452 return client_data.result;
4453}