blob: c76d8fb0e7d180604ff95e67621c9a617304988a [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);
775
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000776 if (clang_CXXField_isMutable(Cursor))
777 printf(" (mutable)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000778 if (clang_CXXMethod_isStatic(Cursor))
779 printf(" (static)");
780 if (clang_CXXMethod_isVirtual(Cursor))
781 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000782 if (clang_CXXMethod_isConst(Cursor))
783 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000784 if (clang_CXXMethod_isPureVirtual(Cursor))
785 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000786 if (clang_Cursor_isVariadic(Cursor))
787 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000788 if (clang_Cursor_isObjCOptional(Cursor))
789 printf(" (@optional)");
790
Ted Kremeneka5940822010-08-26 01:42:22 +0000791 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000792 CXType T =
793 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
794 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000795 printf(" [IBOutletCollection=%s]", clang_getCString(S));
796 clang_disposeString(S);
797 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000798
799 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
800 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
801 unsigned isVirtual = clang_isVirtualBase(Cursor);
802 const char *accessStr = 0;
803
804 switch (access) {
805 case CX_CXXInvalidAccessSpecifier:
806 accessStr = "invalid"; break;
807 case CX_CXXPublic:
808 accessStr = "public"; break;
809 case CX_CXXProtected:
810 accessStr = "protected"; break;
811 case CX_CXXPrivate:
812 accessStr = "private"; break;
813 }
814
815 printf(" [access=%s isVirtual=%s]", accessStr,
816 isVirtual ? "true" : "false");
817 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000818
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000819 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
820 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000821 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
822 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000823 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000824 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000825 clang_getCString(Name), line, column);
826 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000827
828 if (Cursor.kind == CXCursor_FunctionDecl) {
829 /* Collect the template parameter kinds from the base template. */
830 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
831 unsigned I;
832 for (I = 0; I < NumTemplateArgs; I++) {
833 enum CXTemplateArgumentKind TAK =
834 clang_Cursor_getTemplateArgumentKind(Cursor, I);
835 switch(TAK) {
836 case CXTemplateArgumentKind_Type:
837 {
838 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
839 CXString S = clang_getTypeSpelling(T);
840 printf(" [Template arg %d: kind: %d, type: %s]",
841 I, TAK, clang_getCString(S));
842 clang_disposeString(S);
843 }
844 break;
845 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000846 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000847 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
848 break;
849 default:
850 printf(" [Template arg %d: kind: %d]\n", I, TAK);
851 }
852 }
853 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000854 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000855
856 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
857 if (num_overridden) {
858 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000859 LineCol lineCols[50];
860 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000861 printf(" [Overrides ");
862 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000863 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000864 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000865 lineCols[I].line = line;
866 lineCols[I].col = column;
867 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000868 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000869 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
870 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000871 if (I)
872 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000873 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000874 }
875 printf("]");
876 clang_disposeOverriddenCursors(overridden);
877 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000878
879 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000880 CXFile File = clang_getIncludedFile(Cursor);
881 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000882 printf(" (%s)", clang_getCString(Included));
883 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000884
885 if (clang_isFileMultipleIncludeGuarded(TU, File))
886 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000887 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000888
889 CursorExtent = clang_getCursorExtent(Cursor);
890 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
891 CXNameRange_WantQualifier
892 | CXNameRange_WantSinglePiece
893 | CXNameRange_WantTemplateArgs,
894 0);
895 if (!clang_equalRanges(CursorExtent, RefNameRange))
896 PrintRange(RefNameRange, "SingleRefName");
897
898 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
899 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
900 CXNameRange_WantQualifier
901 | CXNameRange_WantTemplateArgs,
902 RefNameRangeNr);
903 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
904 break;
905 if (!clang_equalRanges(CursorExtent, RefNameRange))
906 PrintRange(RefNameRange, "RefName");
907 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000908
Chandler Carruthb2faa592014-05-02 23:30:59 +0000909 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000910
911 {
912 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
913 if (PropAttrs != CXObjCPropertyAttr_noattr) {
914 printf(" [");
915 #define PRINT_PROP_ATTR(A) \
916 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
917 PRINT_PROP_ATTR(readonly);
918 PRINT_PROP_ATTR(getter);
919 PRINT_PROP_ATTR(assign);
920 PRINT_PROP_ATTR(readwrite);
921 PRINT_PROP_ATTR(retain);
922 PRINT_PROP_ATTR(copy);
923 PRINT_PROP_ATTR(nonatomic);
924 PRINT_PROP_ATTR(setter);
925 PRINT_PROP_ATTR(atomic);
926 PRINT_PROP_ATTR(weak);
927 PRINT_PROP_ATTR(strong);
928 PRINT_PROP_ATTR(unsafe_unretained);
929 printf("]");
930 }
931 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000932
933 {
934 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
935 if (QT != CXObjCDeclQualifier_None) {
936 printf(" [");
937 #define PRINT_OBJC_QUAL(A) \
938 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
939 PRINT_OBJC_QUAL(In);
940 PRINT_OBJC_QUAL(Inout);
941 PRINT_OBJC_QUAL(Out);
942 PRINT_OBJC_QUAL(Bycopy);
943 PRINT_OBJC_QUAL(Byref);
944 PRINT_OBJC_QUAL(Oneway);
945 printf("]");
946 }
947 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000948 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000949}
Steve Naroff1054e602009-08-31 00:59:03 +0000950
Ted Kremenek29004672010-02-17 00:41:32 +0000951static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000952 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000953 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000954 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000955 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000956 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000957 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000958 clang_disposeString(source);
959 return "<invalid loc>";
960 }
961 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000962 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000963 clang_disposeString(source);
964 return b;
965 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000966}
967
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000968/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000969/* Callbacks. */
970/******************************************************************************/
971
972typedef void (*PostVisitTU)(CXTranslationUnit);
973
Douglas Gregor33cdd812010-02-18 18:08:43 +0000974void PrintDiagnostic(CXDiagnostic Diagnostic) {
975 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000976 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000977 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000978 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000979 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
980 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000981 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000982
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000983 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000984 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000985
Douglas Gregord770f732010-02-22 23:17:23 +0000986 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
987 fprintf(stderr, "%s\n", clang_getCString(Msg));
988 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000989
Douglas Gregor229bebd2010-11-09 06:24:54 +0000990 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
991 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000992 if (!file)
993 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000994
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000995 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000996 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000997 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000998 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000999 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
1000 CXSourceLocation start = clang_getRangeStart(range);
1001 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +00001002 unsigned start_line, start_column, end_line, end_column;
1003 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001004 clang_getSpellingLocation(start, &start_file, &start_line,
1005 &start_column, 0);
1006 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001007 if (clang_equalLocations(start, end)) {
1008 /* Insertion. */
1009 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001010 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001011 clang_getCString(insertion_text), start_line, start_column);
1012 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1013 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001014 if (start_file == file && end_file == file) {
1015 fprintf(out, "FIX-IT: Remove ");
1016 PrintExtent(out, start_line, start_column, end_line, end_column);
1017 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001018 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001019 } else {
1020 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001021 if (start_file == end_file) {
1022 fprintf(out, "FIX-IT: Replace ");
1023 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001024 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001025 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001026 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001027 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001028 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001029}
1030
Ted Kremenek914c7e62012-02-14 02:46:03 +00001031void PrintDiagnosticSet(CXDiagnosticSet Set) {
1032 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1033 for ( ; i != n ; ++i) {
1034 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1035 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001036 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001037 if (ChildDiags)
1038 PrintDiagnosticSet(ChildDiags);
1039 }
1040}
1041
1042void PrintDiagnostics(CXTranslationUnit TU) {
1043 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1044 PrintDiagnosticSet(TUSet);
1045 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001046}
1047
Ted Kremenek83f642e2011-04-18 22:47:10 +00001048void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001049 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001050 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001051 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001052 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001053 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001054 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001055 unsigned long amount = usage.entries[i].amount;
1056 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001057 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001058 ((double) amount)/(1024*1024));
1059 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001060 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001061 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001062 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001063}
1064
Ted Kremenekb478ff42010-01-26 17:59:48 +00001065/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001066/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001067/******************************************************************************/
1068
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001069static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001070 CXSourceRange extent = clang_getCursorExtent(C);
1071 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001072}
1073
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001074/* Data used by the visitors. */
1075typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001076 CXTranslationUnit TU;
1077 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001078 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001079} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001080
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001081
Ted Kremenek29004672010-02-17 00:41:32 +00001082enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001083 CXCursor Parent,
1084 CXClientData ClientData) {
1085 VisitorData *Data = (VisitorData *)ClientData;
1086 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001087 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001088 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001089 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001090 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001091 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001092 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001093 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001094 if (clang_isDeclaration(Cursor.kind)) {
1095 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1096 const char *accessStr = 0;
1097
1098 switch (access) {
1099 case CX_CXXInvalidAccessSpecifier: break;
1100 case CX_CXXPublic:
1101 accessStr = "public"; break;
1102 case CX_CXXProtected:
1103 accessStr = "protected"; break;
1104 case CX_CXXPrivate:
1105 accessStr = "private"; break;
1106 }
1107
1108 if (accessStr)
1109 printf(" [access=%s]", accessStr);
1110 }
Ted Kremenek29004672010-02-17 00:41:32 +00001111 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001112 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001113 }
Ted Kremenek29004672010-02-17 00:41:32 +00001114
Douglas Gregor720d0052010-01-20 21:32:04 +00001115 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001116}
Steve Naroffa1c72842009-08-28 15:28:48 +00001117
Ted Kremenek29004672010-02-17 00:41:32 +00001118static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001119 CXCursor Parent,
1120 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001121 const char *startBuf, *endBuf;
1122 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1123 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001124 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001125
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001126 if (Cursor.kind != CXCursor_FunctionDecl ||
1127 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001128 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001129
1130 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1131 &startLine, &startColumn,
1132 &endLine, &endColumn);
1133 /* Probe the entire body, looking for both decls and refs. */
1134 curLine = startLine;
1135 curColumn = startColumn;
1136
1137 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001138 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001139 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001140 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001141
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001142 if (*startBuf == '\n') {
1143 startBuf++;
1144 curLine++;
1145 curColumn = 1;
1146 } else if (*startBuf != '\t')
1147 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001148
Douglas Gregor66a58812010-01-18 22:46:11 +00001149 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001150 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001151
Douglas Gregor4f46e782010-01-19 21:36:55 +00001152 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001153 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001154 CXSourceLocation RefLoc
1155 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001156 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001157 if (Ref.kind == CXCursor_NoDeclFound) {
1158 /* Nothing found here; that's fine. */
1159 } else if (Ref.kind != CXCursor_FunctionDecl) {
1160 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1161 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001162 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001163 printf("\n");
1164 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001165 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001166 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001167 startBuf++;
1168 }
Ted Kremenek29004672010-02-17 00:41:32 +00001169
Douglas Gregor720d0052010-01-20 21:32:04 +00001170 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001171}
1172
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001173/******************************************************************************/
1174/* USR testing. */
1175/******************************************************************************/
1176
Douglas Gregor720d0052010-01-20 21:32:04 +00001177enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1178 CXClientData ClientData) {
1179 VisitorData *Data = (VisitorData *)ClientData;
1180 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001181 CXString USR = clang_getCursorUSR(C);
1182 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001183 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001184 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001185 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001186 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001187 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1188
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001189 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001190 printf("\n");
1191 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001192
Douglas Gregor720d0052010-01-20 21:32:04 +00001193 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001194 }
1195
Douglas Gregor720d0052010-01-20 21:32:04 +00001196 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001197}
1198
1199/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001200/* Inclusion stack testing. */
1201/******************************************************************************/
1202
1203void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1204 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001205
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001206 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001207 CXString fname;
1208
1209 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001210 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001211 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001212
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001213 for (i = 0; i < includeStackLen; ++i) {
1214 CXFile includingFile;
1215 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001216 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1217 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001218 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001219 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001220 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001221 }
1222 printf("\n");
1223}
1224
1225void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001226 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001227}
1228
1229/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001230/* Linkage testing. */
1231/******************************************************************************/
1232
1233static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1234 CXClientData d) {
1235 const char *linkage = 0;
1236
1237 if (clang_isInvalid(clang_getCursorKind(cursor)))
1238 return CXChildVisit_Recurse;
1239
1240 switch (clang_getCursorLinkage(cursor)) {
1241 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001242 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1243 case CXLinkage_Internal: linkage = "Internal"; break;
1244 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1245 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001246 }
1247
1248 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001249 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001250 printf("linkage=%s\n", linkage);
1251 }
1252
1253 return CXChildVisit_Recurse;
1254}
1255
1256/******************************************************************************/
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00001257/* Visibility testing. */
1258/******************************************************************************/
1259
1260static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1261 CXClientData d) {
1262 const char *visibility = 0;
1263
1264 if (clang_isInvalid(clang_getCursorKind(cursor)))
1265 return CXChildVisit_Recurse;
1266
1267 switch (clang_getCursorVisibility(cursor)) {
1268 case CXVisibility_Invalid: break;
1269 case CXVisibility_Hidden: visibility = "Hidden"; break;
1270 case CXVisibility_Protected: visibility = "Protected"; break;
1271 case CXVisibility_Default: visibility = "Default"; break;
1272 }
1273
1274 if (visibility) {
1275 PrintCursor(cursor, NULL);
1276 printf("visibility=%s\n", visibility);
1277 }
1278
1279 return CXChildVisit_Recurse;
1280}
1281
1282/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001283/* Typekind testing. */
1284/******************************************************************************/
1285
Dmitri Gribenko00353722013-02-15 21:15:49 +00001286static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1287 CXString TypeSpelling, TypeKindSpelling;
1288
1289 TypeSpelling = clang_getTypeSpelling(T);
1290 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1291 printf(Format,
1292 clang_getCString(TypeSpelling),
1293 clang_getCString(TypeKindSpelling));
1294 clang_disposeString(TypeSpelling);
1295 clang_disposeString(TypeKindSpelling);
1296}
1297
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001298static enum CXVisitorResult FieldVisitor(CXCursor C,
1299 CXClientData client_data) {
1300 (*(int *) client_data)+=1;
1301 return CXVisit_Continue;
1302}
1303
Dmitri Gribenko00353722013-02-15 21:15:49 +00001304static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1305 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001306 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001307 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001308 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001309 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001310 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001311 if (clang_isConstQualifiedType(T))
1312 printf(" const");
1313 if (clang_isVolatileQualifiedType(T))
1314 printf(" volatile");
1315 if (clang_isRestrictQualifiedType(T))
1316 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001317 if (RQ == CXRefQualifier_LValue)
1318 printf(" lvalue-ref-qualifier");
1319 if (RQ == CXRefQualifier_RValue)
1320 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001321 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001322 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001323 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001324 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001325 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001326 }
1327 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001328 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001329 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001330 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001331 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001332 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001333 }
1334 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001335 /* Print the argument types if they exist. */
1336 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001337 int NumArgs = clang_Cursor_getNumArguments(cursor);
1338 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001339 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001340 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001341 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001342 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001343 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001344 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001345 }
1346 }
1347 printf("]");
1348 }
1349 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001350 /* Print the template argument types if they exist. */
1351 {
1352 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1353 if (NumTArgs != -1 && NumTArgs != 0) {
1354 int i;
1355 printf(" [templateargs/%d=", NumTArgs);
1356 for (i = 0; i < NumTArgs; ++i) {
1357 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1358 if (TArg.kind != CXType_Invalid) {
1359 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1360 }
1361 }
1362 printf("]");
1363 }
1364 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001365 /* Print if this is a non-POD type. */
1366 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001367 /* Print the pointee type. */
1368 {
1369 CXType PT = clang_getPointeeType(T);
1370 if (PT.kind != CXType_Invalid) {
1371 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1372 }
1373 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001374 /* Print the number of fields if they exist. */
1375 {
1376 int numFields = 0;
1377 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1378 if (numFields != 0) {
1379 printf(" [nbFields=%d]", numFields);
1380 }
1381 /* Print if it is an anonymous record. */
1382 {
1383 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1384 if (isAnon != 0) {
1385 printf(" [isAnon=%d]", isAnon);
1386 }
1387 }
1388 }
1389 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001390
Ted Kremenek6bca9842010-05-14 21:29:26 +00001391 printf("\n");
1392 }
1393 return CXChildVisit_Recurse;
1394}
1395
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001396static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1397 CXClientData d) {
1398 CXType T;
1399 enum CXCursorKind K = clang_getCursorKind(cursor);
1400 if (clang_isInvalid(K))
1401 return CXChildVisit_Recurse;
1402 T = clang_getCursorType(cursor);
1403 PrintCursor(cursor, NULL);
1404 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1405 /* Print the type sizeof if applicable. */
1406 {
1407 long long Size = clang_Type_getSizeOf(T);
1408 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001409 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001410 }
1411 }
1412 /* Print the type alignof if applicable. */
1413 {
1414 long long Align = clang_Type_getAlignOf(T);
1415 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001416 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001417 }
1418 }
1419 /* Print the record field offset if applicable. */
1420 {
Nico Weber82098cb2014-04-24 04:14:12 +00001421 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1422 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001423 /* recurse to get the first parent record that is not anonymous. */
1424 CXCursor Parent, Record;
1425 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001426 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001427 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001428 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001429 Record = Parent;
1430 Parent = clang_getCursorSemanticParent(Record);
1431 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1432 /* Recurse as long as the parent is a CXType_Record and the Record
1433 is anonymous */
1434 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1435 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001436 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001437 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001438 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001439 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1440 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001441 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001442 } else {
1443 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001444 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001445 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001446 }
1447 }
Nico Weber82098cb2014-04-24 04:14:12 +00001448 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001449 }
1450 /* Print if its a bitfield */
1451 {
1452 int IsBitfield = clang_Cursor_isBitField(cursor);
1453 if (IsBitfield)
1454 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1455 }
1456 printf("\n");
1457 return CXChildVisit_Recurse;
1458}
1459
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001460/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001461/* Mangling testing. */
1462/******************************************************************************/
1463
1464static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1465 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001466 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001467 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1468 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001469 PrintCursor(cursor, NULL);
1470 MangledName = clang_Cursor_getMangling(cursor);
1471 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001472 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001473 return CXChildVisit_Continue;
1474}
1475
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001476static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1477 CXClientData d) {
1478 unsigned I, E;
1479 CXStringSet *Manglings = NULL;
1480 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1481 return CXChildVisit_Recurse;
1482 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1483 return CXChildVisit_Recurse;
1484 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1485 return CXChildVisit_Continue;
1486 PrintCursor(cursor, NULL);
1487 Manglings = clang_Cursor_getCXXManglings(cursor);
1488 for (I = 0, E = Manglings->Count; I < E; ++I)
1489 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1490 clang_disposeStringSet(Manglings);
1491 printf("\n");
1492 return CXChildVisit_Recurse;
1493}
1494
Eli Bendersky44a206f2014-07-31 18:04:56 +00001495/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001496/* Bitwidth testing. */
1497/******************************************************************************/
1498
1499static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1500 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001501 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001502 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1503 return CXChildVisit_Recurse;
1504
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001505 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001506 if (Bitwidth >= 0) {
1507 PrintCursor(cursor, NULL);
1508 printf(" bitwidth=%d\n", Bitwidth);
1509 }
1510
1511 return CXChildVisit_Recurse;
1512}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001513
1514/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001515/* Type declaration testing */
1516/******************************************************************************/
1517
1518static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1519 CXClientData d) {
1520 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1521
1522 if (clang_isDeclaration(typeDeclaration.kind)) {
1523 PrintCursor(cursor, NULL);
1524 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1525 }
1526
1527 return CXChildVisit_Recurse;
1528}
1529
1530/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001531/* Loading ASTs/source. */
1532/******************************************************************************/
1533
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001534static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001535 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001536 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001537 PostVisitTU PV,
1538 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001539
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001540 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001541 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001542
1543 if (Visitor) {
1544 enum CXCursorKind K = CXCursor_NotImplemented;
1545 enum CXCursorKind *ck = &K;
1546 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001547
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001548 /* Perform some simple filtering. */
1549 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001550 else if (!strcmp(filter, "all-display") ||
1551 !strcmp(filter, "local-display")) {
1552 ck = NULL;
1553 want_display_name = 1;
1554 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001555 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001556 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1557 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1558 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1559 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1560 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1561 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1562 else {
1563 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1564 return 1;
1565 }
Ted Kremenek29004672010-02-17 00:41:32 +00001566
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001567 Data.TU = TU;
1568 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001569 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001570 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001571 }
Ted Kremenek29004672010-02-17 00:41:32 +00001572
Ted Kremenekb478ff42010-01-26 17:59:48 +00001573 if (PV)
1574 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001575
Douglas Gregor33cdd812010-02-18 18:08:43 +00001576 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001577 if (checkForErrors(TU) != 0) {
1578 clang_disposeTranslationUnit(TU);
1579 return -1;
1580 }
1581
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001582 clang_disposeTranslationUnit(TU);
1583 return 0;
1584}
1585
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001586int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001587 const char *prefix, CXCursorVisitor Visitor,
1588 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001589 CXIndex Idx;
1590 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001591 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001592 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001593 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001594 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001595
Ted Kremenek50228be2010-02-11 07:41:25 +00001596 if (!CreateTranslationUnit(Idx, file, &TU)) {
1597 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001598 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001599 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001600
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001601 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001602 clang_disposeIndex(Idx);
1603 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001604}
1605
Ted Kremenekb478ff42010-01-26 17:59:48 +00001606int perform_test_load_source(int argc, const char **argv,
1607 const char *filter, CXCursorVisitor Visitor,
1608 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001609 CXIndex Idx;
1610 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001611 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001612 struct CXUnsavedFile *unsaved_files = 0;
1613 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001614 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001615 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001616 unsigned Repeats = 0;
1617 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001618
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001619 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001620 (!strcmp(filter, "local") ||
1621 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001622 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001623
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001624 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1625 argc--;
1626 argv++;
1627 }
1628
Ted Kremenek50228be2010-02-11 07:41:25 +00001629 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1630 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001631 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001632 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001633
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001634 if (getenv("CINDEXTEST_EDITING"))
1635 Repeats = 5;
1636
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001637 Err = clang_parseTranslationUnit2(Idx, 0,
1638 argv + num_unsaved_files,
1639 argc - num_unsaved_files,
1640 unsaved_files, num_unsaved_files,
1641 getDefaultParsingOptions(), &TU);
1642 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001643 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001644 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001645 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001646 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001647 return 1;
1648 }
1649
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001650 for (I = 0; I != Repeats; ++I) {
1651 if (checkForErrors(TU) != 0)
1652 return -1;
1653
1654 if (Repeats > 1) {
1655 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1656 clang_defaultReparseOptions(TU));
1657 if (Err != CXError_Success) {
1658 describeLibclangFailure(Err);
1659 free_remapped_files(unsaved_files, num_unsaved_files);
1660 clang_disposeIndex(Idx);
1661 return 1;
1662 }
1663 }
1664 }
1665
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001666 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1667 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001668 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001669 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001670 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001671}
1672
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001673int perform_test_reparse_source(int argc, const char **argv, int trials,
1674 const char *filter, CXCursorVisitor Visitor,
1675 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001676 CXIndex Idx;
1677 CXTranslationUnit TU;
1678 struct CXUnsavedFile *unsaved_files = 0;
1679 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001680 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001681 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001682 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001683 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001684 int remap_after_trial = 0;
1685 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001686
1687 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1688 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001689 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001690
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001691 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1692 clang_disposeIndex(Idx);
1693 return -1;
1694 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001695
1696 for (i = 0; i < argc; ++i) {
1697 if (strcmp(argv[i], "--") == 0)
1698 break;
1699 }
1700 if (i < argc)
1701 compiler_arg_idx = i+1;
1702 if (num_unsaved_files > compiler_arg_idx)
1703 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001704
Daniel Dunbarec29d712010-08-18 23:09:16 +00001705 /* Load the initial translation unit -- we do this without honoring remapped
1706 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001707 Err = clang_parseTranslationUnit2(Idx, 0,
1708 argv + compiler_arg_idx,
1709 argc - compiler_arg_idx,
1710 0, 0, getDefaultParsingOptions(), &TU);
1711 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001712 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001713 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001714 free_remapped_files(unsaved_files, num_unsaved_files);
1715 clang_disposeIndex(Idx);
1716 return 1;
1717 }
1718
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001719 if (checkForErrors(TU) != 0)
1720 return -1;
1721
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001722 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1723 remap_after_trial =
1724 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1725 }
1726
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001727 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001728 free_remapped_files(unsaved_files, num_unsaved_files);
1729 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1730 &unsaved_files, &num_unsaved_files)) {
1731 clang_disposeTranslationUnit(TU);
1732 clang_disposeIndex(Idx);
1733 return -1;
1734 }
1735
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001736 Err = clang_reparseTranslationUnit(
1737 TU,
1738 trial >= remap_after_trial ? num_unsaved_files : 0,
1739 trial >= remap_after_trial ? unsaved_files : 0,
1740 clang_defaultReparseOptions(TU));
1741 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001742 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001743 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001744 clang_disposeTranslationUnit(TU);
1745 free_remapped_files(unsaved_files, num_unsaved_files);
1746 clang_disposeIndex(Idx);
1747 return -1;
1748 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001749
1750 if (checkForErrors(TU) != 0)
1751 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001752 }
1753
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001754 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001755
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001756 free_remapped_files(unsaved_files, num_unsaved_files);
1757 clang_disposeIndex(Idx);
1758 return result;
1759}
1760
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001761/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001762/* Logic for testing clang_getCursor(). */
1763/******************************************************************************/
1764
Douglas Gregor37aa4932011-05-04 00:14:37 +00001765static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001766 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001767 unsigned end_line, unsigned end_col,
1768 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001769 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001770 if (prefix)
1771 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001772 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1773 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001774 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001775 printf("\n");
1776}
1777
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001778static int perform_file_scan(const char *ast_file, const char *source_file,
1779 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001780 CXIndex Idx;
1781 CXTranslationUnit TU;
1782 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001783 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001784 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001785 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001786 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001787
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001788 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001789 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001790 fprintf(stderr, "Could not create Index\n");
1791 return 1;
1792 }
Ted Kremenek29004672010-02-17 00:41:32 +00001793
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001794 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1795 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001796
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001797 if ((fp = fopen(source_file, "r")) == NULL) {
1798 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001799 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001800 return 1;
1801 }
Ted Kremenek29004672010-02-17 00:41:32 +00001802
Douglas Gregor816fd362010-01-22 21:44:22 +00001803 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001804 for (;;) {
1805 CXCursor cursor;
1806 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001807
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001808 if (c == '\n') {
1809 ++line;
1810 col = 1;
1811 } else
1812 ++col;
1813
1814 /* Check the cursor at this position, and dump the previous one if we have
1815 * found something new.
1816 */
1817 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1818 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1819 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001820 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001821 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001822 start_line = line;
1823 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001824 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001825 if (c == EOF)
1826 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001827
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001828 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001829 }
Ted Kremenek29004672010-02-17 00:41:32 +00001830
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001831 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001832 clang_disposeTranslationUnit(TU);
1833 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001834 return 0;
1835}
1836
1837/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001838/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001839/******************************************************************************/
1840
Douglas Gregor9eb77012009-11-07 00:00:49 +00001841/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1842 on failure. If successful, the pointer *filename will contain newly-allocated
1843 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001844int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001845 unsigned *column, unsigned *second_line,
1846 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001847 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001848 const char *last_colon = strrchr(input, ':');
1849 unsigned values[4], i;
1850 unsigned num_values = (second_line && second_column)? 4 : 2;
1851
Douglas Gregor9eb77012009-11-07 00:00:49 +00001852 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001853 if (!last_colon || last_colon == input) {
1854 if (num_values == 4)
1855 fprintf(stderr, "could not parse filename:line:column:line:column in "
1856 "'%s'\n", input);
1857 else
1858 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001859 return 1;
1860 }
1861
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001862 for (i = 0; i != num_values; ++i) {
1863 const char *prev_colon;
1864
1865 /* Parse the next line or column. */
1866 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1867 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001868 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001869 (i % 2 ? "column" : "line"), input);
1870 return 1;
1871 }
Ted Kremenek29004672010-02-17 00:41:32 +00001872
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001873 if (i + 1 == num_values)
1874 break;
1875
1876 /* Find the previous colon. */
1877 prev_colon = last_colon - 1;
1878 while (prev_colon != input && *prev_colon != ':')
1879 --prev_colon;
1880 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001881 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001882 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001883 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001884 }
1885
1886 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001887 }
1888
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001889 *line = values[0];
1890 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001891
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001892 if (second_line && second_column) {
1893 *second_line = values[2];
1894 *second_column = values[3];
1895 }
1896
Douglas Gregorf96ea292009-11-09 18:19:57 +00001897 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001898 *filename = (char*)malloc(last_colon - input + 1);
1899 memcpy(*filename, input, last_colon - input);
1900 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001901 return 0;
1902}
1903
1904const char *
1905clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1906 switch (Kind) {
1907 case CXCompletionChunk_Optional: return "Optional";
1908 case CXCompletionChunk_TypedText: return "TypedText";
1909 case CXCompletionChunk_Text: return "Text";
1910 case CXCompletionChunk_Placeholder: return "Placeholder";
1911 case CXCompletionChunk_Informative: return "Informative";
1912 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1913 case CXCompletionChunk_LeftParen: return "LeftParen";
1914 case CXCompletionChunk_RightParen: return "RightParen";
1915 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1916 case CXCompletionChunk_RightBracket: return "RightBracket";
1917 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1918 case CXCompletionChunk_RightBrace: return "RightBrace";
1919 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1920 case CXCompletionChunk_RightAngle: return "RightAngle";
1921 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001922 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001923 case CXCompletionChunk_Colon: return "Colon";
1924 case CXCompletionChunk_SemiColon: return "SemiColon";
1925 case CXCompletionChunk_Equal: return "Equal";
1926 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1927 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001928 }
Ted Kremenek29004672010-02-17 00:41:32 +00001929
Douglas Gregor9eb77012009-11-07 00:00:49 +00001930 return "Unknown";
1931}
1932
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001933static int checkForErrors(CXTranslationUnit TU) {
1934 unsigned Num, i;
1935 CXDiagnostic Diag;
1936 CXString DiagStr;
1937
1938 if (!getenv("CINDEXTEST_FAILONERROR"))
1939 return 0;
1940
1941 Num = clang_getNumDiagnostics(TU);
1942 for (i = 0; i != Num; ++i) {
1943 Diag = clang_getDiagnostic(TU, i);
1944 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1945 DiagStr = clang_formatDiagnostic(Diag,
1946 clang_defaultDiagnosticDisplayOptions());
1947 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1948 clang_disposeString(DiagStr);
1949 clang_disposeDiagnostic(Diag);
1950 return -1;
1951 }
1952 clang_disposeDiagnostic(Diag);
1953 }
1954
1955 return 0;
1956}
1957
Nico Weber8d19dff2014-05-07 21:05:22 +00001958static void print_completion_string(CXCompletionString completion_string,
1959 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001960 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001961
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001962 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001963 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001964 CXString text;
1965 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001966 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001967 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001968
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001969 if (Kind == CXCompletionChunk_Optional) {
1970 fprintf(file, "{Optional ");
1971 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001972 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001973 file);
1974 fprintf(file, "}");
1975 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001976 }
1977
1978 if (Kind == CXCompletionChunk_VerticalSpace) {
1979 fprintf(file, "{VerticalSpace }");
1980 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001981 }
Ted Kremenek29004672010-02-17 00:41:32 +00001982
Douglas Gregorf81f5282009-11-09 17:05:28 +00001983 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001984 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001985 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001986 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001987 cstr ? cstr : "");
1988 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001989 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001990
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001991}
1992
Nico Weber8d19dff2014-05-07 21:05:22 +00001993static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001994 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001995 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001996 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001997 enum CXCursorKind ParentKind;
1998 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001999 CXString BriefComment;
2000 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00002001
Ted Kremenek29004672010-02-17 00:41:32 +00002002 fprintf(file, "%s:", clang_getCString(ks));
2003 clang_disposeString(ks);
2004
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002005 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00002006 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00002007 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00002008 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
2009 case CXAvailability_Available:
2010 break;
2011
2012 case CXAvailability_Deprecated:
2013 fprintf(file, " (deprecated)");
2014 break;
2015
2016 case CXAvailability_NotAvailable:
2017 fprintf(file, " (unavailable)");
2018 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002019
2020 case CXAvailability_NotAccessible:
2021 fprintf(file, " (inaccessible)");
2022 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002023 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002024
2025 annotationCount = clang_getCompletionNumAnnotations(
2026 completion_result->CompletionString);
2027 if (annotationCount) {
2028 unsigned i;
2029 fprintf(file, " (");
2030 for (i = 0; i < annotationCount; ++i) {
2031 if (i != 0)
2032 fprintf(file, ", ");
2033 fprintf(file, "\"%s\"",
2034 clang_getCString(clang_getCompletionAnnotation(
2035 completion_result->CompletionString, i)));
2036 }
2037 fprintf(file, ")");
2038 }
2039
Douglas Gregor78254c82012-03-27 23:34:16 +00002040 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2041 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2042 &ParentKind);
2043 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002044 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002045 fprintf(file, " (parent: %s '%s')",
2046 clang_getCString(KindSpelling),
2047 clang_getCString(ParentName));
2048 clang_disposeString(KindSpelling);
2049 }
2050 clang_disposeString(ParentName);
2051 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002052
2053 BriefComment = clang_getCompletionBriefComment(
2054 completion_result->CompletionString);
2055 BriefCommentCString = clang_getCString(BriefComment);
2056 if (BriefCommentCString && *BriefCommentCString != '\0') {
2057 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2058 }
2059 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002060
Douglas Gregorf757a122010-08-23 23:00:57 +00002061 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002062}
2063
Douglas Gregor21325842011-07-07 16:03:39 +00002064void print_completion_contexts(unsigned long long contexts, FILE *file) {
2065 fprintf(file, "Completion contexts:\n");
2066 if (contexts == CXCompletionContext_Unknown) {
2067 fprintf(file, "Unknown\n");
2068 }
2069 if (contexts & CXCompletionContext_AnyType) {
2070 fprintf(file, "Any type\n");
2071 }
2072 if (contexts & CXCompletionContext_AnyValue) {
2073 fprintf(file, "Any value\n");
2074 }
2075 if (contexts & CXCompletionContext_ObjCObjectValue) {
2076 fprintf(file, "Objective-C object value\n");
2077 }
2078 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2079 fprintf(file, "Objective-C selector value\n");
2080 }
2081 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2082 fprintf(file, "C++ class type value\n");
2083 }
2084 if (contexts & CXCompletionContext_DotMemberAccess) {
2085 fprintf(file, "Dot member access\n");
2086 }
2087 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2088 fprintf(file, "Arrow member access\n");
2089 }
2090 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2091 fprintf(file, "Objective-C property access\n");
2092 }
2093 if (contexts & CXCompletionContext_EnumTag) {
2094 fprintf(file, "Enum tag\n");
2095 }
2096 if (contexts & CXCompletionContext_UnionTag) {
2097 fprintf(file, "Union tag\n");
2098 }
2099 if (contexts & CXCompletionContext_StructTag) {
2100 fprintf(file, "Struct tag\n");
2101 }
2102 if (contexts & CXCompletionContext_ClassTag) {
2103 fprintf(file, "Class name\n");
2104 }
2105 if (contexts & CXCompletionContext_Namespace) {
2106 fprintf(file, "Namespace or namespace alias\n");
2107 }
2108 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2109 fprintf(file, "Nested name specifier\n");
2110 }
2111 if (contexts & CXCompletionContext_ObjCInterface) {
2112 fprintf(file, "Objective-C interface\n");
2113 }
2114 if (contexts & CXCompletionContext_ObjCProtocol) {
2115 fprintf(file, "Objective-C protocol\n");
2116 }
2117 if (contexts & CXCompletionContext_ObjCCategory) {
2118 fprintf(file, "Objective-C category\n");
2119 }
2120 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2121 fprintf(file, "Objective-C instance method\n");
2122 }
2123 if (contexts & CXCompletionContext_ObjCClassMessage) {
2124 fprintf(file, "Objective-C class method\n");
2125 }
2126 if (contexts & CXCompletionContext_ObjCSelectorName) {
2127 fprintf(file, "Objective-C selector name\n");
2128 }
2129 if (contexts & CXCompletionContext_MacroName) {
2130 fprintf(file, "Macro name\n");
2131 }
2132 if (contexts & CXCompletionContext_NaturalLanguage) {
2133 fprintf(file, "Natural language\n");
2134 }
2135}
2136
Douglas Gregor47815d52010-07-12 18:38:41 +00002137int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002138 const char *input = argv[1];
2139 char *filename = 0;
2140 unsigned line;
2141 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002142 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002143 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002144 struct CXUnsavedFile *unsaved_files = 0;
2145 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002146 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002147 enum CXErrorCode Err;
2148 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002149 unsigned I, Repeats = 1;
2150 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2151
2152 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2153 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002154 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2155 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002156
Douglas Gregor47815d52010-07-12 18:38:41 +00002157 if (timing_only)
2158 input += strlen("-code-completion-timing=");
2159 else
2160 input += strlen("-code-completion-at=");
2161
Ted Kremenek29004672010-02-17 00:41:32 +00002162 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002163 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002164 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002165
Douglas Gregor9485bf92009-12-02 09:21:34 +00002166 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2167 return -1;
2168
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002169 CIdx = clang_createIndex(0, 0);
2170
2171 if (getenv("CINDEXTEST_EDITING"))
2172 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002173
2174 Err = clang_parseTranslationUnit2(CIdx, 0,
2175 argv + num_unsaved_files + 2,
2176 argc - num_unsaved_files - 2,
2177 0, 0, getDefaultParsingOptions(), &TU);
2178 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002179 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002180 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002181 return 1;
2182 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002183
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002184 Err = clang_reparseTranslationUnit(TU, 0, 0,
2185 clang_defaultReparseOptions(TU));
2186
2187 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002188 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002189 describeLibclangFailure(Err);
2190 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002191 return 1;
2192 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002193
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002194 for (I = 0; I != Repeats; ++I) {
2195 results = clang_codeCompleteAt(TU, filename, line, column,
2196 unsaved_files, num_unsaved_files,
2197 completionOptions);
2198 if (!results) {
2199 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002200 return 1;
2201 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002202 if (I != Repeats-1)
2203 clang_disposeCodeCompleteResults(results);
2204 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002205
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002206 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002207 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002208 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002209 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002210 CXString objCSelector;
2211 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002212 if (!timing_only) {
2213 /* Sort the code-completion results based on the typed text. */
2214 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2215
Douglas Gregor47815d52010-07-12 18:38:41 +00002216 for (i = 0; i != n; ++i)
2217 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002218 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002219 n = clang_codeCompleteGetNumDiagnostics(results);
2220 for (i = 0; i != n; ++i) {
2221 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2222 PrintDiagnostic(diag);
2223 clang_disposeDiagnostic(diag);
2224 }
Douglas Gregor21325842011-07-07 16:03:39 +00002225
2226 contexts = clang_codeCompleteGetContexts(results);
2227 print_completion_contexts(contexts, stdout);
2228
Douglas Gregorea777402011-07-26 15:24:30 +00002229 containerKind = clang_codeCompleteGetContainerKind(results,
2230 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002231
2232 if (containerKind != CXCursor_InvalidCode) {
2233 /* We have found a container */
2234 CXString containerUSR, containerKindSpelling;
2235 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2236 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2237 clang_disposeString(containerKindSpelling);
2238
2239 if (containerIsIncomplete) {
2240 printf("Container is incomplete\n");
2241 }
2242 else {
2243 printf("Container is complete\n");
2244 }
2245
2246 containerUSR = clang_codeCompleteGetContainerUSR(results);
2247 printf("Container USR: %s\n", clang_getCString(containerUSR));
2248 clang_disposeString(containerUSR);
2249 }
2250
Douglas Gregorea777402011-07-26 15:24:30 +00002251 objCSelector = clang_codeCompleteGetObjCSelector(results);
2252 selectorString = clang_getCString(objCSelector);
2253 if (selectorString && strlen(selectorString) > 0) {
2254 printf("Objective-C selector: %s\n", selectorString);
2255 }
2256 clang_disposeString(objCSelector);
2257
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002258 clang_disposeCodeCompleteResults(results);
2259 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002260 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002261 clang_disposeIndex(CIdx);
2262 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002263
Douglas Gregor9485bf92009-12-02 09:21:34 +00002264 free_remapped_files(unsaved_files, num_unsaved_files);
2265
Ted Kremenekef3339b2009-11-17 18:09:14 +00002266 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002267}
2268
Douglas Gregor082c3e62010-01-15 19:40:17 +00002269typedef struct {
2270 char *filename;
2271 unsigned line;
2272 unsigned column;
2273} CursorSourceLocation;
2274
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002275typedef void (*cursor_handler_t)(CXCursor cursor);
2276
2277static int inspect_cursor_at(int argc, const char **argv,
2278 const char *locations_flag,
2279 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002280 CXIndex CIdx;
2281 int errorCode;
2282 struct CXUnsavedFile *unsaved_files = 0;
2283 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002284 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002285 CXTranslationUnit TU;
2286 CXCursor Cursor;
2287 CursorSourceLocation *Locations = 0;
2288 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002289 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002290 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002291
Ted Kremenek29004672010-02-17 00:41:32 +00002292 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002293 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002294 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002295
Douglas Gregor082c3e62010-01-15 19:40:17 +00002296 /* Parse the locations. */
2297 assert(NumLocations > 0 && "Unable to count locations?");
2298 Locations = (CursorSourceLocation *)malloc(
2299 NumLocations * sizeof(CursorSourceLocation));
2300 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002301 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002302 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2303 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002304 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002305 return errorCode;
2306 }
Ted Kremenek29004672010-02-17 00:41:32 +00002307
2308 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002309 &num_unsaved_files))
2310 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002311
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002312 if (getenv("CINDEXTEST_EDITING"))
2313 Repeats = 5;
2314
2315 /* Parse the translation unit. When we're testing clang_getCursor() after
2316 reparsing, don't remap unsaved files until the second parse. */
2317 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002318 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2319 argv + num_unsaved_files + 1 + NumLocations,
2320 argc - num_unsaved_files - 2 - NumLocations,
2321 unsaved_files,
2322 Repeats > 1? 0 : num_unsaved_files,
2323 getDefaultParsingOptions(), &TU);
2324 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002325 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002326 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002327 return -1;
2328 }
Ted Kremenek29004672010-02-17 00:41:32 +00002329
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002330 if (checkForErrors(TU) != 0)
2331 return -1;
2332
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002333 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002334 if (Repeats > 1) {
2335 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2336 clang_defaultReparseOptions(TU));
2337 if (Err != CXError_Success) {
2338 describeLibclangFailure(Err);
2339 clang_disposeTranslationUnit(TU);
2340 return 1;
2341 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002342 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002343
2344 if (checkForErrors(TU) != 0)
2345 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002346
2347 for (Loc = 0; Loc < NumLocations; ++Loc) {
2348 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2349 if (!file)
2350 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002351
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002352 Cursor = clang_getCursor(TU,
2353 clang_getLocation(TU, file, Locations[Loc].line,
2354 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002355
2356 if (checkForErrors(TU) != 0)
2357 return -1;
2358
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002359 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002360 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002361 free(Locations[Loc].filename);
2362 }
2363 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002364 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002365
Douglas Gregor33cdd812010-02-18 18:08:43 +00002366 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002367 clang_disposeTranslationUnit(TU);
2368 clang_disposeIndex(CIdx);
2369 free(Locations);
2370 free_remapped_files(unsaved_files, num_unsaved_files);
2371 return 0;
2372}
2373
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002374static void inspect_print_cursor(CXCursor Cursor) {
2375 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2376 CXCompletionString completionString = clang_getCursorCompletionString(
2377 Cursor);
2378 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2379 CXString Spelling;
2380 const char *cspell;
2381 unsigned line, column;
2382 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2383 printf("%d:%d ", line, column);
2384 PrintCursor(Cursor, NULL);
2385 PrintCursorExtent(Cursor);
2386 Spelling = clang_getCursorSpelling(Cursor);
2387 cspell = clang_getCString(Spelling);
2388 if (cspell && strlen(cspell) != 0) {
2389 unsigned pieceIndex;
2390 printf(" Spelling=%s (", cspell);
2391 for (pieceIndex = 0; ; ++pieceIndex) {
2392 CXSourceRange range =
2393 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2394 if (clang_Range_isNull(range))
2395 break;
2396 PrintRange(range, 0);
2397 }
2398 printf(")");
2399 }
2400 clang_disposeString(Spelling);
2401 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2402 printf(" Selector index=%d",
2403 clang_Cursor_getObjCSelectorIndex(Cursor));
2404 if (clang_Cursor_isDynamicCall(Cursor))
2405 printf(" Dynamic-call");
2406 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2407 CXType T = clang_Cursor_getReceiverType(Cursor);
2408 CXString S = clang_getTypeKindSpelling(T.kind);
2409 printf(" Receiver-type=%s", clang_getCString(S));
2410 clang_disposeString(S);
2411 }
2412
2413 {
2414 CXModule mod = clang_Cursor_getModule(Cursor);
2415 CXFile astFile;
2416 CXString name, astFilename;
2417 unsigned i, numHeaders;
2418 if (mod) {
2419 astFile = clang_Module_getASTFile(mod);
2420 astFilename = clang_getFileName(astFile);
2421 name = clang_Module_getFullName(mod);
2422 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2423 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2424 clang_getCString(name), clang_getCString(astFilename),
2425 clang_Module_isSystem(mod), numHeaders);
2426 clang_disposeString(name);
2427 clang_disposeString(astFilename);
2428 for (i = 0; i < numHeaders; ++i) {
2429 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2430 CXString filename = clang_getFileName(file);
2431 printf("\n%s", clang_getCString(filename));
2432 clang_disposeString(filename);
2433 }
2434 }
2435 }
2436
2437 if (completionString != NULL) {
2438 printf("\nCompletion string: ");
2439 print_completion_string(completionString, stdout);
2440 }
2441 printf("\n");
2442}
2443
2444static void display_evaluate_results(CXEvalResult result) {
2445 switch (clang_EvalResult_getKind(result)) {
2446 case CXEval_Int:
2447 {
2448 int val = clang_EvalResult_getAsInt(result);
2449 printf("Kind: Int , Value: %d", val);
2450 break;
2451 }
2452 case CXEval_Float:
2453 {
2454 double val = clang_EvalResult_getAsDouble(result);
2455 printf("Kind: Float , Value: %f", val);
2456 break;
2457 }
2458 case CXEval_ObjCStrLiteral:
2459 {
2460 const char* str = clang_EvalResult_getAsStr(result);
2461 printf("Kind: ObjCString , Value: %s", str);
2462 break;
2463 }
2464 case CXEval_StrLiteral:
2465 {
2466 const char* str = clang_EvalResult_getAsStr(result);
2467 printf("Kind: CString , Value: %s", str);
2468 break;
2469 }
2470 case CXEval_CFStr:
2471 {
2472 const char* str = clang_EvalResult_getAsStr(result);
2473 printf("Kind: CFString , Value: %s", str);
2474 break;
2475 }
2476 default:
2477 printf("Unexposed");
2478 break;
2479 }
2480}
2481
2482static void inspect_evaluate_cursor(CXCursor Cursor) {
2483 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2484 CXString Spelling;
2485 const char *cspell;
2486 unsigned line, column;
2487 CXEvalResult ER;
2488
2489 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2490 printf("%d:%d ", line, column);
2491 PrintCursor(Cursor, NULL);
2492 PrintCursorExtent(Cursor);
2493 Spelling = clang_getCursorSpelling(Cursor);
2494 cspell = clang_getCString(Spelling);
2495 if (cspell && strlen(cspell) != 0) {
2496 unsigned pieceIndex;
2497 printf(" Spelling=%s (", cspell);
2498 for (pieceIndex = 0; ; ++pieceIndex) {
2499 CXSourceRange range =
2500 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2501 if (clang_Range_isNull(range))
2502 break;
2503 PrintRange(range, 0);
2504 }
2505 printf(")");
2506 }
2507 clang_disposeString(Spelling);
2508
2509 ER = clang_Cursor_Evaluate(Cursor);
2510 if (!ER) {
2511 printf("Not Evaluatable");
2512 } else {
2513 display_evaluate_results(ER);
2514 clang_EvalResult_dispose(ER);
2515 }
2516 printf("\n");
2517}
2518
2519static void inspect_macroinfo_cursor(CXCursor Cursor) {
2520 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2521 CXString Spelling;
2522 const char *cspell;
2523 unsigned line, column;
2524 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2525 printf("%d:%d ", line, column);
2526 PrintCursor(Cursor, NULL);
2527 PrintCursorExtent(Cursor);
2528 Spelling = clang_getCursorSpelling(Cursor);
2529 cspell = clang_getCString(Spelling);
2530 if (cspell && strlen(cspell) != 0) {
2531 unsigned pieceIndex;
2532 printf(" Spelling=%s (", cspell);
2533 for (pieceIndex = 0; ; ++pieceIndex) {
2534 CXSourceRange range =
2535 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2536 if (clang_Range_isNull(range))
2537 break;
2538 PrintRange(range, 0);
2539 }
2540 printf(")");
2541 }
2542 clang_disposeString(Spelling);
2543
2544 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2545 printf("[builtin macro]");
2546 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2547 printf("[function macro]");
2548 }
2549 printf("\n");
2550}
2551
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002552static enum CXVisitorResult findFileRefsVisit(void *context,
2553 CXCursor cursor, CXSourceRange range) {
2554 if (clang_Range_isNull(range))
2555 return CXVisit_Continue;
2556
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002557 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002558 PrintRange(range, "");
2559 printf("\n");
2560 return CXVisit_Continue;
2561}
2562
2563static int find_file_refs_at(int argc, const char **argv) {
2564 CXIndex CIdx;
2565 int errorCode;
2566 struct CXUnsavedFile *unsaved_files = 0;
2567 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002568 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002569 CXTranslationUnit TU;
2570 CXCursor Cursor;
2571 CursorSourceLocation *Locations = 0;
2572 unsigned NumLocations = 0, Loc;
2573 unsigned Repeats = 1;
2574 unsigned I;
2575
2576 /* Count the number of locations. */
2577 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2578 ++NumLocations;
2579
2580 /* Parse the locations. */
2581 assert(NumLocations > 0 && "Unable to count locations?");
2582 Locations = (CursorSourceLocation *)malloc(
2583 NumLocations * sizeof(CursorSourceLocation));
2584 for (Loc = 0; Loc < NumLocations; ++Loc) {
2585 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2586 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2587 &Locations[Loc].line,
2588 &Locations[Loc].column, 0, 0)))
2589 return errorCode;
2590 }
2591
2592 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2593 &num_unsaved_files))
2594 return -1;
2595
2596 if (getenv("CINDEXTEST_EDITING"))
2597 Repeats = 5;
2598
2599 /* Parse the translation unit. When we're testing clang_getCursor() after
2600 reparsing, don't remap unsaved files until the second parse. */
2601 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002602 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2603 argv + num_unsaved_files + 1 + NumLocations,
2604 argc - num_unsaved_files - 2 - NumLocations,
2605 unsaved_files,
2606 Repeats > 1? 0 : num_unsaved_files,
2607 getDefaultParsingOptions(), &TU);
2608 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002609 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002610 describeLibclangFailure(Err);
2611 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002612 return -1;
2613 }
2614
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002615 if (checkForErrors(TU) != 0)
2616 return -1;
2617
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002618 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002619 if (Repeats > 1) {
2620 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2621 clang_defaultReparseOptions(TU));
2622 if (Err != CXError_Success) {
2623 describeLibclangFailure(Err);
2624 clang_disposeTranslationUnit(TU);
2625 return 1;
2626 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002627 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002628
2629 if (checkForErrors(TU) != 0)
2630 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002631
2632 for (Loc = 0; Loc < NumLocations; ++Loc) {
2633 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2634 if (!file)
2635 continue;
2636
2637 Cursor = clang_getCursor(TU,
2638 clang_getLocation(TU, file, Locations[Loc].line,
2639 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002640
2641 if (checkForErrors(TU) != 0)
2642 return -1;
2643
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002644 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002645 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002646 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002647 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002648 clang_findReferencesInFile(Cursor, file, visitor);
2649 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002650
2651 if (checkForErrors(TU) != 0)
2652 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002653 }
2654 }
2655 }
2656
2657 PrintDiagnostics(TU);
2658 clang_disposeTranslationUnit(TU);
2659 clang_disposeIndex(CIdx);
2660 free(Locations);
2661 free_remapped_files(unsaved_files, num_unsaved_files);
2662 return 0;
2663}
2664
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002665static enum CXVisitorResult findFileIncludesVisit(void *context,
2666 CXCursor cursor, CXSourceRange range) {
2667 PrintCursor(cursor, NULL);
2668 PrintRange(range, "");
2669 printf("\n");
2670 return CXVisit_Continue;
2671}
2672
2673static int find_file_includes_in(int argc, const char **argv) {
2674 CXIndex CIdx;
2675 struct CXUnsavedFile *unsaved_files = 0;
2676 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002677 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002678 CXTranslationUnit TU;
2679 const char **Filenames = 0;
2680 unsigned NumFilenames = 0;
2681 unsigned Repeats = 1;
2682 unsigned I, FI;
2683
2684 /* Count the number of locations. */
2685 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2686 ++NumFilenames;
2687
2688 /* Parse the locations. */
2689 assert(NumFilenames > 0 && "Unable to count filenames?");
2690 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2691 for (I = 0; I < NumFilenames; ++I) {
2692 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2693 /* Copy the file name. */
2694 Filenames[I] = input;
2695 }
2696
2697 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2698 &num_unsaved_files))
2699 return -1;
2700
2701 if (getenv("CINDEXTEST_EDITING"))
2702 Repeats = 2;
2703
2704 /* Parse the translation unit. When we're testing clang_getCursor() after
2705 reparsing, don't remap unsaved files until the second parse. */
2706 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002707 Err = clang_parseTranslationUnit2(
2708 CIdx, argv[argc - 1],
2709 argv + num_unsaved_files + 1 + NumFilenames,
2710 argc - num_unsaved_files - 2 - NumFilenames,
2711 unsaved_files,
2712 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002713
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002714 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002715 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002716 describeLibclangFailure(Err);
2717 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002718 return -1;
2719 }
2720
2721 if (checkForErrors(TU) != 0)
2722 return -1;
2723
2724 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002725 if (Repeats > 1) {
2726 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2727 clang_defaultReparseOptions(TU));
2728 if (Err != CXError_Success) {
2729 describeLibclangFailure(Err);
2730 clang_disposeTranslationUnit(TU);
2731 return 1;
2732 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002733 }
2734
2735 if (checkForErrors(TU) != 0)
2736 return -1;
2737
2738 for (FI = 0; FI < NumFilenames; ++FI) {
2739 CXFile file = clang_getFile(TU, Filenames[FI]);
2740 if (!file)
2741 continue;
2742
2743 if (checkForErrors(TU) != 0)
2744 return -1;
2745
2746 if (I + 1 == Repeats) {
2747 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2748 clang_findIncludesInFile(TU, file, visitor);
2749
2750 if (checkForErrors(TU) != 0)
2751 return -1;
2752 }
2753 }
2754 }
2755
2756 PrintDiagnostics(TU);
2757 clang_disposeTranslationUnit(TU);
2758 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002759 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002760 free_remapped_files(unsaved_files, num_unsaved_files);
2761 return 0;
2762}
2763
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002764#define MAX_IMPORTED_ASTFILES 200
2765
2766typedef struct {
2767 char **filenames;
2768 unsigned num_files;
2769} ImportedASTFilesData;
2770
2771static ImportedASTFilesData *importedASTs_create() {
2772 ImportedASTFilesData *p;
2773 p = malloc(sizeof(ImportedASTFilesData));
2774 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2775 p->num_files = 0;
2776 return p;
2777}
2778
2779static void importedASTs_dispose(ImportedASTFilesData *p) {
2780 unsigned i;
2781 if (!p)
2782 return;
2783
2784 for (i = 0; i < p->num_files; ++i)
2785 free(p->filenames[i]);
2786 free(p->filenames);
2787 free(p);
2788}
2789
2790static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2791 unsigned i;
2792 assert(p && file);
2793 for (i = 0; i < p->num_files; ++i)
2794 if (strcmp(file, p->filenames[i]) == 0)
2795 return;
2796 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2797 p->filenames[p->num_files++] = strdup(file);
2798}
2799
Nico Weberdf686022014-05-07 21:09:42 +00002800typedef struct IndexDataStringList_ {
2801 struct IndexDataStringList_ *next;
2802 char data[1]; /* Dynamically sized. */
2803} IndexDataStringList;
2804
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002805typedef struct {
2806 const char *check_prefix;
2807 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002808 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002809 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002810 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002811 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002812 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002813 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002814} IndexData;
2815
Nico Weberdf686022014-05-07 21:09:42 +00002816static void free_client_data(IndexData *index_data) {
2817 IndexDataStringList *node = index_data->strings;
2818 while (node) {
2819 IndexDataStringList *next = node->next;
2820 free(node);
2821 node = next;
2822 }
2823 index_data->strings = NULL;
2824}
2825
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002826static void printCheck(IndexData *data) {
2827 if (data->check_prefix) {
2828 if (data->first_check_printed) {
2829 printf("// %s-NEXT: ", data->check_prefix);
2830 } else {
2831 printf("// %s : ", data->check_prefix);
2832 data->first_check_printed = 1;
2833 }
2834 }
2835}
2836
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002837static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002838 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002839 printf("%s", clang_getCString(filename));
2840 clang_disposeString(filename);
2841}
2842
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002843static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2844 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002845 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002846 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002847 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002848 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002849 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002850
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002851 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002852 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2853 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002854 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002855 return;
2856 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002857 if (!file) {
2858 printf("<no idxfile>");
2859 return;
2860 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002861 filename = clang_getFileName((CXFile)file);
2862 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002863 if (strcmp(cname, index_data->main_filename) == 0)
2864 isMainFile = 1;
2865 else
2866 isMainFile = 0;
2867 clang_disposeString(filename);
2868
2869 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002870 printCXIndexFile(file);
2871 printf(":");
2872 }
2873 printf("%d:%d", line, column);
2874}
2875
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002876static unsigned digitCount(unsigned val) {
2877 unsigned c = 1;
2878 while (1) {
2879 if (val < 10)
2880 return c;
2881 ++c;
2882 val /= 10;
2883 }
2884}
2885
Nico Weberdf686022014-05-07 21:09:42 +00002886static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2887 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002888 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002889 IndexData *index_data;
2890 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002891 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002892 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002893 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002894 unsigned line, column;
2895
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002896 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002897 if (!name)
2898 name = "<anon-tag>";
2899
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002900 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002901
2902 node =
2903 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2904 digitCount(line) + digitCount(column) + 2);
2905 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002906 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002907
2908 /* Remember string so it can be freed later. */
2909 index_data = (IndexData *)client_data;
2910 node->next = index_data->strings;
2911 index_data->strings = node;
2912
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002913 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002914}
2915
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002916static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2917 CXIdxClientContainer container;
2918 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002919 if (!container)
2920 printf("[<<NULL>>]");
2921 else
2922 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002923}
2924
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002925static const char *getEntityKindString(CXIdxEntityKind kind) {
2926 switch (kind) {
2927 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2928 case CXIdxEntity_Typedef: return "typedef";
2929 case CXIdxEntity_Function: return "function";
2930 case CXIdxEntity_Variable: return "variable";
2931 case CXIdxEntity_Field: return "field";
2932 case CXIdxEntity_EnumConstant: return "enumerator";
2933 case CXIdxEntity_ObjCClass: return "objc-class";
2934 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2935 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002936 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2937 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002938 case CXIdxEntity_ObjCProperty: return "objc-property";
2939 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2940 case CXIdxEntity_Enum: return "enum";
2941 case CXIdxEntity_Struct: return "struct";
2942 case CXIdxEntity_Union: return "union";
2943 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002944 case CXIdxEntity_CXXNamespace: return "namespace";
2945 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2946 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2947 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2948 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2949 case CXIdxEntity_CXXConstructor: return "constructor";
2950 case CXIdxEntity_CXXDestructor: return "destructor";
2951 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2952 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002953 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002954 }
2955 assert(0 && "Garbage entity kind");
2956 return 0;
2957}
2958
2959static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2960 switch (kind) {
2961 case CXIdxEntity_NonTemplate: return "";
2962 case CXIdxEntity_Template: return "-template";
2963 case CXIdxEntity_TemplatePartialSpecialization:
2964 return "-template-partial-spec";
2965 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002966 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002967 assert(0 && "Garbage entity kind");
2968 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002969}
2970
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002971static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2972 switch (kind) {
2973 case CXIdxEntityLang_None: return "<none>";
2974 case CXIdxEntityLang_C: return "C";
2975 case CXIdxEntityLang_ObjC: return "ObjC";
2976 case CXIdxEntityLang_CXX: return "C++";
2977 }
2978 assert(0 && "Garbage language kind");
2979 return 0;
2980}
2981
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002982static void printEntityInfo(const char *cb,
2983 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002984 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002985 const char *name;
2986 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002987 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002988 index_data = (IndexData *)client_data;
2989 printCheck(index_data);
2990
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002991 if (!info) {
2992 printf("%s: <<NULL>>", cb);
2993 return;
2994 }
2995
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002996 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002997 if (!name)
2998 name = "<anon-tag>";
2999
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003000 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
3001 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003002 printf(" | name: %s", name);
3003 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00003004 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003005
3006 for (i = 0; i != info->numAttributes; ++i) {
3007 const CXIdxAttrInfo *Attr = info->attributes[i];
3008 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003009 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003010 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003011}
3012
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003013static void printBaseClassInfo(CXClientData client_data,
3014 const CXIdxBaseClassInfo *info) {
3015 printEntityInfo(" <base>", client_data, info->base);
3016 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003017 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003018 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003019 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003020}
3021
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003022static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3023 CXClientData client_data) {
3024 unsigned i;
3025 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3026 printEntityInfo(" <protocol>", client_data,
3027 ProtoInfo->protocols[i]->protocol);
3028 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003029 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003030 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003031 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003032 printf("\n");
3033 }
3034}
3035
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003036static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003037 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003038 CXString str;
3039 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003040 unsigned numDiags, i;
3041 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003042 IndexData *index_data;
3043 index_data = (IndexData *)client_data;
3044 printCheck(index_data);
3045
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003046 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3047 for (i = 0; i != numDiags; ++i) {
3048 diag = clang_getDiagnosticInSet(diagSet, i);
3049 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3050 cstr = clang_getCString(str);
3051 printf("[diagnostic]: %s\n", cstr);
3052 clang_disposeString(str);
3053
3054 if (getenv("CINDEXTEST_FAILONERROR") &&
3055 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3056 index_data->fail_for_error = 1;
3057 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003058 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003059}
3060
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003061static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3062 CXFile file, void *reserved) {
3063 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003064 CXString filename;
3065
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003066 index_data = (IndexData *)client_data;
3067 printCheck(index_data);
3068
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003069 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003070 index_data->main_filename = clang_getCString(filename);
3071 clang_disposeString(filename);
3072
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003073 printf("[enteredMainFile]: ");
3074 printCXIndexFile((CXIdxClientFile)file);
3075 printf("\n");
3076
3077 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003078}
3079
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003080static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003081 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003082 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003083 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003084 index_data = (IndexData *)client_data;
3085 printCheck(index_data);
3086
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003087 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003088 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003089 printf(" | name: \"%s\"", info->filename);
3090 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003091 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003092 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003093 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003094
3095 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3096 if (Mod) {
3097 CXString str = clang_Module_getFullName(Mod);
3098 const char *cstr = clang_getCString(str);
3099 printf(" | module: %s", cstr);
3100 clang_disposeString(str);
3101 }
3102
3103 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003104
3105 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003106}
3107
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003108static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3109 const CXIdxImportedASTFileInfo *info) {
3110 IndexData *index_data;
3111 index_data = (IndexData *)client_data;
3112 printCheck(index_data);
3113
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003114 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003115 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003116 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3117 clang_disposeString(filename);
3118 }
3119
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003120 printf("[importedASTFile]: ");
3121 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003122 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003123 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003124 printf(" | loc: ");
3125 printCXIndexLoc(info->loc, client_data);
3126 printf(" | name: \"%s\"", clang_getCString(name));
3127 printf(" | isImplicit: %d\n", info->isImplicit);
3128 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003129 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003130 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003131 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003132 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003133
3134 return (CXIdxClientFile)info->file;
3135}
3136
Nico Weber8d19dff2014-05-07 21:05:22 +00003137static CXIdxClientContainer
3138index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003139 IndexData *index_data;
3140 index_data = (IndexData *)client_data;
3141 printCheck(index_data);
3142
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003143 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003144 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003145}
3146
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003147static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003148 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003149 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003150 const CXIdxObjCCategoryDeclInfo *CatInfo;
3151 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003152 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003153 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003154 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003155 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003156 index_data = (IndexData *)client_data;
3157
3158 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3159 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003160 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003161 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003162 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003163 printf(" | semantic-container: ");
3164 printCXIndexContainer(info->semanticContainer);
3165 printf(" | lexical-container: ");
3166 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003167 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003168 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003169 if (info->flags & CXIdxDeclFlag_Skipped) {
3170 assert(!info->isContainer);
3171 printf(" | isContainer: skipped");
3172 } else {
3173 printf(" | isContainer: %d", info->isContainer);
3174 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003175 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003176
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003177 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003178 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003179 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003180 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003181 printf("\n");
3182 }
3183
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003184 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3185 const char *kindName = 0;
3186 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3187 switch (K) {
3188 case CXIdxObjCContainer_ForwardRef:
3189 kindName = "forward-ref"; break;
3190 case CXIdxObjCContainer_Interface:
3191 kindName = "interface"; break;
3192 case CXIdxObjCContainer_Implementation:
3193 kindName = "implementation"; break;
3194 }
3195 printCheck(index_data);
3196 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3197 }
3198
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003199 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003200 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3201 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003202 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003203 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003204 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003205 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003206 printf("\n");
3207 }
3208
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003209 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3210 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003211 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003212 printf("\n");
3213 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003214 }
3215
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003216 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3217 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003218 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003219
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003220 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3221 if (PropInfo->getter) {
3222 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3223 printf("\n");
3224 }
3225 if (PropInfo->setter) {
3226 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3227 printf("\n");
3228 }
3229 }
3230
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003231 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3232 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3233 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3234 printf("\n");
3235 }
3236 }
3237
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003238 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003239 clang_index_setClientContainer(
3240 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003241 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003242}
3243
3244static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003245 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003246 printEntityInfo("[indexEntityReference]", client_data,
3247 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003248 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003249 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003250 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003251 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003252 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003253 printf(" | container: ");
3254 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003255 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003256 switch (info->kind) {
3257 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003258 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003259 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003260 printf("\n");
3261}
3262
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003263static int index_abortQuery(CXClientData client_data, void *reserved) {
3264 IndexData *index_data;
3265 index_data = (IndexData *)client_data;
3266 return index_data->abort;
3267}
3268
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003269static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003270 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003271 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003272 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003273 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003274 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003275 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003276 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003277 index_indexEntityReference
3278};
3279
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003280static unsigned getIndexOptions(void) {
3281 unsigned index_opts;
3282 index_opts = 0;
3283 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3284 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3285 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3286 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003287 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3288 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003289
3290 return index_opts;
3291}
3292
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003293static int index_compile_args(int num_args, const char **args,
3294 CXIndexAction idxAction,
3295 ImportedASTFilesData *importedASTs,
3296 const char *check_prefix) {
3297 IndexData index_data;
3298 unsigned index_opts;
3299 int result;
3300
3301 if (num_args == 0) {
3302 fprintf(stderr, "no compiler arguments\n");
3303 return -1;
3304 }
3305
3306 index_data.check_prefix = check_prefix;
3307 index_data.first_check_printed = 0;
3308 index_data.fail_for_error = 0;
3309 index_data.abort = 0;
3310 index_data.main_filename = "";
3311 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003312 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003313 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003314
3315 index_opts = getIndexOptions();
3316 result = clang_indexSourceFile(idxAction, &index_data,
3317 &IndexCB,sizeof(IndexCB), index_opts,
3318 0, args, num_args, 0, 0, 0,
3319 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003320 if (result != CXError_Success)
3321 describeLibclangFailure(result);
3322
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003323 if (index_data.fail_for_error)
3324 result = -1;
3325
Nico Weberdf686022014-05-07 21:09:42 +00003326 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003327 return result;
3328}
3329
3330static int index_ast_file(const char *ast_file,
3331 CXIndex Idx,
3332 CXIndexAction idxAction,
3333 ImportedASTFilesData *importedASTs,
3334 const char *check_prefix) {
3335 CXTranslationUnit TU;
3336 IndexData index_data;
3337 unsigned index_opts;
3338 int result;
3339
3340 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3341 return -1;
3342
3343 index_data.check_prefix = check_prefix;
3344 index_data.first_check_printed = 0;
3345 index_data.fail_for_error = 0;
3346 index_data.abort = 0;
3347 index_data.main_filename = "";
3348 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003349 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003350 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003351
3352 index_opts = getIndexOptions();
3353 result = clang_indexTranslationUnit(idxAction, &index_data,
3354 &IndexCB,sizeof(IndexCB),
3355 index_opts, TU);
3356 if (index_data.fail_for_error)
3357 result = -1;
3358
3359 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003360 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003361 return result;
3362}
3363
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003364static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003365 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003366 CXIndex Idx;
3367 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003368 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003369 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003370
3371 check_prefix = 0;
3372 if (argc > 0) {
3373 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3374 check_prefix = argv[0] + strlen("-check-prefix=");
3375 ++argv;
3376 --argc;
3377 }
3378 }
3379
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003380 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003381 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003382 fprintf(stderr, "Could not create Index\n");
3383 return 1;
3384 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003385 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003386 importedASTs = 0;
3387 if (full)
3388 importedASTs = importedASTs_create();
3389
3390 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3391 if (result != 0)
3392 goto finished;
3393
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003394 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003395 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003396 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3397 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3398 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003399 }
3400 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003401
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003402finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003403 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003404 clang_IndexAction_dispose(idxAction);
3405 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003406 return result;
3407}
3408
3409static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003410 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003411 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003412 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003413 int result;
3414
3415 check_prefix = 0;
3416 if (argc > 0) {
3417 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3418 check_prefix = argv[0] + strlen("-check-prefix=");
3419 ++argv;
3420 --argc;
3421 }
3422 }
3423
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003424 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003425 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003426 fprintf(stderr, "Could not create Index\n");
3427 return 1;
3428 }
3429 idxAction = clang_IndexAction_create(Idx);
3430
3431 result = index_ast_file(argv[0], Idx, idxAction,
3432 /*importedASTs=*/0, check_prefix);
3433
3434 clang_IndexAction_dispose(idxAction);
3435 clang_disposeIndex(Idx);
3436 return result;
3437}
3438
3439static int index_compile_db(int argc, const char **argv) {
3440 const char *check_prefix;
3441 CXIndex Idx;
3442 CXIndexAction idxAction;
3443 int errorCode = 0;
3444
3445 check_prefix = 0;
3446 if (argc > 0) {
3447 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3448 check_prefix = argv[0] + strlen("-check-prefix=");
3449 ++argv;
3450 --argc;
3451 }
3452 }
3453
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003454 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003455 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003456 return -1;
3457 }
3458
3459 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003460 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003461 fprintf(stderr, "Could not create Index\n");
3462 return 1;
3463 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003464 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003465
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003466 {
3467 const char *database = argv[0];
3468 CXCompilationDatabase db = 0;
3469 CXCompileCommands CCmds = 0;
3470 CXCompileCommand CCmd;
3471 CXCompilationDatabase_Error ec;
3472 CXString wd;
3473#define MAX_COMPILE_ARGS 512
3474 CXString cxargs[MAX_COMPILE_ARGS];
3475 const char *args[MAX_COMPILE_ARGS];
3476 char *tmp;
3477 unsigned len;
3478 char *buildDir;
3479 int i, a, numCmds, numArgs;
3480
3481 len = strlen(database);
3482 tmp = (char *) malloc(len+1);
3483 memcpy(tmp, database, len+1);
3484 buildDir = dirname(tmp);
3485
3486 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3487
3488 if (db) {
3489
3490 if (ec!=CXCompilationDatabase_NoError) {
3491 printf("unexpected error %d code while loading compilation database\n", ec);
3492 errorCode = -1;
3493 goto cdb_end;
3494 }
3495
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003496 if (chdir(buildDir) != 0) {
3497 printf("Could not chdir to %s\n", buildDir);
3498 errorCode = -1;
3499 goto cdb_end;
3500 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003501
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003502 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003503 if (!CCmds) {
3504 printf("compilation db is empty\n");
3505 errorCode = -1;
3506 goto cdb_end;
3507 }
3508
3509 numCmds = clang_CompileCommands_getSize(CCmds);
3510
3511 if (numCmds==0) {
3512 fprintf(stderr, "should not get an empty compileCommand set\n");
3513 errorCode = -1;
3514 goto cdb_end;
3515 }
3516
3517 for (i=0; i<numCmds && errorCode == 0; ++i) {
3518 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3519
3520 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003521 if (chdir(clang_getCString(wd)) != 0) {
3522 printf("Could not chdir to %s\n", clang_getCString(wd));
3523 errorCode = -1;
3524 goto cdb_end;
3525 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003526 clang_disposeString(wd);
3527
3528 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3529 if (numArgs > MAX_COMPILE_ARGS){
3530 fprintf(stderr, "got more compile arguments than maximum\n");
3531 errorCode = -1;
3532 goto cdb_end;
3533 }
3534 for (a=0; a<numArgs; ++a) {
3535 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3536 args[a] = clang_getCString(cxargs[a]);
3537 }
3538
3539 errorCode = index_compile_args(numArgs, args, idxAction,
3540 /*importedASTs=*/0, check_prefix);
3541
3542 for (a=0; a<numArgs; ++a)
3543 clang_disposeString(cxargs[a]);
3544 }
3545 } else {
3546 printf("database loading failed with error code %d.\n", ec);
3547 errorCode = -1;
3548 }
3549
3550 cdb_end:
3551 clang_CompileCommands_dispose(CCmds);
3552 clang_CompilationDatabase_dispose(db);
3553 free(tmp);
3554
3555 }
3556
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003557 clang_IndexAction_dispose(idxAction);
3558 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003559 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003560}
3561
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003562int perform_token_annotation(int argc, const char **argv) {
3563 const char *input = argv[1];
3564 char *filename = 0;
3565 unsigned line, second_line;
3566 unsigned column, second_column;
3567 CXIndex CIdx;
3568 CXTranslationUnit TU = 0;
3569 int errorCode;
3570 struct CXUnsavedFile *unsaved_files = 0;
3571 int num_unsaved_files = 0;
3572 CXToken *tokens;
3573 unsigned num_tokens;
3574 CXSourceRange range;
3575 CXSourceLocation startLoc, endLoc;
3576 CXFile file = 0;
3577 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003578 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003579 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003580 unsigned i;
3581
3582 input += strlen("-test-annotate-tokens=");
3583 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3584 &second_line, &second_column)))
3585 return errorCode;
3586
Richard Smith1ea42eb2012-07-05 08:20:49 +00003587 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3588 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003589 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003590 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003591
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003592 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003593 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3594 argv + num_unsaved_files + 2,
3595 argc - num_unsaved_files - 3,
3596 unsaved_files,
3597 num_unsaved_files,
3598 getDefaultParsingOptions(), &TU);
3599 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003600 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003601 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003602 clang_disposeIndex(CIdx);
3603 free(filename);
3604 free_remapped_files(unsaved_files, num_unsaved_files);
3605 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003606 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003607 errorCode = 0;
3608
Richard Smith1ea42eb2012-07-05 08:20:49 +00003609 if (checkForErrors(TU) != 0) {
3610 errorCode = -1;
3611 goto teardown;
3612 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003613
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003614 if (getenv("CINDEXTEST_EDITING")) {
3615 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003616 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3617 clang_defaultReparseOptions(TU));
3618 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003619 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003620 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003621 errorCode = -1;
3622 goto teardown;
3623 }
3624 }
3625 }
3626
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003627 if (checkForErrors(TU) != 0) {
3628 errorCode = -1;
3629 goto teardown;
3630 }
3631
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003632 file = clang_getFile(TU, filename);
3633 if (!file) {
3634 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3635 errorCode = -1;
3636 goto teardown;
3637 }
3638
3639 startLoc = clang_getLocation(TU, file, line, column);
3640 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003641 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003642 column);
3643 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003644 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003645 }
3646
3647 endLoc = clang_getLocation(TU, file, second_line, second_column);
3648 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003649 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003650 second_line, second_column);
3651 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003652 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003653 }
3654
3655 range = clang_getRange(startLoc, endLoc);
3656 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003657
3658 if (checkForErrors(TU) != 0) {
3659 errorCode = -1;
3660 goto teardown;
3661 }
3662
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003663 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3664 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003665
3666 if (checkForErrors(TU) != 0) {
3667 errorCode = -1;
3668 goto teardown;
3669 }
3670
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003671 skipped_ranges = clang_getSkippedRanges(TU, file);
3672 for (i = 0; i != skipped_ranges->count; ++i) {
3673 unsigned start_line, start_column, end_line, end_column;
3674 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3675 0, &start_line, &start_column, 0);
3676 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3677 0, &end_line, &end_column, 0);
3678 printf("Skipping: ");
3679 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3680 printf("\n");
3681 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003682 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003683
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003684 for (i = 0; i != num_tokens; ++i) {
3685 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003686 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3687 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003688 unsigned start_line, start_column, end_line, end_column;
3689
3690 switch (clang_getTokenKind(tokens[i])) {
3691 case CXToken_Punctuation: kind = "Punctuation"; break;
3692 case CXToken_Keyword: kind = "Keyword"; break;
3693 case CXToken_Identifier: kind = "Identifier"; break;
3694 case CXToken_Literal: kind = "Literal"; break;
3695 case CXToken_Comment: kind = "Comment"; break;
3696 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003697 clang_getSpellingLocation(clang_getRangeStart(extent),
3698 0, &start_line, &start_column, 0);
3699 clang_getSpellingLocation(clang_getRangeEnd(extent),
3700 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003701 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003702 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003703 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003704 if (!clang_isInvalid(cursors[i].kind)) {
3705 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003706 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003707 }
3708 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003709 }
3710 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003711 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003712
3713 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003714 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003715 clang_disposeTranslationUnit(TU);
3716 clang_disposeIndex(CIdx);
3717 free(filename);
3718 free_remapped_files(unsaved_files, num_unsaved_files);
3719 return errorCode;
3720}
3721
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003722static int
3723perform_test_compilation_db(const char *database, int argc, const char **argv) {
3724 CXCompilationDatabase db;
3725 CXCompileCommands CCmds;
3726 CXCompileCommand CCmd;
3727 CXCompilationDatabase_Error ec;
3728 CXString wd;
3729 CXString arg;
3730 int errorCode = 0;
3731 char *tmp;
3732 unsigned len;
3733 char *buildDir;
3734 int i, j, a, numCmds, numArgs;
3735
3736 len = strlen(database);
3737 tmp = (char *) malloc(len+1);
3738 memcpy(tmp, database, len+1);
3739 buildDir = dirname(tmp);
3740
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003741 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003742
3743 if (db) {
3744
3745 if (ec!=CXCompilationDatabase_NoError) {
3746 printf("unexpected error %d code while loading compilation database\n", ec);
3747 errorCode = -1;
3748 goto cdb_end;
3749 }
3750
3751 for (i=0; i<argc && errorCode==0; ) {
3752 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003753 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003754
3755 if (!CCmds) {
3756 printf("file %s not found in compilation db\n", argv[i+1]);
3757 errorCode = -1;
3758 break;
3759 }
3760
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003761 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003762
3763 if (numCmds==0) {
3764 fprintf(stderr, "should not get an empty compileCommand set for file"
3765 " '%s'\n", argv[i+1]);
3766 errorCode = -1;
3767 break;
3768 }
3769
3770 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003771 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003772
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003773 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003774 printf("workdir:'%s'", clang_getCString(wd));
3775 clang_disposeString(wd);
3776
3777 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003778 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003779 for (a=0; a<numArgs; ++a) {
3780 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003781 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003782 printf("%s", clang_getCString(arg));
3783 clang_disposeString(arg);
3784 }
3785 printf("'\n");
3786 }
3787
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003788 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003789
3790 i += 2;
3791 }
3792 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003793 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003794 } else {
3795 printf("database loading failed with error code %d.\n", ec);
3796 errorCode = -1;
3797 }
3798
3799cdb_end:
3800 free(tmp);
3801
3802 return errorCode;
3803}
3804
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003805/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003806/* USR printing. */
3807/******************************************************************************/
3808
3809static int insufficient_usr(const char *kind, const char *usage) {
3810 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3811 return 1;
3812}
3813
3814static unsigned isUSR(const char *s) {
3815 return s[0] == 'c' && s[1] == ':';
3816}
3817
3818static int not_usr(const char *s, const char *arg) {
3819 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3820 return 1;
3821}
3822
3823static void print_usr(CXString usr) {
3824 const char *s = clang_getCString(usr);
3825 printf("%s\n", s);
3826 clang_disposeString(usr);
3827}
3828
3829static void display_usrs() {
3830 fprintf(stderr, "-print-usrs options:\n"
3831 " ObjCCategory <class name> <category name>\n"
3832 " ObjCClass <class name>\n"
3833 " ObjCIvar <ivar name> <class USR>\n"
3834 " ObjCMethod <selector> [0=class method|1=instance method] "
3835 "<class USR>\n"
3836 " ObjCProperty <property name> <class USR>\n"
3837 " ObjCProtocol <protocol name>\n");
3838}
3839
3840int print_usrs(const char **I, const char **E) {
3841 while (I != E) {
3842 const char *kind = *I;
3843 unsigned len = strlen(kind);
3844 switch (len) {
3845 case 8:
3846 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3847 if (I + 2 >= E)
3848 return insufficient_usr(kind, "<ivar name> <class USR>");
3849 if (!isUSR(I[2]))
3850 return not_usr("<class USR>", I[2]);
3851 else {
3852 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003853 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003854 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003855 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3856 }
3857
3858 I += 3;
3859 continue;
3860 }
3861 break;
3862 case 9:
3863 if (memcmp(kind, "ObjCClass", 9) == 0) {
3864 if (I + 1 >= E)
3865 return insufficient_usr(kind, "<class name>");
3866 print_usr(clang_constructUSR_ObjCClass(I[1]));
3867 I += 2;
3868 continue;
3869 }
3870 break;
3871 case 10:
3872 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3873 if (I + 3 >= E)
3874 return insufficient_usr(kind, "<method selector> "
3875 "[0=class method|1=instance method] <class USR>");
3876 if (!isUSR(I[3]))
3877 return not_usr("<class USR>", I[3]);
3878 else {
3879 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003880 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003881 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003882 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3883 }
3884 I += 4;
3885 continue;
3886 }
3887 break;
3888 case 12:
3889 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3890 if (I + 2 >= E)
3891 return insufficient_usr(kind, "<class name> <category name>");
3892 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3893 I += 3;
3894 continue;
3895 }
3896 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3897 if (I + 1 >= E)
3898 return insufficient_usr(kind, "<protocol name>");
3899 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3900 I += 2;
3901 continue;
3902 }
3903 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3904 if (I + 2 >= E)
3905 return insufficient_usr(kind, "<property name> <class USR>");
3906 if (!isUSR(I[2]))
3907 return not_usr("<class USR>", I[2]);
3908 else {
3909 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003910 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003911 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003912 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3913 }
3914 I += 3;
3915 continue;
3916 }
3917 break;
3918 default:
3919 break;
3920 }
3921 break;
3922 }
3923
3924 if (I != E) {
3925 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3926 display_usrs();
3927 return 1;
3928 }
3929 return 0;
3930}
3931
3932int print_usrs_file(const char *file_name) {
3933 char line[2048];
3934 const char *args[128];
3935 unsigned numChars = 0;
3936
3937 FILE *fp = fopen(file_name, "r");
3938 if (!fp) {
3939 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3940 return 1;
3941 }
3942
3943 /* This code is not really all that safe, but it works fine for testing. */
3944 while (!feof(fp)) {
3945 char c = fgetc(fp);
3946 if (c == '\n') {
3947 unsigned i = 0;
3948 const char *s = 0;
3949
3950 if (numChars == 0)
3951 continue;
3952
3953 line[numChars] = '\0';
3954 numChars = 0;
3955
3956 if (line[0] == '/' && line[1] == '/')
3957 continue;
3958
3959 s = strtok(line, " ");
3960 while (s) {
3961 args[i] = s;
3962 ++i;
3963 s = strtok(0, " ");
3964 }
3965 if (print_usrs(&args[0], &args[i]))
3966 return 1;
3967 }
3968 else
3969 line[numChars++] = c;
3970 }
3971
3972 fclose(fp);
3973 return 0;
3974}
3975
3976/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003977/* Command line processing. */
3978/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003979int write_pch_file(const char *filename, int argc, const char *argv[]) {
3980 CXIndex Idx;
3981 CXTranslationUnit TU;
3982 struct CXUnsavedFile *unsaved_files = 0;
3983 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003984 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003985 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003986
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003987 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003988
3989 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3990 clang_disposeIndex(Idx);
3991 return -1;
3992 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003993
3994 Err = clang_parseTranslationUnit2(
3995 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3996 unsaved_files, num_unsaved_files,
3997 CXTranslationUnit_Incomplete |
3998 CXTranslationUnit_DetailedPreprocessingRecord |
3999 CXTranslationUnit_ForSerialization,
4000 &TU);
4001 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00004002 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004003 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00004004 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004005 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00004006 clang_disposeIndex(Idx);
4007 return 1;
4008 }
4009
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004010 switch (clang_saveTranslationUnit(TU, filename,
4011 clang_defaultSaveOptions(TU))) {
4012 case CXSaveError_None:
4013 break;
4014
4015 case CXSaveError_TranslationErrors:
4016 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4017 filename);
4018 result = 2;
4019 break;
4020
4021 case CXSaveError_InvalidTU:
4022 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4023 filename);
4024 result = 3;
4025 break;
4026
4027 case CXSaveError_Unknown:
4028 default:
4029 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4030 result = 1;
4031 break;
4032 }
4033
Douglas Gregore9386682010-08-13 05:36:37 +00004034 clang_disposeTranslationUnit(TU);
4035 free_remapped_files(unsaved_files, num_unsaved_files);
4036 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004037 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004038}
4039
4040/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004041/* Serialized diagnostics. */
4042/******************************************************************************/
4043
4044static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4045 switch (error) {
4046 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4047 case CXLoadDiag_None: break;
4048 case CXLoadDiag_Unknown: return "Unknown";
4049 case CXLoadDiag_InvalidFile: return "Invalid File";
4050 }
4051 return "None";
4052}
4053
4054static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4055 switch (severity) {
4056 case CXDiagnostic_Note: return "note";
4057 case CXDiagnostic_Error: return "error";
4058 case CXDiagnostic_Fatal: return "fatal";
4059 case CXDiagnostic_Ignored: return "ignored";
4060 case CXDiagnostic_Warning: return "warning";
4061 }
4062 return "unknown";
4063}
4064
4065static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004066 if (indent == 0)
4067 return;
4068 fprintf(stderr, "+");
4069 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004070 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004071 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004072 --indent;
4073 }
4074}
4075
4076static void printLocation(CXSourceLocation L) {
4077 CXFile File;
4078 CXString FileName;
4079 unsigned line, column, offset;
4080
4081 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4082 FileName = clang_getFileName(File);
4083
4084 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4085 clang_disposeString(FileName);
4086}
4087
4088static void printRanges(CXDiagnostic D, unsigned indent) {
4089 unsigned i, n = clang_getDiagnosticNumRanges(D);
4090
4091 for (i = 0; i < n; ++i) {
4092 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004093 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004094 Start = clang_getRangeStart(SR);
4095 End = clang_getRangeEnd(SR);
4096
4097 printIndent(indent);
4098 fprintf(stderr, "Range: ");
4099 printLocation(Start);
4100 fprintf(stderr, " ");
4101 printLocation(End);
4102 fprintf(stderr, "\n");
4103 }
4104}
4105
4106static void printFixIts(CXDiagnostic D, unsigned indent) {
4107 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004108 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004109 for (i = 0 ; i < n; ++i) {
4110 CXSourceRange ReplacementRange;
4111 CXString text;
4112 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4113
4114 printIndent(indent);
4115 fprintf(stderr, "FIXIT: (");
4116 printLocation(clang_getRangeStart(ReplacementRange));
4117 fprintf(stderr, " - ");
4118 printLocation(clang_getRangeEnd(ReplacementRange));
4119 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4120 clang_disposeString(text);
4121 }
4122}
4123
4124static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004125 unsigned i, n;
4126
Ted Kremenekd010ba42011-11-10 08:43:12 +00004127 if (!Diags)
4128 return;
4129
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004130 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004131 for (i = 0; i < n; ++i) {
4132 CXSourceLocation DiagLoc;
4133 CXDiagnostic D;
4134 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004135 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004136 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004137 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004138
4139 D = clang_getDiagnosticInSet(Diags, i);
4140 DiagLoc = clang_getDiagnosticLocation(D);
4141 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4142 FileName = clang_getFileName(File);
4143 DiagSpelling = clang_getDiagnosticSpelling(D);
4144
4145 printIndent(indent);
4146
4147 fprintf(stderr, "%s:%d:%d: %s: %s",
4148 clang_getCString(FileName),
4149 line,
4150 column,
4151 getSeverityString(clang_getDiagnosticSeverity(D)),
4152 clang_getCString(DiagSpelling));
4153
4154 DiagOption = clang_getDiagnosticOption(D, 0);
4155 DiagOptionStr = clang_getCString(DiagOption);
4156 if (DiagOptionStr) {
4157 fprintf(stderr, " [%s]", DiagOptionStr);
4158 }
4159
Ted Kremenek26a6d492012-04-12 00:03:31 +00004160 DiagCat = clang_getDiagnosticCategoryText(D);
4161 DiagCatStr = clang_getCString(DiagCat);
4162 if (DiagCatStr) {
4163 fprintf(stderr, " [%s]", DiagCatStr);
4164 }
4165
Ted Kremenekd010ba42011-11-10 08:43:12 +00004166 fprintf(stderr, "\n");
4167
4168 printRanges(D, indent);
4169 printFixIts(D, indent);
4170
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004171 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004172 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4173
4174 clang_disposeString(FileName);
4175 clang_disposeString(DiagSpelling);
4176 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004177 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004178 }
4179}
4180
4181static int read_diagnostics(const char *filename) {
4182 enum CXLoadDiag_Error error;
4183 CXString errorString;
4184 CXDiagnosticSet Diags = 0;
4185
4186 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4187 if (!Diags) {
4188 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4189 getDiagnosticCodeStr(error),
4190 clang_getCString(errorString));
4191 clang_disposeString(errorString);
4192 return 1;
4193 }
4194
4195 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004196 fprintf(stderr, "Number of diagnostics: %d\n",
4197 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004198 clang_disposeDiagnosticSet(Diags);
4199 return 0;
4200}
4201
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004202static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004203 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004204 return 0;
4205}
4206
Ted Kremenekd010ba42011-11-10 08:43:12 +00004207/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004208/* Command line processing. */
4209/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004210
Douglas Gregor720d0052010-01-20 21:32:04 +00004211static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004212 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004213 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004214 if (strcmp(s, "-usrs") == 0)
4215 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004216 if (strncmp(s, "-memory-usage", 13) == 0)
4217 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004218 return NULL;
4219}
4220
Ted Kremenekef3339b2009-11-17 18:09:14 +00004221static void print_usage(void) {
4222 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004223 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004224 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004225 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004226 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4227 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004228 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4229 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004230 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004231 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004232 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004233 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004234 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004235 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004236 "[FileCheck prefix]\n");
4237 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004238 " c-index-test -test-load-tu <AST file> <symbol filter> "
4239 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004240 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4241 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004242 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004243 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004244 " c-index-test -test-load-source-memory-usage "
4245 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004246 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4247 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004248 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004249 " c-index-test -test-load-source-usrs-memory-usage "
4250 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004251 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4252 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004253 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004254 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004255 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004256 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004257 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004258 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004259 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004260 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004261 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004262 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004263 " c-index-test -write-pch <file> <compiler arguments>\n");
4264 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004265 " c-index-test -compilation-db [lookup <filename>] database\n");
4266 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004267 " c-index-test -print-build-session-timestamp\n");
4268 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004269 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004270 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004271 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004272 " all - load all symbols, including those from PCH\n"
4273 " local - load all symbols except those in PCH\n"
4274 " category - only load ObjC categories (non-PCH)\n"
4275 " interface - only load ObjC interfaces (non-PCH)\n"
4276 " protocol - only load ObjC protocols (non-PCH)\n"
4277 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004278 " typedef - only load typdefs (non-PCH)\n"
4279 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004280}
4281
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004282/***/
4283
4284int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004285 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004286 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4287 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004288 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004289 return perform_code_completion(argc, argv, 0);
4290 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4291 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004292 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004293 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4294 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4295 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4296 inspect_evaluate_cursor);
4297 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4298 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4299 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004300 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4301 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004302 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4303 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004304 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004305 return index_file(argc - 2, argv + 2, /*full=*/0);
4306 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4307 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004308 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4309 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004310 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4311 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004312 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004313 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004314 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004315 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4316 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004317 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004318 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4319 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4320 if (I) {
4321 int trials = atoi(argv[2]);
4322 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4323 NULL);
4324 }
4325 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004326 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004327 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004328
4329 PostVisitTU postVisit = 0;
4330 if (strstr(argv[1], "-memory-usage"))
4331 postVisit = PrintMemoryUsage;
4332
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004333 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004334 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4335 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004336 }
4337 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004338 return perform_file_scan(argv[2], argv[3],
4339 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004340 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4341 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004342 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4343 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4344 PrintInclusionStack);
4345 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4346 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4347 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004348 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4349 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4350 NULL);
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004351 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4352 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4353 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004354 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004355 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004356 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004357 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4358 return perform_test_load_source(argc - 2, argv + 2, "all",
4359 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004360 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4361 return perform_test_load_source(argc - 2, argv + 2, "all",
4362 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004363 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4364 return perform_test_load_source(argc - 2, argv + 2, "all",
4365 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004366 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4367 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004368 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4369 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004370 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4371 if (argc > 2)
4372 return print_usrs(argv + 2, argv + argc);
4373 else {
4374 display_usrs();
4375 return 1;
4376 }
4377 }
4378 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4379 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004380 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4381 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004382 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4383 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004384 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4385 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004386
Ted Kremenekef3339b2009-11-17 18:09:14 +00004387 print_usage();
4388 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004389}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004390
4391/***/
4392
4393/* We intentionally run in a separate thread to ensure we at least minimal
4394 * testing of a multithreaded environment (for example, having a reduced stack
4395 * size). */
4396
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004397typedef struct thread_info {
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004398 int (*main_func)(int argc, const char **argv);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004399 int argc;
4400 const char **argv;
4401 int result;
4402} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004403void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004404 thread_info *client_data = client_data_v;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004405 client_data->result = client_data->main_func(client_data->argc,
4406 client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004407}
4408
4409static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004410 /* stdout, and surprisingly even stderr, are not always flushed on process
4411 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004412 fflush(stdout);
4413 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004414}
4415
4416int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004417 thread_info client_data;
4418
Reid Klecknere931c062014-06-05 00:13:43 +00004419 atexit(flush_atexit);
4420
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004421#ifdef CLANG_HAVE_LIBXML
4422 LIBXML_TEST_VERSION
4423#endif
4424
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004425 client_data.main_func = cindextest_main;
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004426 client_data.argc = argc;
4427 client_data.argv = argv;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004428
4429 if (argc > 1 && strcmp(argv[1], "core") == 0) {
4430 client_data.main_func = indextest_core_main;
4431 --client_data.argc;
4432 ++client_data.argv;
4433 }
4434
4435 if (getenv("CINDEXTEST_NOTHREADS"))
4436 return client_data.main_func(client_data.argc, client_data.argv);
4437
Daniel Dunbar23397c32010-11-04 01:26:31 +00004438 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004439 return client_data.result;
4440}