blob: 2878ba26aff40827f2bd4e8214487de5b3d66a54 [file] [log] [blame]
Steve Naroff69b10fd2009-09-01 15:55:40 +00001/* c-index-test.c */
Steve Naroffa1c72842009-08-28 15:28:48 +00002
Alp Toker1d257e12014-06-04 03:28:55 +00003#include "clang/Config/config.h"
Steve Naroffa1c72842009-08-28 15:28:48 +00004#include "clang-c/Index.h"
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00005#include "clang-c/CXCompilationDatabase.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +00006#include "clang-c/BuildSystem.h"
Alp Toker59c6bc52014-04-28 02:39:27 +00007#include "clang-c/Documentation.h"
Douglas Gregor49f67ce2010-08-26 13:48:20 +00008#include <ctype.h>
Douglas Gregor9eb77012009-11-07 00:00:49 +00009#include <stdlib.h>
Steve Naroff1054e602009-08-31 00:59:03 +000010#include <stdio.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000011#include <string.h>
Douglas Gregor082c3e62010-01-15 19:40:17 +000012#include <assert.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000013
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +000014#ifdef CLANG_HAVE_LIBXML
15#include <libxml/parser.h>
16#include <libxml/relaxng.h>
17#include <libxml/xmlerror.h>
18#endif
19
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +000020#ifdef _WIN32
21# include <direct.h>
22#else
23# include <unistd.h>
24#endif
25
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +000026extern int indextest_core_main(int argc, const char **argv);
27
Ted Kremenek1cd27d52009-11-17 18:13:31 +000028/******************************************************************************/
29/* Utility functions. */
30/******************************************************************************/
31
John Thompsonde258b52009-10-27 13:42:56 +000032#ifdef _MSC_VER
33char *basename(const char* path)
34{
35 char* base1 = (char*)strrchr(path, '/');
36 char* base2 = (char*)strrchr(path, '\\');
37 if (base1 && base2)
38 return((base1 > base2) ? base1 + 1 : base2 + 1);
39 else if (base1)
40 return(base1 + 1);
41 else if (base2)
42 return(base2 + 1);
43
44 return((char*)path);
45}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000046char *dirname(char* path)
47{
48 char* base1 = (char*)strrchr(path, '/');
49 char* base2 = (char*)strrchr(path, '\\');
50 if (base1 && base2)
51 if (base1 > base2)
52 *base1 = 0;
53 else
54 *base2 = 0;
55 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000056 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000057 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000058 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000059
60 return path;
61}
John Thompsonde258b52009-10-27 13:42:56 +000062#else
Steve Naroffa7753c42009-09-24 20:03:06 +000063extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000064extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000065#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000066
Douglas Gregorf2430ba2010-07-25 17:39:21 +000067/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000068static unsigned getDefaultParsingOptions() {
69 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
70
71 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000072 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000073 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
74 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000075 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
76 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000077 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
78 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000079 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
80 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000081 if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
82 options |= CXTranslationUnit_CreatePreambleOnFirstParse;
Manuel Klimek016c0242016-03-01 10:56:19 +000083 if (getenv("CINDEXTEST_KEEP_GOING"))
84 options |= CXTranslationUnit_KeepGoing;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000085
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000086 return options;
87}
88
Patrik Hagglund55701d22014-02-17 11:54:08 +000089/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000090static int checkForErrors(CXTranslationUnit TU);
91
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000092static void describeLibclangFailure(enum CXErrorCode Err) {
93 switch (Err) {
94 case CXError_Success:
95 fprintf(stderr, "Success\n");
96 return;
97
98 case CXError_Failure:
99 fprintf(stderr, "Failure (no details available)\n");
100 return;
101
102 case CXError_Crashed:
103 fprintf(stderr, "Failure: libclang crashed\n");
104 return;
105
106 case CXError_InvalidArguments:
107 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
108 return;
109
110 case CXError_ASTReadError:
111 fprintf(stderr, "Failure: AST deserialization error occurred\n");
112 return;
113 }
114}
115
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000116static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
117 unsigned end_line, unsigned end_column) {
118 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000119 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000120}
121
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000122static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
123 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000124 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
125 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000126 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000127 describeLibclangFailure(Err);
128 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000129 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000130 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000131 return 1;
132}
133
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000134void free_remapped_files(struct CXUnsavedFile *unsaved_files,
135 int num_unsaved_files) {
136 int i;
137 for (i = 0; i != num_unsaved_files; ++i) {
138 free((char *)unsaved_files[i].Filename);
139 free((char *)unsaved_files[i].Contents);
140 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000141 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000142}
143
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000144static int parse_remapped_files_with_opt(const char *opt_name,
145 int argc, const char **argv,
146 int start_arg,
147 struct CXUnsavedFile **unsaved_files,
148 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000149 int i;
150 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000151 int prefix_len = strlen(opt_name);
152 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000153 *unsaved_files = 0;
154 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000155
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000156 /* Count the number of remapped files. */
157 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000158 if (strncmp(argv[arg], opt_name, prefix_len))
159 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000160
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000161 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
162 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000163 ++*num_unsaved_files;
164 }
Ted Kremenek29004672010-02-17 00:41:32 +0000165
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000166 if (*num_unsaved_files == 0)
167 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000168
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000170 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
171 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000172 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000173 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000174 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000175 int filename_len;
176 char *filename;
177 char *contents;
178 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000179 const char *sep = strchr(arg_string, ',');
180 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000181 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000182 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000183 free_remapped_files(*unsaved_files, i);
184 *unsaved_files = 0;
185 *num_unsaved_files = 0;
186 return -1;
187 }
Ted Kremenek29004672010-02-17 00:41:32 +0000188
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000189 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000190 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000191 if (!to_file) {
192 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000193 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000194 free_remapped_files(*unsaved_files, i);
195 *unsaved_files = 0;
196 *num_unsaved_files = 0;
197 return -1;
198 }
Ted Kremenek29004672010-02-17 00:41:32 +0000199
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000200 /* Determine the length of the file we're remapping to. */
201 fseek(to_file, 0, SEEK_END);
202 unsaved->Length = ftell(to_file);
203 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000204
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000205 /* Read the contents of the file we're remapping to. */
206 contents = (char *)malloc(unsaved->Length + 1);
207 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
208 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000209 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000210 fclose(to_file);
211 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000212 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000213 *unsaved_files = 0;
214 *num_unsaved_files = 0;
215 return -1;
216 }
217 contents[unsaved->Length] = 0;
218 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000219
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000220 /* Close the file. */
221 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000222
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000223 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000224 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000225 filename = (char *)malloc(filename_len + 1);
226 memcpy(filename, arg_string, filename_len);
227 filename[filename_len] = 0;
228 unsaved->Filename = filename;
229 }
Ted Kremenek29004672010-02-17 00:41:32 +0000230
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000231 return 0;
232}
233
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000234static int parse_remapped_files(int argc, const char **argv, int start_arg,
235 struct CXUnsavedFile **unsaved_files,
236 int *num_unsaved_files) {
237 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
238 unsaved_files, num_unsaved_files);
239}
240
241static int parse_remapped_files_with_try(int try_idx,
242 int argc, const char **argv,
243 int start_arg,
244 struct CXUnsavedFile **unsaved_files,
245 int *num_unsaved_files) {
246 struct CXUnsavedFile *unsaved_files_no_try_idx;
247 int num_unsaved_files_no_try_idx;
248 struct CXUnsavedFile *unsaved_files_try_idx;
249 int num_unsaved_files_try_idx;
250 int ret;
251 char opt_name[32];
252
253 ret = parse_remapped_files(argc, argv, start_arg,
254 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
255 if (ret)
256 return ret;
257
258 sprintf(opt_name, "-remap-file-%d=", try_idx);
259 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
260 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
261 if (ret)
262 return ret;
263
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000264 if (num_unsaved_files_no_try_idx == 0) {
265 *unsaved_files = unsaved_files_try_idx;
266 *num_unsaved_files = num_unsaved_files_try_idx;
267 return 0;
268 }
269 if (num_unsaved_files_try_idx == 0) {
270 *unsaved_files = unsaved_files_no_try_idx;
271 *num_unsaved_files = num_unsaved_files_no_try_idx;
272 return 0;
273 }
274
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000275 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
276 *unsaved_files
277 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
278 sizeof(struct CXUnsavedFile) *
279 *num_unsaved_files);
280 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
281 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
282 num_unsaved_files_try_idx);
283 free(unsaved_files_try_idx);
284 return 0;
285}
286
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000287static const char *parse_comments_schema(int argc, const char **argv) {
288 const char *CommentsSchemaArg = "-comments-xml-schema=";
289 const char *CommentSchemaFile = NULL;
290
291 if (argc == 0)
292 return CommentSchemaFile;
293
294 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
295 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
296
297 return CommentSchemaFile;
298}
299
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000300/******************************************************************************/
301/* Pretty-printing. */
302/******************************************************************************/
303
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000304static const char *FileCheckPrefix = "CHECK";
305
306static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000307 if (CStr != NULL && CStr[0] != '\0') {
308 for ( ; *CStr; ++CStr) {
309 const char C = *CStr;
310 switch (C) {
311 case '\n': printf("\\n"); break;
312 case '\r': printf("\\r"); break;
313 case '\t': printf("\\t"); break;
314 case '\v': printf("\\v"); break;
315 case '\f': printf("\\f"); break;
316 default: putchar(C); break;
317 }
318 }
319 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000320}
321
322static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
323 printf(" %s=[", Prefix);
324 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000325 printf("]");
326}
327
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000328static void PrintCXStringAndDispose(CXString Str) {
329 PrintCString(clang_getCString(Str));
330 clang_disposeString(Str);
331}
332
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000333static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
334 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
335}
336
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000337static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
338 CXString Str) {
339 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
340 clang_disposeString(Str);
341}
342
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000343static void PrintRange(CXSourceRange R, const char *str) {
344 CXFile begin_file, end_file;
345 unsigned begin_line, begin_column, end_line, end_column;
346
347 clang_getSpellingLocation(clang_getRangeStart(R),
348 &begin_file, &begin_line, &begin_column, 0);
349 clang_getSpellingLocation(clang_getRangeEnd(R),
350 &end_file, &end_line, &end_column, 0);
351 if (!begin_file || !end_file)
352 return;
353
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000354 if (str)
355 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000356 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
357}
358
Douglas Gregor97c75712010-10-02 22:49:11 +0000359int want_display_name = 0;
360
Douglas Gregord6225d32012-05-08 00:14:45 +0000361static void printVersion(const char *Prefix, CXVersion Version) {
362 if (Version.Major < 0)
363 return;
364 printf("%s%d", Prefix, Version.Major);
365
366 if (Version.Minor < 0)
367 return;
368 printf(".%d", Version.Minor);
369
370 if (Version.Subminor < 0)
371 return;
372 printf(".%d", Version.Subminor);
373}
374
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000375struct CommentASTDumpingContext {
376 int IndentLevel;
377};
378
379static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
380 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000381 unsigned i;
382 unsigned e;
383 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
384
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000385 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000386 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000387 printf(" ");
388
389 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000390 switch (Kind) {
391 case CXComment_Null:
392 printf("CXComment_Null");
393 break;
394 case CXComment_Text:
395 printf("CXComment_Text");
396 PrintCXStringWithPrefixAndDispose("Text",
397 clang_TextComment_getText(Comment));
398 if (clang_Comment_isWhitespace(Comment))
399 printf(" IsWhitespace");
400 if (clang_InlineContentComment_hasTrailingNewline(Comment))
401 printf(" HasTrailingNewline");
402 break;
403 case CXComment_InlineCommand:
404 printf("CXComment_InlineCommand");
405 PrintCXStringWithPrefixAndDispose(
406 "CommandName",
407 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000408 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
409 case CXCommentInlineCommandRenderKind_Normal:
410 printf(" RenderNormal");
411 break;
412 case CXCommentInlineCommandRenderKind_Bold:
413 printf(" RenderBold");
414 break;
415 case CXCommentInlineCommandRenderKind_Monospaced:
416 printf(" RenderMonospaced");
417 break;
418 case CXCommentInlineCommandRenderKind_Emphasized:
419 printf(" RenderEmphasized");
420 break;
421 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000422 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000423 i != e; ++i) {
424 printf(" Arg[%u]=", i);
425 PrintCXStringAndDispose(
426 clang_InlineCommandComment_getArgText(Comment, i));
427 }
428 if (clang_InlineContentComment_hasTrailingNewline(Comment))
429 printf(" HasTrailingNewline");
430 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000431 case CXComment_HTMLStartTag: {
432 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000433 printf("CXComment_HTMLStartTag");
434 PrintCXStringWithPrefixAndDispose(
435 "Name",
436 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000437 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000438 if (NumAttrs != 0) {
439 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000440 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000441 printf(" ");
442 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
443 printf("=");
444 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
445 }
446 }
447 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
448 printf(" SelfClosing");
449 if (clang_InlineContentComment_hasTrailingNewline(Comment))
450 printf(" HasTrailingNewline");
451 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000452 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000453 case CXComment_HTMLEndTag:
454 printf("CXComment_HTMLEndTag");
455 PrintCXStringWithPrefixAndDispose(
456 "Name",
457 clang_HTMLTagComment_getTagName(Comment));
458 if (clang_InlineContentComment_hasTrailingNewline(Comment))
459 printf(" HasTrailingNewline");
460 break;
461 case CXComment_Paragraph:
462 printf("CXComment_Paragraph");
463 if (clang_Comment_isWhitespace(Comment))
464 printf(" IsWhitespace");
465 break;
466 case CXComment_BlockCommand:
467 printf("CXComment_BlockCommand");
468 PrintCXStringWithPrefixAndDispose(
469 "CommandName",
470 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000471 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000472 i != e; ++i) {
473 printf(" Arg[%u]=", i);
474 PrintCXStringAndDispose(
475 clang_BlockCommandComment_getArgText(Comment, i));
476 }
477 break;
478 case CXComment_ParamCommand:
479 printf("CXComment_ParamCommand");
480 switch (clang_ParamCommandComment_getDirection(Comment)) {
481 case CXCommentParamPassDirection_In:
482 printf(" in");
483 break;
484 case CXCommentParamPassDirection_Out:
485 printf(" out");
486 break;
487 case CXCommentParamPassDirection_InOut:
488 printf(" in,out");
489 break;
490 }
491 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
492 printf(" explicitly");
493 else
494 printf(" implicitly");
495 PrintCXStringWithPrefixAndDispose(
496 "ParamName",
497 clang_ParamCommandComment_getParamName(Comment));
498 if (clang_ParamCommandComment_isParamIndexValid(Comment))
499 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
500 else
501 printf(" ParamIndex=Invalid");
502 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000503 case CXComment_TParamCommand:
504 printf("CXComment_TParamCommand");
505 PrintCXStringWithPrefixAndDispose(
506 "ParamName",
507 clang_TParamCommandComment_getParamName(Comment));
508 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
509 printf(" ParamPosition={");
510 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
511 i != e; ++i) {
512 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
513 if (i != e - 1)
514 printf(", ");
515 }
516 printf("}");
517 } else
518 printf(" ParamPosition=Invalid");
519 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000520 case CXComment_VerbatimBlockCommand:
521 printf("CXComment_VerbatimBlockCommand");
522 PrintCXStringWithPrefixAndDispose(
523 "CommandName",
524 clang_BlockCommandComment_getCommandName(Comment));
525 break;
526 case CXComment_VerbatimBlockLine:
527 printf("CXComment_VerbatimBlockLine");
528 PrintCXStringWithPrefixAndDispose(
529 "Text",
530 clang_VerbatimBlockLineComment_getText(Comment));
531 break;
532 case CXComment_VerbatimLine:
533 printf("CXComment_VerbatimLine");
534 PrintCXStringWithPrefixAndDispose(
535 "Text",
536 clang_VerbatimLineComment_getText(Comment));
537 break;
538 case CXComment_FullComment:
539 printf("CXComment_FullComment");
540 break;
541 }
542 if (Kind != CXComment_Null) {
543 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000544 unsigned i;
545 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000546 printf("\n// %s: ", FileCheckPrefix);
547 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
548 }
549 }
550 printf(")");
551 Ctx->IndentLevel--;
552}
553
554static void DumpCXComment(CXComment Comment) {
555 struct CommentASTDumpingContext Ctx;
556 Ctx.IndentLevel = 1;
557 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
558 DumpCXCommentInternal(&Ctx, Comment);
559 printf("]");
560}
561
Chandler Carruthb2faa592014-05-02 23:30:59 +0000562static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000563#ifdef CLANG_HAVE_LIBXML
564 xmlRelaxNGParserCtxtPtr RNGParser;
565 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000566 xmlDocPtr Doc;
567 xmlRelaxNGValidCtxtPtr ValidationCtxt;
568 int status;
569
Chandler Carruthb2faa592014-05-02 23:30:59 +0000570 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000571 return;
572
Chandler Carruthb2faa592014-05-02 23:30:59 +0000573 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
574 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000575 printf(" libXMLError");
576 return;
577 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000578 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000579
580 Doc = xmlParseDoc((const xmlChar *) Str);
581
582 if (!Doc) {
583 xmlErrorPtr Error = xmlGetLastError();
584 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
585 return;
586 }
587
Chandler Carruthb2faa592014-05-02 23:30:59 +0000588 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000589 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
590 if (!status)
591 printf(" CommentXMLValid");
592 else if (status > 0) {
593 xmlErrorPtr Error = xmlGetLastError();
594 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
595 } else
596 printf(" libXMLError");
597
598 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
599 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000600 xmlRelaxNGFree(Schema);
601 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000602#endif
603}
604
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000605static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000606 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000607 {
608 CXString RawComment;
609 const char *RawCommentCString;
610 CXString BriefComment;
611 const char *BriefCommentCString;
612
613 RawComment = clang_Cursor_getRawCommentText(Cursor);
614 RawCommentCString = clang_getCString(RawComment);
615 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
616 PrintCStringWithPrefix("RawComment", RawCommentCString);
617 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
618
619 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
620 BriefCommentCString = clang_getCString(BriefComment);
621 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
622 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
623 clang_disposeString(BriefComment);
624 }
625 clang_disposeString(RawComment);
626 }
627
628 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000629 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000630 if (clang_Comment_getKind(Comment) != CXComment_Null) {
631 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
632 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000633 {
634 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000635 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000636 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000637 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000638 clang_disposeString(XML);
639 }
640
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000641 DumpCXComment(Comment);
642 }
643 }
644}
645
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000646typedef struct {
647 unsigned line;
648 unsigned col;
649} LineCol;
650
651static int lineCol_cmp(const void *p1, const void *p2) {
652 const LineCol *lhs = p1;
653 const LineCol *rhs = p2;
654 if (lhs->line != rhs->line)
655 return (int)lhs->line - (int)rhs->line;
656 return (int)lhs->col - (int)rhs->col;
657}
658
Chandler Carruthb2faa592014-05-02 23:30:59 +0000659static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000660 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000661 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000662 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000663 printf("Invalid Cursor => %s", clang_getCString(ks));
664 clang_disposeString(ks);
665 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000666 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000667 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000668 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000669 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000670 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000671 CXCursor *overridden;
672 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000673 unsigned RefNameRangeNr;
674 CXSourceRange CursorExtent;
675 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000676 int AlwaysUnavailable;
677 int AlwaysDeprecated;
678 CXString UnavailableMessage;
679 CXString DeprecatedMessage;
680 CXPlatformAvailability PlatformAvailability[2];
681 int NumPlatformAvailability;
682 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000683
Ted Kremenek29004672010-02-17 00:41:32 +0000684 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000685 string = want_display_name? clang_getCursorDisplayName(Cursor)
686 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000687 printf("%s=%s", clang_getCString(ks),
688 clang_getCString(string));
689 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000690 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000691
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000692 Referenced = clang_getCursorReferenced(Cursor);
693 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000694 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
695 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
696 printf("[");
697 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000698 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000699 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000700 if (I)
701 printf(", ");
702
Douglas Gregor2967e282010-09-14 00:20:32 +0000703 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000704 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000705 printf("%d:%d", line, column);
706 }
707 printf("]");
708 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000709 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000710 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000711 printf(":%d:%d", line, column);
712 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000713 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000714
715 if (clang_isCursorDefinition(Cursor))
716 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000717
718 switch (clang_getCursorAvailability(Cursor)) {
719 case CXAvailability_Available:
720 break;
721
722 case CXAvailability_Deprecated:
723 printf(" (deprecated)");
724 break;
725
726 case CXAvailability_NotAvailable:
727 printf(" (unavailable)");
728 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000729
730 case CXAvailability_NotAccessible:
731 printf(" (inaccessible)");
732 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000733 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000734
Douglas Gregord6225d32012-05-08 00:14:45 +0000735 NumPlatformAvailability
736 = clang_getCursorPlatformAvailability(Cursor,
737 &AlwaysDeprecated,
738 &DeprecatedMessage,
739 &AlwaysUnavailable,
740 &UnavailableMessage,
741 PlatformAvailability, 2);
742 if (AlwaysUnavailable) {
743 printf(" (always unavailable: \"%s\")",
744 clang_getCString(UnavailableMessage));
745 } else if (AlwaysDeprecated) {
746 printf(" (always deprecated: \"%s\")",
747 clang_getCString(DeprecatedMessage));
748 } else {
749 for (I = 0; I != NumPlatformAvailability; ++I) {
750 if (I >= 2)
751 break;
752
753 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
754 if (PlatformAvailability[I].Unavailable)
755 printf(", unavailable");
756 else {
757 printVersion(", introduced=", PlatformAvailability[I].Introduced);
758 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
759 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
760 }
761 if (clang_getCString(PlatformAvailability[I].Message)[0])
762 printf(", message=\"%s\"",
763 clang_getCString(PlatformAvailability[I].Message));
764 printf(")");
765 }
766 }
767 for (I = 0; I != NumPlatformAvailability; ++I) {
768 if (I >= 2)
769 break;
770 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
771 }
772
773 clang_disposeString(DeprecatedMessage);
774 clang_disposeString(UnavailableMessage);
Jonathan Coe29565352016-04-27 12:48:25 +0000775
776 if (clang_CXXConstructor_isDefaultConstructor(Cursor))
777 printf(" (default constructor)");
778
779 if (clang_CXXConstructor_isMoveConstructor(Cursor))
780 printf(" (move constructor)");
781 if (clang_CXXConstructor_isCopyConstructor(Cursor))
782 printf(" (copy constructor)");
783 if (clang_CXXConstructor_isConvertingConstructor(Cursor))
784 printf(" (converting constructor)");
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000785 if (clang_CXXField_isMutable(Cursor))
786 printf(" (mutable)");
Jonathan Coe29565352016-04-27 12:48:25 +0000787 if (clang_CXXMethod_isDefaulted(Cursor))
788 printf(" (defaulted)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000789 if (clang_CXXMethod_isStatic(Cursor))
790 printf(" (static)");
791 if (clang_CXXMethod_isVirtual(Cursor))
792 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000793 if (clang_CXXMethod_isConst(Cursor))
794 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000795 if (clang_CXXMethod_isPureVirtual(Cursor))
796 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000797 if (clang_Cursor_isVariadic(Cursor))
798 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000799 if (clang_Cursor_isObjCOptional(Cursor))
800 printf(" (@optional)");
801
Ted Kremeneka5940822010-08-26 01:42:22 +0000802 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000803 CXType T =
804 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
805 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000806 printf(" [IBOutletCollection=%s]", clang_getCString(S));
807 clang_disposeString(S);
808 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000809
810 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
811 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
812 unsigned isVirtual = clang_isVirtualBase(Cursor);
813 const char *accessStr = 0;
814
815 switch (access) {
816 case CX_CXXInvalidAccessSpecifier:
817 accessStr = "invalid"; break;
818 case CX_CXXPublic:
819 accessStr = "public"; break;
820 case CX_CXXProtected:
821 accessStr = "protected"; break;
822 case CX_CXXPrivate:
823 accessStr = "private"; break;
824 }
825
826 printf(" [access=%s isVirtual=%s]", accessStr,
827 isVirtual ? "true" : "false");
828 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000829
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000830 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
831 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000832 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
833 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000834 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000835 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000836 clang_getCString(Name), line, column);
837 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000838
839 if (Cursor.kind == CXCursor_FunctionDecl) {
840 /* Collect the template parameter kinds from the base template. */
Argyrios Kyrtzidisfcfec5f2016-07-30 02:20:21 +0000841 int NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
842 int I;
843 if (NumTemplateArgs < 0) {
844 printf(" [no template arg info]");
845 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000846 for (I = 0; I < NumTemplateArgs; I++) {
847 enum CXTemplateArgumentKind TAK =
848 clang_Cursor_getTemplateArgumentKind(Cursor, I);
849 switch(TAK) {
850 case CXTemplateArgumentKind_Type:
851 {
852 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
853 CXString S = clang_getTypeSpelling(T);
854 printf(" [Template arg %d: kind: %d, type: %s]",
855 I, TAK, clang_getCString(S));
856 clang_disposeString(S);
857 }
858 break;
859 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000860 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000861 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
862 break;
863 default:
864 printf(" [Template arg %d: kind: %d]\n", I, TAK);
865 }
866 }
867 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000868 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000869
870 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
871 if (num_overridden) {
872 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000873 LineCol lineCols[50];
874 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000875 printf(" [Overrides ");
876 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000877 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000878 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000879 lineCols[I].line = line;
880 lineCols[I].col = column;
881 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000882 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000883 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
884 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000885 if (I)
886 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000887 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000888 }
889 printf("]");
890 clang_disposeOverriddenCursors(overridden);
891 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000892
893 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000894 CXFile File = clang_getIncludedFile(Cursor);
895 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000896 printf(" (%s)", clang_getCString(Included));
897 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000898
899 if (clang_isFileMultipleIncludeGuarded(TU, File))
900 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000901 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000902
903 CursorExtent = clang_getCursorExtent(Cursor);
904 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
905 CXNameRange_WantQualifier
906 | CXNameRange_WantSinglePiece
907 | CXNameRange_WantTemplateArgs,
908 0);
909 if (!clang_equalRanges(CursorExtent, RefNameRange))
910 PrintRange(RefNameRange, "SingleRefName");
911
912 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
913 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
914 CXNameRange_WantQualifier
915 | CXNameRange_WantTemplateArgs,
916 RefNameRangeNr);
917 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
918 break;
919 if (!clang_equalRanges(CursorExtent, RefNameRange))
920 PrintRange(RefNameRange, "RefName");
921 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000922
Chandler Carruthb2faa592014-05-02 23:30:59 +0000923 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000924
925 {
926 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
927 if (PropAttrs != CXObjCPropertyAttr_noattr) {
928 printf(" [");
929 #define PRINT_PROP_ATTR(A) \
930 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
931 PRINT_PROP_ATTR(readonly);
932 PRINT_PROP_ATTR(getter);
933 PRINT_PROP_ATTR(assign);
934 PRINT_PROP_ATTR(readwrite);
935 PRINT_PROP_ATTR(retain);
936 PRINT_PROP_ATTR(copy);
937 PRINT_PROP_ATTR(nonatomic);
938 PRINT_PROP_ATTR(setter);
939 PRINT_PROP_ATTR(atomic);
940 PRINT_PROP_ATTR(weak);
941 PRINT_PROP_ATTR(strong);
942 PRINT_PROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +0000943 PRINT_PROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000944 printf("]");
945 }
946 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000947
948 {
949 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
950 if (QT != CXObjCDeclQualifier_None) {
951 printf(" [");
952 #define PRINT_OBJC_QUAL(A) \
953 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
954 PRINT_OBJC_QUAL(In);
955 PRINT_OBJC_QUAL(Inout);
956 PRINT_OBJC_QUAL(Out);
957 PRINT_OBJC_QUAL(Bycopy);
958 PRINT_OBJC_QUAL(Byref);
959 PRINT_OBJC_QUAL(Oneway);
960 printf("]");
961 }
962 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000963 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000964}
Steve Naroff1054e602009-08-31 00:59:03 +0000965
Ted Kremenek29004672010-02-17 00:41:32 +0000966static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000967 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000968 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000969 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000970 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000971 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000972 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000973 clang_disposeString(source);
974 return "<invalid loc>";
975 }
976 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000977 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000978 clang_disposeString(source);
979 return b;
980 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000981}
982
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000983/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000984/* Callbacks. */
985/******************************************************************************/
986
987typedef void (*PostVisitTU)(CXTranslationUnit);
988
Douglas Gregor33cdd812010-02-18 18:08:43 +0000989void PrintDiagnostic(CXDiagnostic Diagnostic) {
990 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000991 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000992 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000993 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000994 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
995 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000996 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000997
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000998 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000999 return;
Ted Kremenek29004672010-02-17 00:41:32 +00001000
Douglas Gregord770f732010-02-22 23:17:23 +00001001 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
1002 fprintf(stderr, "%s\n", clang_getCString(Msg));
1003 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +00001004
Douglas Gregor229bebd2010-11-09 06:24:54 +00001005 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
1006 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001007 if (!file)
1008 return;
Ted Kremenek29004672010-02-17 00:41:32 +00001009
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001010 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +00001011 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001012 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +00001013 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001014 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
1015 CXSourceLocation start = clang_getRangeStart(range);
1016 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +00001017 unsigned start_line, start_column, end_line, end_column;
1018 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001019 clang_getSpellingLocation(start, &start_file, &start_line,
1020 &start_column, 0);
1021 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001022 if (clang_equalLocations(start, end)) {
1023 /* Insertion. */
1024 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001025 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001026 clang_getCString(insertion_text), start_line, start_column);
1027 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1028 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001029 if (start_file == file && end_file == file) {
1030 fprintf(out, "FIX-IT: Remove ");
1031 PrintExtent(out, start_line, start_column, end_line, end_column);
1032 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001033 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001034 } else {
1035 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001036 if (start_file == end_file) {
1037 fprintf(out, "FIX-IT: Replace ");
1038 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001039 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001040 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001041 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001042 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001043 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001044}
1045
Ted Kremenek914c7e62012-02-14 02:46:03 +00001046void PrintDiagnosticSet(CXDiagnosticSet Set) {
1047 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1048 for ( ; i != n ; ++i) {
1049 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1050 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001051 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001052 if (ChildDiags)
1053 PrintDiagnosticSet(ChildDiags);
1054 }
1055}
1056
1057void PrintDiagnostics(CXTranslationUnit TU) {
1058 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1059 PrintDiagnosticSet(TUSet);
1060 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001061}
1062
Ted Kremenek83f642e2011-04-18 22:47:10 +00001063void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001064 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001065 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001066 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001067 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001068 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001069 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001070 unsigned long amount = usage.entries[i].amount;
1071 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001072 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001073 ((double) amount)/(1024*1024));
1074 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001075 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001076 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001077 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001078}
1079
Ted Kremenekb478ff42010-01-26 17:59:48 +00001080/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001081/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001082/******************************************************************************/
1083
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001084static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001085 CXSourceRange extent = clang_getCursorExtent(C);
1086 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001087}
1088
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001089/* Data used by the visitors. */
1090typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001091 CXTranslationUnit TU;
1092 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001093 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001094} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001095
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001096
Ted Kremenek29004672010-02-17 00:41:32 +00001097enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001098 CXCursor Parent,
1099 CXClientData ClientData) {
1100 VisitorData *Data = (VisitorData *)ClientData;
1101 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001102 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001103 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001104 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001105 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001106 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001107 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001108 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001109 if (clang_isDeclaration(Cursor.kind)) {
1110 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1111 const char *accessStr = 0;
1112
1113 switch (access) {
1114 case CX_CXXInvalidAccessSpecifier: break;
1115 case CX_CXXPublic:
1116 accessStr = "public"; break;
1117 case CX_CXXProtected:
1118 accessStr = "protected"; break;
1119 case CX_CXXPrivate:
1120 accessStr = "private"; break;
1121 }
1122
1123 if (accessStr)
1124 printf(" [access=%s]", accessStr);
1125 }
Ted Kremenek29004672010-02-17 00:41:32 +00001126 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001127 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001128 }
Ted Kremenek29004672010-02-17 00:41:32 +00001129
Douglas Gregor720d0052010-01-20 21:32:04 +00001130 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001131}
Steve Naroffa1c72842009-08-28 15:28:48 +00001132
Ted Kremenek29004672010-02-17 00:41:32 +00001133static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001134 CXCursor Parent,
1135 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001136 const char *startBuf, *endBuf;
1137 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1138 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001139 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001140
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001141 if (Cursor.kind != CXCursor_FunctionDecl ||
1142 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001143 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001144
1145 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1146 &startLine, &startColumn,
1147 &endLine, &endColumn);
1148 /* Probe the entire body, looking for both decls and refs. */
1149 curLine = startLine;
1150 curColumn = startColumn;
1151
1152 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001153 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001154 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001155 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001156
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001157 if (*startBuf == '\n') {
1158 startBuf++;
1159 curLine++;
1160 curColumn = 1;
1161 } else if (*startBuf != '\t')
1162 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001163
Douglas Gregor66a58812010-01-18 22:46:11 +00001164 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001165 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001166
Douglas Gregor4f46e782010-01-19 21:36:55 +00001167 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001168 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001169 CXSourceLocation RefLoc
1170 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001171 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001172 if (Ref.kind == CXCursor_NoDeclFound) {
1173 /* Nothing found here; that's fine. */
1174 } else if (Ref.kind != CXCursor_FunctionDecl) {
1175 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1176 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001177 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001178 printf("\n");
1179 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001180 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001181 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001182 startBuf++;
1183 }
Ted Kremenek29004672010-02-17 00:41:32 +00001184
Douglas Gregor720d0052010-01-20 21:32:04 +00001185 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001186}
1187
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001188/******************************************************************************/
1189/* USR testing. */
1190/******************************************************************************/
1191
Douglas Gregor720d0052010-01-20 21:32:04 +00001192enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1193 CXClientData ClientData) {
1194 VisitorData *Data = (VisitorData *)ClientData;
1195 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001196 CXString USR = clang_getCursorUSR(C);
1197 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001198 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001199 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001200 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001201 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001202 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1203
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001204 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001205 printf("\n");
1206 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001207
Douglas Gregor720d0052010-01-20 21:32:04 +00001208 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001209 }
1210
Douglas Gregor720d0052010-01-20 21:32:04 +00001211 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001212}
1213
1214/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001215/* Inclusion stack testing. */
1216/******************************************************************************/
1217
1218void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1219 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001220
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001221 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001222 CXString fname;
1223
1224 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001225 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001226 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001227
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001228 for (i = 0; i < includeStackLen; ++i) {
1229 CXFile includingFile;
1230 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001231 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1232 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001233 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001234 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001235 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001236 }
1237 printf("\n");
1238}
1239
1240void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001241 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001242}
1243
1244/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001245/* Linkage testing. */
1246/******************************************************************************/
1247
1248static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1249 CXClientData d) {
1250 const char *linkage = 0;
1251
1252 if (clang_isInvalid(clang_getCursorKind(cursor)))
1253 return CXChildVisit_Recurse;
1254
1255 switch (clang_getCursorLinkage(cursor)) {
1256 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001257 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1258 case CXLinkage_Internal: linkage = "Internal"; break;
1259 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1260 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001261 }
1262
1263 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001264 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001265 printf("linkage=%s\n", linkage);
1266 }
1267
1268 return CXChildVisit_Recurse;
1269}
1270
1271/******************************************************************************/
Ehsan Akhgarib743de72016-05-31 15:55:51 +00001272/* Visibility testing. */
1273/******************************************************************************/
1274
1275static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1276 CXClientData d) {
1277 const char *visibility = 0;
1278
1279 if (clang_isInvalid(clang_getCursorKind(cursor)))
1280 return CXChildVisit_Recurse;
1281
1282 switch (clang_getCursorVisibility(cursor)) {
1283 case CXVisibility_Invalid: break;
1284 case CXVisibility_Hidden: visibility = "Hidden"; break;
1285 case CXVisibility_Protected: visibility = "Protected"; break;
1286 case CXVisibility_Default: visibility = "Default"; break;
1287 }
1288
1289 if (visibility) {
1290 PrintCursor(cursor, NULL);
1291 printf("visibility=%s\n", visibility);
1292 }
1293
1294 return CXChildVisit_Recurse;
1295}
1296
1297/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001298/* Typekind testing. */
1299/******************************************************************************/
1300
Dmitri Gribenko00353722013-02-15 21:15:49 +00001301static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1302 CXString TypeSpelling, TypeKindSpelling;
1303
1304 TypeSpelling = clang_getTypeSpelling(T);
1305 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1306 printf(Format,
1307 clang_getCString(TypeSpelling),
1308 clang_getCString(TypeKindSpelling));
1309 clang_disposeString(TypeSpelling);
1310 clang_disposeString(TypeKindSpelling);
1311}
1312
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001313static enum CXVisitorResult FieldVisitor(CXCursor C,
1314 CXClientData client_data) {
1315 (*(int *) client_data)+=1;
1316 return CXVisit_Continue;
1317}
1318
Dmitri Gribenko00353722013-02-15 21:15:49 +00001319static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1320 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001321 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001322 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001323 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001324 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001325 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001326 if (clang_isConstQualifiedType(T))
1327 printf(" const");
1328 if (clang_isVolatileQualifiedType(T))
1329 printf(" volatile");
1330 if (clang_isRestrictQualifiedType(T))
1331 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001332 if (RQ == CXRefQualifier_LValue)
1333 printf(" lvalue-ref-qualifier");
1334 if (RQ == CXRefQualifier_RValue)
1335 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001336 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001337 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001338 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001339 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001340 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001341 }
1342 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001343 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001344 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001345 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001346 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001347 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001348 }
1349 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001350 /* Print the argument types if they exist. */
1351 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001352 int NumArgs = clang_Cursor_getNumArguments(cursor);
1353 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001354 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001355 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001356 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001357 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001358 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001359 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001360 }
1361 }
1362 printf("]");
1363 }
1364 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001365 /* Print the template argument types if they exist. */
1366 {
1367 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1368 if (NumTArgs != -1 && NumTArgs != 0) {
1369 int i;
1370 printf(" [templateargs/%d=", NumTArgs);
1371 for (i = 0; i < NumTArgs; ++i) {
1372 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1373 if (TArg.kind != CXType_Invalid) {
1374 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1375 }
1376 }
1377 printf("]");
1378 }
1379 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001380 /* Print if this is a non-POD type. */
1381 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001382 /* Print the pointee type. */
1383 {
1384 CXType PT = clang_getPointeeType(T);
1385 if (PT.kind != CXType_Invalid) {
1386 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1387 }
1388 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001389 /* Print the number of fields if they exist. */
1390 {
1391 int numFields = 0;
1392 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1393 if (numFields != 0) {
1394 printf(" [nbFields=%d]", numFields);
1395 }
1396 /* Print if it is an anonymous record. */
1397 {
1398 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1399 if (isAnon != 0) {
1400 printf(" [isAnon=%d]", isAnon);
1401 }
1402 }
1403 }
1404 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001405
Ted Kremenek6bca9842010-05-14 21:29:26 +00001406 printf("\n");
1407 }
1408 return CXChildVisit_Recurse;
1409}
1410
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001411static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1412 CXClientData d) {
1413 CXType T;
1414 enum CXCursorKind K = clang_getCursorKind(cursor);
1415 if (clang_isInvalid(K))
1416 return CXChildVisit_Recurse;
1417 T = clang_getCursorType(cursor);
1418 PrintCursor(cursor, NULL);
1419 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1420 /* Print the type sizeof if applicable. */
1421 {
1422 long long Size = clang_Type_getSizeOf(T);
1423 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001424 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001425 }
1426 }
1427 /* Print the type alignof if applicable. */
1428 {
1429 long long Align = clang_Type_getAlignOf(T);
1430 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001431 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001432 }
1433 }
1434 /* Print the record field offset if applicable. */
1435 {
Nico Weber82098cb2014-04-24 04:14:12 +00001436 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1437 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001438 /* recurse to get the first parent record that is not anonymous. */
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001439 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001440 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
David Blaikie263942f2016-05-03 22:14:14 +00001441 CXCursor Record;
1442 CXCursor Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001443 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001444 Record = Parent;
1445 Parent = clang_getCursorSemanticParent(Record);
1446 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1447 /* Recurse as long as the parent is a CXType_Record and the Record
1448 is anonymous */
1449 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1450 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001451 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001452 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001453 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001454 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1455 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001456 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001457 } else {
1458 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001459 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001460 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001461 }
1462 }
Nico Weber82098cb2014-04-24 04:14:12 +00001463 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001464 }
1465 /* Print if its a bitfield */
1466 {
1467 int IsBitfield = clang_Cursor_isBitField(cursor);
1468 if (IsBitfield)
1469 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1470 }
1471 printf("\n");
1472 return CXChildVisit_Recurse;
1473}
1474
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001475/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001476/* Mangling testing. */
1477/******************************************************************************/
1478
1479static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1480 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001481 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001482 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1483 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001484 PrintCursor(cursor, NULL);
1485 MangledName = clang_Cursor_getMangling(cursor);
1486 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001487 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001488 return CXChildVisit_Continue;
1489}
1490
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001491static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1492 CXClientData d) {
1493 unsigned I, E;
1494 CXStringSet *Manglings = NULL;
1495 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1496 return CXChildVisit_Recurse;
1497 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1498 return CXChildVisit_Recurse;
1499 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1500 return CXChildVisit_Continue;
1501 PrintCursor(cursor, NULL);
1502 Manglings = clang_Cursor_getCXXManglings(cursor);
1503 for (I = 0, E = Manglings->Count; I < E; ++I)
1504 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1505 clang_disposeStringSet(Manglings);
1506 printf("\n");
1507 return CXChildVisit_Recurse;
1508}
1509
Eli Bendersky44a206f2014-07-31 18:04:56 +00001510/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001511/* Bitwidth testing. */
1512/******************************************************************************/
1513
1514static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1515 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001516 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001517 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1518 return CXChildVisit_Recurse;
1519
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001520 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001521 if (Bitwidth >= 0) {
1522 PrintCursor(cursor, NULL);
1523 printf(" bitwidth=%d\n", Bitwidth);
1524 }
1525
1526 return CXChildVisit_Recurse;
1527}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001528
1529/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001530/* Type declaration testing */
1531/******************************************************************************/
1532
1533static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1534 CXClientData d) {
1535 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1536
1537 if (clang_isDeclaration(typeDeclaration.kind)) {
1538 PrintCursor(cursor, NULL);
1539 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1540 }
1541
1542 return CXChildVisit_Recurse;
1543}
1544
1545/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001546/* Loading ASTs/source. */
1547/******************************************************************************/
1548
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001549static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001550 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001551 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001552 PostVisitTU PV,
1553 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001554
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001555 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001556 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001557
1558 if (Visitor) {
1559 enum CXCursorKind K = CXCursor_NotImplemented;
1560 enum CXCursorKind *ck = &K;
1561 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001562
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001563 /* Perform some simple filtering. */
1564 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001565 else if (!strcmp(filter, "all-display") ||
1566 !strcmp(filter, "local-display")) {
1567 ck = NULL;
1568 want_display_name = 1;
1569 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001570 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001571 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1572 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1573 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1574 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1575 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1576 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1577 else {
1578 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1579 return 1;
1580 }
Ted Kremenek29004672010-02-17 00:41:32 +00001581
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001582 Data.TU = TU;
1583 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001584 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001585 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001586 }
Ted Kremenek29004672010-02-17 00:41:32 +00001587
Ted Kremenekb478ff42010-01-26 17:59:48 +00001588 if (PV)
1589 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001590
Douglas Gregor33cdd812010-02-18 18:08:43 +00001591 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001592 if (checkForErrors(TU) != 0) {
1593 clang_disposeTranslationUnit(TU);
1594 return -1;
1595 }
1596
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001597 clang_disposeTranslationUnit(TU);
1598 return 0;
1599}
1600
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001601int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001602 const char *prefix, CXCursorVisitor Visitor,
1603 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001604 CXIndex Idx;
1605 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001606 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001607 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001608 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001609 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001610
Ted Kremenek50228be2010-02-11 07:41:25 +00001611 if (!CreateTranslationUnit(Idx, file, &TU)) {
1612 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001613 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001614 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001615
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001616 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001617 clang_disposeIndex(Idx);
1618 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001619}
1620
Ted Kremenekb478ff42010-01-26 17:59:48 +00001621int perform_test_load_source(int argc, const char **argv,
1622 const char *filter, CXCursorVisitor Visitor,
1623 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001624 CXIndex Idx;
1625 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001626 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001627 struct CXUnsavedFile *unsaved_files = 0;
1628 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001629 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001630 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001631 unsigned Repeats = 0;
1632 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001633
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001634 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001635 (!strcmp(filter, "local") ||
1636 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001637 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001638
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001639 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1640 argc--;
1641 argv++;
1642 }
1643
Ted Kremenek50228be2010-02-11 07:41:25 +00001644 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1645 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001646 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001647 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001648
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001649 if (getenv("CINDEXTEST_EDITING"))
1650 Repeats = 5;
1651
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001652 Err = clang_parseTranslationUnit2(Idx, 0,
1653 argv + num_unsaved_files,
1654 argc - num_unsaved_files,
1655 unsaved_files, num_unsaved_files,
1656 getDefaultParsingOptions(), &TU);
1657 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001658 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001659 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001660 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001661 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001662 return 1;
1663 }
1664
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001665 for (I = 0; I != Repeats; ++I) {
1666 if (checkForErrors(TU) != 0)
1667 return -1;
1668
1669 if (Repeats > 1) {
1670 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1671 clang_defaultReparseOptions(TU));
1672 if (Err != CXError_Success) {
1673 describeLibclangFailure(Err);
1674 free_remapped_files(unsaved_files, num_unsaved_files);
1675 clang_disposeIndex(Idx);
1676 return 1;
1677 }
1678 }
1679 }
1680
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001681 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1682 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001683 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001684 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001685 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001686}
1687
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001688int perform_test_reparse_source(int argc, const char **argv, int trials,
1689 const char *filter, CXCursorVisitor Visitor,
1690 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001691 CXIndex Idx;
1692 CXTranslationUnit TU;
1693 struct CXUnsavedFile *unsaved_files = 0;
1694 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001695 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001696 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001697 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001698 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001699 int remap_after_trial = 0;
1700 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001701
1702 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1703 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001704 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001705
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001706 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1707 clang_disposeIndex(Idx);
1708 return -1;
1709 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001710
1711 for (i = 0; i < argc; ++i) {
1712 if (strcmp(argv[i], "--") == 0)
1713 break;
1714 }
1715 if (i < argc)
1716 compiler_arg_idx = i+1;
1717 if (num_unsaved_files > compiler_arg_idx)
1718 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001719
Daniel Dunbarec29d712010-08-18 23:09:16 +00001720 /* Load the initial translation unit -- we do this without honoring remapped
1721 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001722 Err = clang_parseTranslationUnit2(Idx, 0,
1723 argv + compiler_arg_idx,
1724 argc - compiler_arg_idx,
1725 0, 0, getDefaultParsingOptions(), &TU);
1726 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001727 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001728 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001729 free_remapped_files(unsaved_files, num_unsaved_files);
1730 clang_disposeIndex(Idx);
1731 return 1;
1732 }
1733
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001734 if (checkForErrors(TU) != 0)
1735 return -1;
1736
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001737 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1738 remap_after_trial =
1739 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1740 }
1741
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001742 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001743 free_remapped_files(unsaved_files, num_unsaved_files);
1744 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1745 &unsaved_files, &num_unsaved_files)) {
1746 clang_disposeTranslationUnit(TU);
1747 clang_disposeIndex(Idx);
1748 return -1;
1749 }
1750
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001751 Err = clang_reparseTranslationUnit(
1752 TU,
1753 trial >= remap_after_trial ? num_unsaved_files : 0,
1754 trial >= remap_after_trial ? unsaved_files : 0,
1755 clang_defaultReparseOptions(TU));
1756 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001757 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001758 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001759 clang_disposeTranslationUnit(TU);
1760 free_remapped_files(unsaved_files, num_unsaved_files);
1761 clang_disposeIndex(Idx);
1762 return -1;
1763 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001764
1765 if (checkForErrors(TU) != 0)
1766 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001767 }
1768
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001769 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001770
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001771 free_remapped_files(unsaved_files, num_unsaved_files);
1772 clang_disposeIndex(Idx);
1773 return result;
1774}
1775
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001776/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001777/* Logic for testing clang_getCursor(). */
1778/******************************************************************************/
1779
Douglas Gregor37aa4932011-05-04 00:14:37 +00001780static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001781 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001782 unsigned end_line, unsigned end_col,
1783 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001784 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001785 if (prefix)
1786 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001787 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1788 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001789 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001790 printf("\n");
1791}
1792
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001793static int perform_file_scan(const char *ast_file, const char *source_file,
1794 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001795 CXIndex Idx;
1796 CXTranslationUnit TU;
1797 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001798 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001799 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001800 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001801 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001802
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001803 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001804 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001805 fprintf(stderr, "Could not create Index\n");
1806 return 1;
1807 }
Ted Kremenek29004672010-02-17 00:41:32 +00001808
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001809 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1810 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001811
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001812 if ((fp = fopen(source_file, "r")) == NULL) {
1813 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001814 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001815 return 1;
1816 }
Ted Kremenek29004672010-02-17 00:41:32 +00001817
Douglas Gregor816fd362010-01-22 21:44:22 +00001818 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001819 for (;;) {
1820 CXCursor cursor;
1821 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001822
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001823 if (c == '\n') {
1824 ++line;
1825 col = 1;
1826 } else
1827 ++col;
1828
1829 /* Check the cursor at this position, and dump the previous one if we have
1830 * found something new.
1831 */
1832 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1833 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1834 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001835 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001836 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001837 start_line = line;
1838 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001839 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001840 if (c == EOF)
1841 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001842
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001843 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001844 }
Ted Kremenek29004672010-02-17 00:41:32 +00001845
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001846 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001847 clang_disposeTranslationUnit(TU);
1848 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001849 return 0;
1850}
1851
1852/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001853/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001854/******************************************************************************/
1855
Douglas Gregor9eb77012009-11-07 00:00:49 +00001856/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1857 on failure. If successful, the pointer *filename will contain newly-allocated
1858 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001859int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001860 unsigned *column, unsigned *second_line,
1861 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001862 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001863 const char *last_colon = strrchr(input, ':');
1864 unsigned values[4], i;
1865 unsigned num_values = (second_line && second_column)? 4 : 2;
1866
Douglas Gregor9eb77012009-11-07 00:00:49 +00001867 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001868 if (!last_colon || last_colon == input) {
1869 if (num_values == 4)
1870 fprintf(stderr, "could not parse filename:line:column:line:column in "
1871 "'%s'\n", input);
1872 else
1873 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001874 return 1;
1875 }
1876
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001877 for (i = 0; i != num_values; ++i) {
1878 const char *prev_colon;
1879
1880 /* Parse the next line or column. */
1881 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1882 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001883 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001884 (i % 2 ? "column" : "line"), input);
1885 return 1;
1886 }
Ted Kremenek29004672010-02-17 00:41:32 +00001887
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001888 if (i + 1 == num_values)
1889 break;
1890
1891 /* Find the previous colon. */
1892 prev_colon = last_colon - 1;
1893 while (prev_colon != input && *prev_colon != ':')
1894 --prev_colon;
1895 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001896 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001897 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001898 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001899 }
1900
1901 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001902 }
1903
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001904 *line = values[0];
1905 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001906
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001907 if (second_line && second_column) {
1908 *second_line = values[2];
1909 *second_column = values[3];
1910 }
1911
Douglas Gregorf96ea292009-11-09 18:19:57 +00001912 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001913 *filename = (char*)malloc(last_colon - input + 1);
1914 memcpy(*filename, input, last_colon - input);
1915 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001916 return 0;
1917}
1918
1919const char *
1920clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1921 switch (Kind) {
1922 case CXCompletionChunk_Optional: return "Optional";
1923 case CXCompletionChunk_TypedText: return "TypedText";
1924 case CXCompletionChunk_Text: return "Text";
1925 case CXCompletionChunk_Placeholder: return "Placeholder";
1926 case CXCompletionChunk_Informative: return "Informative";
1927 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1928 case CXCompletionChunk_LeftParen: return "LeftParen";
1929 case CXCompletionChunk_RightParen: return "RightParen";
1930 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1931 case CXCompletionChunk_RightBracket: return "RightBracket";
1932 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1933 case CXCompletionChunk_RightBrace: return "RightBrace";
1934 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1935 case CXCompletionChunk_RightAngle: return "RightAngle";
1936 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001937 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001938 case CXCompletionChunk_Colon: return "Colon";
1939 case CXCompletionChunk_SemiColon: return "SemiColon";
1940 case CXCompletionChunk_Equal: return "Equal";
1941 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1942 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001943 }
Ted Kremenek29004672010-02-17 00:41:32 +00001944
Douglas Gregor9eb77012009-11-07 00:00:49 +00001945 return "Unknown";
1946}
1947
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001948static int checkForErrors(CXTranslationUnit TU) {
1949 unsigned Num, i;
1950 CXDiagnostic Diag;
1951 CXString DiagStr;
1952
1953 if (!getenv("CINDEXTEST_FAILONERROR"))
1954 return 0;
1955
1956 Num = clang_getNumDiagnostics(TU);
1957 for (i = 0; i != Num; ++i) {
1958 Diag = clang_getDiagnostic(TU, i);
1959 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1960 DiagStr = clang_formatDiagnostic(Diag,
1961 clang_defaultDiagnosticDisplayOptions());
1962 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1963 clang_disposeString(DiagStr);
1964 clang_disposeDiagnostic(Diag);
1965 return -1;
1966 }
1967 clang_disposeDiagnostic(Diag);
1968 }
1969
1970 return 0;
1971}
1972
Nico Weber8d19dff2014-05-07 21:05:22 +00001973static void print_completion_string(CXCompletionString completion_string,
1974 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001975 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001976
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001977 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001978 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001979 CXString text;
1980 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001981 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001982 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001983
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001984 if (Kind == CXCompletionChunk_Optional) {
1985 fprintf(file, "{Optional ");
1986 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001987 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001988 file);
1989 fprintf(file, "}");
1990 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001991 }
1992
1993 if (Kind == CXCompletionChunk_VerticalSpace) {
1994 fprintf(file, "{VerticalSpace }");
1995 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001996 }
Ted Kremenek29004672010-02-17 00:41:32 +00001997
Douglas Gregorf81f5282009-11-09 17:05:28 +00001998 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001999 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00002000 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00002001 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00002002 cstr ? cstr : "");
2003 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002004 }
Ted Kremenekf602f962010-02-17 01:42:24 +00002005
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002006}
2007
Nico Weber8d19dff2014-05-07 21:05:22 +00002008static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00002009 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002010 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002011 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00002012 enum CXCursorKind ParentKind;
2013 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002014 CXString BriefComment;
Vedant Kumarf27d2272016-04-03 00:54:46 +00002015 CXString Annotation;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002016 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00002017
Ted Kremenek29004672010-02-17 00:41:32 +00002018 fprintf(file, "%s:", clang_getCString(ks));
2019 clang_disposeString(ks);
2020
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002021 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00002022 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00002023 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00002024 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
2025 case CXAvailability_Available:
2026 break;
2027
2028 case CXAvailability_Deprecated:
2029 fprintf(file, " (deprecated)");
2030 break;
2031
2032 case CXAvailability_NotAvailable:
2033 fprintf(file, " (unavailable)");
2034 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002035
2036 case CXAvailability_NotAccessible:
2037 fprintf(file, " (inaccessible)");
2038 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002039 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002040
2041 annotationCount = clang_getCompletionNumAnnotations(
2042 completion_result->CompletionString);
2043 if (annotationCount) {
2044 unsigned i;
2045 fprintf(file, " (");
2046 for (i = 0; i < annotationCount; ++i) {
2047 if (i != 0)
2048 fprintf(file, ", ");
Vedant Kumarf27d2272016-04-03 00:54:46 +00002049 Annotation =
2050 clang_getCompletionAnnotation(completion_result->CompletionString, i);
2051 fprintf(file, "\"%s\"", clang_getCString(Annotation));
2052 clang_disposeString(Annotation);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002053 }
2054 fprintf(file, ")");
2055 }
2056
Douglas Gregor78254c82012-03-27 23:34:16 +00002057 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2058 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2059 &ParentKind);
2060 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002061 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002062 fprintf(file, " (parent: %s '%s')",
2063 clang_getCString(KindSpelling),
2064 clang_getCString(ParentName));
2065 clang_disposeString(KindSpelling);
2066 }
2067 clang_disposeString(ParentName);
2068 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002069
2070 BriefComment = clang_getCompletionBriefComment(
2071 completion_result->CompletionString);
2072 BriefCommentCString = clang_getCString(BriefComment);
2073 if (BriefCommentCString && *BriefCommentCString != '\0') {
2074 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2075 }
2076 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002077
Douglas Gregorf757a122010-08-23 23:00:57 +00002078 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002079}
2080
Douglas Gregor21325842011-07-07 16:03:39 +00002081void print_completion_contexts(unsigned long long contexts, FILE *file) {
2082 fprintf(file, "Completion contexts:\n");
2083 if (contexts == CXCompletionContext_Unknown) {
2084 fprintf(file, "Unknown\n");
2085 }
2086 if (contexts & CXCompletionContext_AnyType) {
2087 fprintf(file, "Any type\n");
2088 }
2089 if (contexts & CXCompletionContext_AnyValue) {
2090 fprintf(file, "Any value\n");
2091 }
2092 if (contexts & CXCompletionContext_ObjCObjectValue) {
2093 fprintf(file, "Objective-C object value\n");
2094 }
2095 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2096 fprintf(file, "Objective-C selector value\n");
2097 }
2098 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2099 fprintf(file, "C++ class type value\n");
2100 }
2101 if (contexts & CXCompletionContext_DotMemberAccess) {
2102 fprintf(file, "Dot member access\n");
2103 }
2104 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2105 fprintf(file, "Arrow member access\n");
2106 }
2107 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2108 fprintf(file, "Objective-C property access\n");
2109 }
2110 if (contexts & CXCompletionContext_EnumTag) {
2111 fprintf(file, "Enum tag\n");
2112 }
2113 if (contexts & CXCompletionContext_UnionTag) {
2114 fprintf(file, "Union tag\n");
2115 }
2116 if (contexts & CXCompletionContext_StructTag) {
2117 fprintf(file, "Struct tag\n");
2118 }
2119 if (contexts & CXCompletionContext_ClassTag) {
2120 fprintf(file, "Class name\n");
2121 }
2122 if (contexts & CXCompletionContext_Namespace) {
2123 fprintf(file, "Namespace or namespace alias\n");
2124 }
2125 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2126 fprintf(file, "Nested name specifier\n");
2127 }
2128 if (contexts & CXCompletionContext_ObjCInterface) {
2129 fprintf(file, "Objective-C interface\n");
2130 }
2131 if (contexts & CXCompletionContext_ObjCProtocol) {
2132 fprintf(file, "Objective-C protocol\n");
2133 }
2134 if (contexts & CXCompletionContext_ObjCCategory) {
2135 fprintf(file, "Objective-C category\n");
2136 }
2137 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2138 fprintf(file, "Objective-C instance method\n");
2139 }
2140 if (contexts & CXCompletionContext_ObjCClassMessage) {
2141 fprintf(file, "Objective-C class method\n");
2142 }
2143 if (contexts & CXCompletionContext_ObjCSelectorName) {
2144 fprintf(file, "Objective-C selector name\n");
2145 }
2146 if (contexts & CXCompletionContext_MacroName) {
2147 fprintf(file, "Macro name\n");
2148 }
2149 if (contexts & CXCompletionContext_NaturalLanguage) {
2150 fprintf(file, "Natural language\n");
2151 }
2152}
2153
Douglas Gregor47815d52010-07-12 18:38:41 +00002154int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002155 const char *input = argv[1];
2156 char *filename = 0;
2157 unsigned line;
2158 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002159 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002160 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002161 struct CXUnsavedFile *unsaved_files = 0;
2162 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002163 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002164 enum CXErrorCode Err;
2165 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002166 unsigned I, Repeats = 1;
2167 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2168
2169 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2170 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002171 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2172 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002173
Douglas Gregor47815d52010-07-12 18:38:41 +00002174 if (timing_only)
2175 input += strlen("-code-completion-timing=");
2176 else
2177 input += strlen("-code-completion-at=");
2178
Ted Kremenek29004672010-02-17 00:41:32 +00002179 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002180 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002181 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002182
Douglas Gregor9485bf92009-12-02 09:21:34 +00002183 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2184 return -1;
2185
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002186 CIdx = clang_createIndex(0, 0);
2187
2188 if (getenv("CINDEXTEST_EDITING"))
2189 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002190
2191 Err = clang_parseTranslationUnit2(CIdx, 0,
2192 argv + num_unsaved_files + 2,
2193 argc - num_unsaved_files - 2,
2194 0, 0, getDefaultParsingOptions(), &TU);
2195 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002196 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002197 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002198 return 1;
2199 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002200
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002201 Err = clang_reparseTranslationUnit(TU, 0, 0,
2202 clang_defaultReparseOptions(TU));
2203
2204 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002205 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002206 describeLibclangFailure(Err);
2207 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002208 return 1;
2209 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002210
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002211 for (I = 0; I != Repeats; ++I) {
2212 results = clang_codeCompleteAt(TU, filename, line, column,
2213 unsaved_files, num_unsaved_files,
2214 completionOptions);
2215 if (!results) {
2216 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002217 return 1;
2218 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002219 if (I != Repeats-1)
2220 clang_disposeCodeCompleteResults(results);
2221 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002222
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002223 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002224 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002225 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002226 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002227 CXString objCSelector;
2228 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002229 if (!timing_only) {
2230 /* Sort the code-completion results based on the typed text. */
2231 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2232
Douglas Gregor47815d52010-07-12 18:38:41 +00002233 for (i = 0; i != n; ++i)
2234 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002235 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002236 n = clang_codeCompleteGetNumDiagnostics(results);
2237 for (i = 0; i != n; ++i) {
2238 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2239 PrintDiagnostic(diag);
2240 clang_disposeDiagnostic(diag);
2241 }
Douglas Gregor21325842011-07-07 16:03:39 +00002242
2243 contexts = clang_codeCompleteGetContexts(results);
2244 print_completion_contexts(contexts, stdout);
2245
Douglas Gregorea777402011-07-26 15:24:30 +00002246 containerKind = clang_codeCompleteGetContainerKind(results,
2247 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002248
2249 if (containerKind != CXCursor_InvalidCode) {
2250 /* We have found a container */
2251 CXString containerUSR, containerKindSpelling;
2252 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2253 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2254 clang_disposeString(containerKindSpelling);
2255
2256 if (containerIsIncomplete) {
2257 printf("Container is incomplete\n");
2258 }
2259 else {
2260 printf("Container is complete\n");
2261 }
2262
2263 containerUSR = clang_codeCompleteGetContainerUSR(results);
2264 printf("Container USR: %s\n", clang_getCString(containerUSR));
2265 clang_disposeString(containerUSR);
2266 }
2267
Douglas Gregorea777402011-07-26 15:24:30 +00002268 objCSelector = clang_codeCompleteGetObjCSelector(results);
2269 selectorString = clang_getCString(objCSelector);
2270 if (selectorString && strlen(selectorString) > 0) {
2271 printf("Objective-C selector: %s\n", selectorString);
2272 }
2273 clang_disposeString(objCSelector);
2274
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002275 clang_disposeCodeCompleteResults(results);
2276 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002277 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002278 clang_disposeIndex(CIdx);
2279 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002280
Douglas Gregor9485bf92009-12-02 09:21:34 +00002281 free_remapped_files(unsaved_files, num_unsaved_files);
2282
Ted Kremenekef3339b2009-11-17 18:09:14 +00002283 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002284}
2285
Douglas Gregor082c3e62010-01-15 19:40:17 +00002286typedef struct {
2287 char *filename;
2288 unsigned line;
2289 unsigned column;
2290} CursorSourceLocation;
2291
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002292typedef void (*cursor_handler_t)(CXCursor cursor);
2293
2294static int inspect_cursor_at(int argc, const char **argv,
2295 const char *locations_flag,
2296 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002297 CXIndex CIdx;
2298 int errorCode;
2299 struct CXUnsavedFile *unsaved_files = 0;
2300 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002301 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002302 CXTranslationUnit TU;
2303 CXCursor Cursor;
2304 CursorSourceLocation *Locations = 0;
2305 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002306 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002307 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002308
Ted Kremenek29004672010-02-17 00:41:32 +00002309 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002310 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002311 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002312
Douglas Gregor082c3e62010-01-15 19:40:17 +00002313 /* Parse the locations. */
2314 assert(NumLocations > 0 && "Unable to count locations?");
2315 Locations = (CursorSourceLocation *)malloc(
2316 NumLocations * sizeof(CursorSourceLocation));
2317 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002318 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002319 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2320 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002321 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002322 return errorCode;
2323 }
Ted Kremenek29004672010-02-17 00:41:32 +00002324
2325 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002326 &num_unsaved_files))
2327 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002328
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002329 if (getenv("CINDEXTEST_EDITING"))
2330 Repeats = 5;
2331
2332 /* Parse the translation unit. When we're testing clang_getCursor() after
2333 reparsing, don't remap unsaved files until the second parse. */
2334 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002335 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2336 argv + num_unsaved_files + 1 + NumLocations,
2337 argc - num_unsaved_files - 2 - NumLocations,
2338 unsaved_files,
2339 Repeats > 1? 0 : num_unsaved_files,
2340 getDefaultParsingOptions(), &TU);
2341 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002342 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002343 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002344 return -1;
2345 }
Ted Kremenek29004672010-02-17 00:41:32 +00002346
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002347 if (checkForErrors(TU) != 0)
2348 return -1;
2349
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002350 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002351 if (Repeats > 1) {
2352 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2353 clang_defaultReparseOptions(TU));
2354 if (Err != CXError_Success) {
2355 describeLibclangFailure(Err);
2356 clang_disposeTranslationUnit(TU);
2357 return 1;
2358 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002359 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002360
2361 if (checkForErrors(TU) != 0)
2362 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002363
2364 for (Loc = 0; Loc < NumLocations; ++Loc) {
2365 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2366 if (!file)
2367 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002368
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002369 Cursor = clang_getCursor(TU,
2370 clang_getLocation(TU, file, Locations[Loc].line,
2371 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002372
2373 if (checkForErrors(TU) != 0)
2374 return -1;
2375
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002376 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002377 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002378 free(Locations[Loc].filename);
2379 }
2380 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002381 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002382
Douglas Gregor33cdd812010-02-18 18:08:43 +00002383 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002384 clang_disposeTranslationUnit(TU);
2385 clang_disposeIndex(CIdx);
2386 free(Locations);
2387 free_remapped_files(unsaved_files, num_unsaved_files);
2388 return 0;
2389}
2390
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002391static void inspect_print_cursor(CXCursor Cursor) {
2392 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2393 CXCompletionString completionString = clang_getCursorCompletionString(
2394 Cursor);
2395 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2396 CXString Spelling;
2397 const char *cspell;
2398 unsigned line, column;
2399 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2400 printf("%d:%d ", line, column);
2401 PrintCursor(Cursor, NULL);
2402 PrintCursorExtent(Cursor);
2403 Spelling = clang_getCursorSpelling(Cursor);
2404 cspell = clang_getCString(Spelling);
2405 if (cspell && strlen(cspell) != 0) {
2406 unsigned pieceIndex;
2407 printf(" Spelling=%s (", cspell);
2408 for (pieceIndex = 0; ; ++pieceIndex) {
2409 CXSourceRange range =
2410 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2411 if (clang_Range_isNull(range))
2412 break;
2413 PrintRange(range, 0);
2414 }
2415 printf(")");
2416 }
2417 clang_disposeString(Spelling);
2418 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2419 printf(" Selector index=%d",
2420 clang_Cursor_getObjCSelectorIndex(Cursor));
2421 if (clang_Cursor_isDynamicCall(Cursor))
2422 printf(" Dynamic-call");
2423 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2424 CXType T = clang_Cursor_getReceiverType(Cursor);
2425 CXString S = clang_getTypeKindSpelling(T.kind);
2426 printf(" Receiver-type=%s", clang_getCString(S));
2427 clang_disposeString(S);
2428 }
2429
2430 {
2431 CXModule mod = clang_Cursor_getModule(Cursor);
2432 CXFile astFile;
2433 CXString name, astFilename;
2434 unsigned i, numHeaders;
2435 if (mod) {
2436 astFile = clang_Module_getASTFile(mod);
2437 astFilename = clang_getFileName(astFile);
2438 name = clang_Module_getFullName(mod);
2439 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2440 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2441 clang_getCString(name), clang_getCString(astFilename),
2442 clang_Module_isSystem(mod), numHeaders);
2443 clang_disposeString(name);
2444 clang_disposeString(astFilename);
2445 for (i = 0; i < numHeaders; ++i) {
2446 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2447 CXString filename = clang_getFileName(file);
2448 printf("\n%s", clang_getCString(filename));
2449 clang_disposeString(filename);
2450 }
2451 }
2452 }
2453
2454 if (completionString != NULL) {
2455 printf("\nCompletion string: ");
2456 print_completion_string(completionString, stdout);
2457 }
2458 printf("\n");
2459}
2460
2461static void display_evaluate_results(CXEvalResult result) {
2462 switch (clang_EvalResult_getKind(result)) {
2463 case CXEval_Int:
2464 {
2465 int val = clang_EvalResult_getAsInt(result);
2466 printf("Kind: Int , Value: %d", val);
2467 break;
2468 }
2469 case CXEval_Float:
2470 {
2471 double val = clang_EvalResult_getAsDouble(result);
2472 printf("Kind: Float , Value: %f", val);
2473 break;
2474 }
2475 case CXEval_ObjCStrLiteral:
2476 {
2477 const char* str = clang_EvalResult_getAsStr(result);
2478 printf("Kind: ObjCString , Value: %s", str);
2479 break;
2480 }
2481 case CXEval_StrLiteral:
2482 {
2483 const char* str = clang_EvalResult_getAsStr(result);
2484 printf("Kind: CString , Value: %s", str);
2485 break;
2486 }
2487 case CXEval_CFStr:
2488 {
2489 const char* str = clang_EvalResult_getAsStr(result);
2490 printf("Kind: CFString , Value: %s", str);
2491 break;
2492 }
2493 default:
2494 printf("Unexposed");
2495 break;
2496 }
2497}
2498
2499static void inspect_evaluate_cursor(CXCursor Cursor) {
2500 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2501 CXString Spelling;
2502 const char *cspell;
2503 unsigned line, column;
2504 CXEvalResult ER;
2505
2506 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2507 printf("%d:%d ", line, column);
2508 PrintCursor(Cursor, NULL);
2509 PrintCursorExtent(Cursor);
2510 Spelling = clang_getCursorSpelling(Cursor);
2511 cspell = clang_getCString(Spelling);
2512 if (cspell && strlen(cspell) != 0) {
2513 unsigned pieceIndex;
2514 printf(" Spelling=%s (", cspell);
2515 for (pieceIndex = 0; ; ++pieceIndex) {
2516 CXSourceRange range =
2517 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2518 if (clang_Range_isNull(range))
2519 break;
2520 PrintRange(range, 0);
2521 }
2522 printf(")");
2523 }
2524 clang_disposeString(Spelling);
2525
2526 ER = clang_Cursor_Evaluate(Cursor);
2527 if (!ER) {
2528 printf("Not Evaluatable");
2529 } else {
2530 display_evaluate_results(ER);
2531 clang_EvalResult_dispose(ER);
2532 }
2533 printf("\n");
2534}
2535
2536static void inspect_macroinfo_cursor(CXCursor Cursor) {
2537 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2538 CXString Spelling;
2539 const char *cspell;
2540 unsigned line, column;
2541 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2542 printf("%d:%d ", line, column);
2543 PrintCursor(Cursor, NULL);
2544 PrintCursorExtent(Cursor);
2545 Spelling = clang_getCursorSpelling(Cursor);
2546 cspell = clang_getCString(Spelling);
2547 if (cspell && strlen(cspell) != 0) {
2548 unsigned pieceIndex;
2549 printf(" Spelling=%s (", cspell);
2550 for (pieceIndex = 0; ; ++pieceIndex) {
2551 CXSourceRange range =
2552 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2553 if (clang_Range_isNull(range))
2554 break;
2555 PrintRange(range, 0);
2556 }
2557 printf(")");
2558 }
2559 clang_disposeString(Spelling);
2560
2561 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2562 printf("[builtin macro]");
2563 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2564 printf("[function macro]");
2565 }
2566 printf("\n");
2567}
2568
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002569static enum CXVisitorResult findFileRefsVisit(void *context,
2570 CXCursor cursor, CXSourceRange range) {
2571 if (clang_Range_isNull(range))
2572 return CXVisit_Continue;
2573
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002574 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002575 PrintRange(range, "");
2576 printf("\n");
2577 return CXVisit_Continue;
2578}
2579
2580static int find_file_refs_at(int argc, const char **argv) {
2581 CXIndex CIdx;
2582 int errorCode;
2583 struct CXUnsavedFile *unsaved_files = 0;
2584 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002585 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002586 CXTranslationUnit TU;
2587 CXCursor Cursor;
2588 CursorSourceLocation *Locations = 0;
2589 unsigned NumLocations = 0, Loc;
2590 unsigned Repeats = 1;
2591 unsigned I;
2592
2593 /* Count the number of locations. */
2594 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2595 ++NumLocations;
2596
2597 /* Parse the locations. */
2598 assert(NumLocations > 0 && "Unable to count locations?");
2599 Locations = (CursorSourceLocation *)malloc(
2600 NumLocations * sizeof(CursorSourceLocation));
2601 for (Loc = 0; Loc < NumLocations; ++Loc) {
2602 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2603 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2604 &Locations[Loc].line,
2605 &Locations[Loc].column, 0, 0)))
2606 return errorCode;
2607 }
2608
2609 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2610 &num_unsaved_files))
2611 return -1;
2612
2613 if (getenv("CINDEXTEST_EDITING"))
2614 Repeats = 5;
2615
2616 /* Parse the translation unit. When we're testing clang_getCursor() after
2617 reparsing, don't remap unsaved files until the second parse. */
2618 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002619 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2620 argv + num_unsaved_files + 1 + NumLocations,
2621 argc - num_unsaved_files - 2 - NumLocations,
2622 unsaved_files,
2623 Repeats > 1? 0 : num_unsaved_files,
2624 getDefaultParsingOptions(), &TU);
2625 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002626 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002627 describeLibclangFailure(Err);
2628 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002629 return -1;
2630 }
2631
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002632 if (checkForErrors(TU) != 0)
2633 return -1;
2634
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002635 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002636 if (Repeats > 1) {
2637 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2638 clang_defaultReparseOptions(TU));
2639 if (Err != CXError_Success) {
2640 describeLibclangFailure(Err);
2641 clang_disposeTranslationUnit(TU);
2642 return 1;
2643 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002644 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002645
2646 if (checkForErrors(TU) != 0)
2647 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002648
2649 for (Loc = 0; Loc < NumLocations; ++Loc) {
2650 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2651 if (!file)
2652 continue;
2653
2654 Cursor = clang_getCursor(TU,
2655 clang_getLocation(TU, file, Locations[Loc].line,
2656 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002657
2658 if (checkForErrors(TU) != 0)
2659 return -1;
2660
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002661 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002662 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002663 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002664 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002665 clang_findReferencesInFile(Cursor, file, visitor);
2666 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002667
2668 if (checkForErrors(TU) != 0)
2669 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002670 }
2671 }
2672 }
2673
2674 PrintDiagnostics(TU);
2675 clang_disposeTranslationUnit(TU);
2676 clang_disposeIndex(CIdx);
2677 free(Locations);
2678 free_remapped_files(unsaved_files, num_unsaved_files);
2679 return 0;
2680}
2681
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002682static enum CXVisitorResult findFileIncludesVisit(void *context,
2683 CXCursor cursor, CXSourceRange range) {
2684 PrintCursor(cursor, NULL);
2685 PrintRange(range, "");
2686 printf("\n");
2687 return CXVisit_Continue;
2688}
2689
2690static int find_file_includes_in(int argc, const char **argv) {
2691 CXIndex CIdx;
2692 struct CXUnsavedFile *unsaved_files = 0;
2693 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002694 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002695 CXTranslationUnit TU;
2696 const char **Filenames = 0;
2697 unsigned NumFilenames = 0;
2698 unsigned Repeats = 1;
2699 unsigned I, FI;
2700
2701 /* Count the number of locations. */
2702 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2703 ++NumFilenames;
2704
2705 /* Parse the locations. */
2706 assert(NumFilenames > 0 && "Unable to count filenames?");
2707 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2708 for (I = 0; I < NumFilenames; ++I) {
2709 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2710 /* Copy the file name. */
2711 Filenames[I] = input;
2712 }
2713
2714 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2715 &num_unsaved_files))
2716 return -1;
2717
2718 if (getenv("CINDEXTEST_EDITING"))
2719 Repeats = 2;
2720
2721 /* Parse the translation unit. When we're testing clang_getCursor() after
2722 reparsing, don't remap unsaved files until the second parse. */
2723 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002724 Err = clang_parseTranslationUnit2(
2725 CIdx, argv[argc - 1],
2726 argv + num_unsaved_files + 1 + NumFilenames,
2727 argc - num_unsaved_files - 2 - NumFilenames,
2728 unsaved_files,
2729 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002730
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002731 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002732 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002733 describeLibclangFailure(Err);
2734 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002735 return -1;
2736 }
2737
2738 if (checkForErrors(TU) != 0)
2739 return -1;
2740
2741 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002742 if (Repeats > 1) {
2743 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2744 clang_defaultReparseOptions(TU));
2745 if (Err != CXError_Success) {
2746 describeLibclangFailure(Err);
2747 clang_disposeTranslationUnit(TU);
2748 return 1;
2749 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002750 }
2751
2752 if (checkForErrors(TU) != 0)
2753 return -1;
2754
2755 for (FI = 0; FI < NumFilenames; ++FI) {
2756 CXFile file = clang_getFile(TU, Filenames[FI]);
2757 if (!file)
2758 continue;
2759
2760 if (checkForErrors(TU) != 0)
2761 return -1;
2762
2763 if (I + 1 == Repeats) {
2764 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2765 clang_findIncludesInFile(TU, file, visitor);
2766
2767 if (checkForErrors(TU) != 0)
2768 return -1;
2769 }
2770 }
2771 }
2772
2773 PrintDiagnostics(TU);
2774 clang_disposeTranslationUnit(TU);
2775 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002776 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002777 free_remapped_files(unsaved_files, num_unsaved_files);
2778 return 0;
2779}
2780
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002781#define MAX_IMPORTED_ASTFILES 200
2782
2783typedef struct {
2784 char **filenames;
2785 unsigned num_files;
2786} ImportedASTFilesData;
2787
2788static ImportedASTFilesData *importedASTs_create() {
2789 ImportedASTFilesData *p;
2790 p = malloc(sizeof(ImportedASTFilesData));
2791 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2792 p->num_files = 0;
2793 return p;
2794}
2795
2796static void importedASTs_dispose(ImportedASTFilesData *p) {
2797 unsigned i;
2798 if (!p)
2799 return;
2800
2801 for (i = 0; i < p->num_files; ++i)
2802 free(p->filenames[i]);
2803 free(p->filenames);
2804 free(p);
2805}
2806
2807static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2808 unsigned i;
2809 assert(p && file);
2810 for (i = 0; i < p->num_files; ++i)
2811 if (strcmp(file, p->filenames[i]) == 0)
2812 return;
2813 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2814 p->filenames[p->num_files++] = strdup(file);
2815}
2816
Nico Weberdf686022014-05-07 21:09:42 +00002817typedef struct IndexDataStringList_ {
2818 struct IndexDataStringList_ *next;
2819 char data[1]; /* Dynamically sized. */
2820} IndexDataStringList;
2821
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002822typedef struct {
2823 const char *check_prefix;
2824 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002825 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002826 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002827 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002828 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002829 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002830 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002831} IndexData;
2832
Nico Weberdf686022014-05-07 21:09:42 +00002833static void free_client_data(IndexData *index_data) {
2834 IndexDataStringList *node = index_data->strings;
2835 while (node) {
2836 IndexDataStringList *next = node->next;
2837 free(node);
2838 node = next;
2839 }
2840 index_data->strings = NULL;
2841}
2842
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002843static void printCheck(IndexData *data) {
2844 if (data->check_prefix) {
2845 if (data->first_check_printed) {
2846 printf("// %s-NEXT: ", data->check_prefix);
2847 } else {
2848 printf("// %s : ", data->check_prefix);
2849 data->first_check_printed = 1;
2850 }
2851 }
2852}
2853
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002854static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002855 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002856 printf("%s", clang_getCString(filename));
2857 clang_disposeString(filename);
2858}
2859
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002860static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2861 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002862 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002863 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002864 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002865 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002866 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002867
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002868 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002869 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2870 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002871 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002872 return;
2873 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002874 if (!file) {
2875 printf("<no idxfile>");
2876 return;
2877 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002878 filename = clang_getFileName((CXFile)file);
2879 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002880 if (strcmp(cname, index_data->main_filename) == 0)
2881 isMainFile = 1;
2882 else
2883 isMainFile = 0;
2884 clang_disposeString(filename);
2885
2886 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002887 printCXIndexFile(file);
2888 printf(":");
2889 }
2890 printf("%d:%d", line, column);
2891}
2892
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002893static unsigned digitCount(unsigned val) {
2894 unsigned c = 1;
2895 while (1) {
2896 if (val < 10)
2897 return c;
2898 ++c;
2899 val /= 10;
2900 }
2901}
2902
Nico Weberdf686022014-05-07 21:09:42 +00002903static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2904 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002905 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002906 IndexData *index_data;
2907 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002908 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002909 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002910 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002911 unsigned line, column;
2912
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002913 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002914 if (!name)
2915 name = "<anon-tag>";
2916
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002917 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002918
2919 node =
2920 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2921 digitCount(line) + digitCount(column) + 2);
2922 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002923 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002924
2925 /* Remember string so it can be freed later. */
2926 index_data = (IndexData *)client_data;
2927 node->next = index_data->strings;
2928 index_data->strings = node;
2929
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002930 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002931}
2932
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002933static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2934 CXIdxClientContainer container;
2935 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002936 if (!container)
2937 printf("[<<NULL>>]");
2938 else
2939 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002940}
2941
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002942static const char *getEntityKindString(CXIdxEntityKind kind) {
2943 switch (kind) {
2944 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2945 case CXIdxEntity_Typedef: return "typedef";
2946 case CXIdxEntity_Function: return "function";
2947 case CXIdxEntity_Variable: return "variable";
2948 case CXIdxEntity_Field: return "field";
2949 case CXIdxEntity_EnumConstant: return "enumerator";
2950 case CXIdxEntity_ObjCClass: return "objc-class";
2951 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2952 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002953 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2954 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002955 case CXIdxEntity_ObjCProperty: return "objc-property";
2956 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2957 case CXIdxEntity_Enum: return "enum";
2958 case CXIdxEntity_Struct: return "struct";
2959 case CXIdxEntity_Union: return "union";
2960 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002961 case CXIdxEntity_CXXNamespace: return "namespace";
2962 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2963 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2964 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2965 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2966 case CXIdxEntity_CXXConstructor: return "constructor";
2967 case CXIdxEntity_CXXDestructor: return "destructor";
2968 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2969 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002970 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002971 }
2972 assert(0 && "Garbage entity kind");
2973 return 0;
2974}
2975
2976static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2977 switch (kind) {
2978 case CXIdxEntity_NonTemplate: return "";
2979 case CXIdxEntity_Template: return "-template";
2980 case CXIdxEntity_TemplatePartialSpecialization:
2981 return "-template-partial-spec";
2982 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002983 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002984 assert(0 && "Garbage entity kind");
2985 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002986}
2987
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002988static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2989 switch (kind) {
2990 case CXIdxEntityLang_None: return "<none>";
2991 case CXIdxEntityLang_C: return "C";
2992 case CXIdxEntityLang_ObjC: return "ObjC";
2993 case CXIdxEntityLang_CXX: return "C++";
2994 }
2995 assert(0 && "Garbage language kind");
2996 return 0;
2997}
2998
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002999static void printEntityInfo(const char *cb,
3000 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003001 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003002 const char *name;
3003 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003004 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003005 index_data = (IndexData *)client_data;
3006 printCheck(index_data);
3007
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00003008 if (!info) {
3009 printf("%s: <<NULL>>", cb);
3010 return;
3011 }
3012
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003013 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003014 if (!name)
3015 name = "<anon-tag>";
3016
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003017 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
3018 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003019 printf(" | name: %s", name);
3020 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00003021 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003022
3023 for (i = 0; i != info->numAttributes; ++i) {
3024 const CXIdxAttrInfo *Attr = info->attributes[i];
3025 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003026 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003027 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003028}
3029
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003030static void printBaseClassInfo(CXClientData client_data,
3031 const CXIdxBaseClassInfo *info) {
3032 printEntityInfo(" <base>", client_data, info->base);
3033 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003034 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003035 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003036 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003037}
3038
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003039static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3040 CXClientData client_data) {
3041 unsigned i;
3042 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3043 printEntityInfo(" <protocol>", client_data,
3044 ProtoInfo->protocols[i]->protocol);
3045 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003046 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003047 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003048 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003049 printf("\n");
3050 }
3051}
3052
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003053static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003054 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003055 CXString str;
3056 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003057 unsigned numDiags, i;
3058 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003059 IndexData *index_data;
3060 index_data = (IndexData *)client_data;
3061 printCheck(index_data);
3062
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003063 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3064 for (i = 0; i != numDiags; ++i) {
3065 diag = clang_getDiagnosticInSet(diagSet, i);
3066 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3067 cstr = clang_getCString(str);
3068 printf("[diagnostic]: %s\n", cstr);
3069 clang_disposeString(str);
3070
3071 if (getenv("CINDEXTEST_FAILONERROR") &&
3072 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3073 index_data->fail_for_error = 1;
3074 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003075 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003076}
3077
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003078static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3079 CXFile file, void *reserved) {
3080 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003081 CXString filename;
3082
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003083 index_data = (IndexData *)client_data;
3084 printCheck(index_data);
3085
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003086 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003087 index_data->main_filename = clang_getCString(filename);
3088 clang_disposeString(filename);
3089
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003090 printf("[enteredMainFile]: ");
3091 printCXIndexFile((CXIdxClientFile)file);
3092 printf("\n");
3093
3094 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003095}
3096
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003097static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003098 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003099 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003100 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003101 index_data = (IndexData *)client_data;
3102 printCheck(index_data);
3103
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003104 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003105 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003106 printf(" | name: \"%s\"", info->filename);
3107 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003108 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003109 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003110 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003111
3112 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3113 if (Mod) {
3114 CXString str = clang_Module_getFullName(Mod);
3115 const char *cstr = clang_getCString(str);
3116 printf(" | module: %s", cstr);
3117 clang_disposeString(str);
3118 }
3119
3120 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003121
3122 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003123}
3124
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003125static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3126 const CXIdxImportedASTFileInfo *info) {
3127 IndexData *index_data;
3128 index_data = (IndexData *)client_data;
3129 printCheck(index_data);
3130
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003131 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003132 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003133 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3134 clang_disposeString(filename);
3135 }
3136
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003137 printf("[importedASTFile]: ");
3138 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003139 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003140 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003141 printf(" | loc: ");
3142 printCXIndexLoc(info->loc, client_data);
3143 printf(" | name: \"%s\"", clang_getCString(name));
3144 printf(" | isImplicit: %d\n", info->isImplicit);
3145 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003146 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003147 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003148 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003149 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003150
3151 return (CXIdxClientFile)info->file;
3152}
3153
Nico Weber8d19dff2014-05-07 21:05:22 +00003154static CXIdxClientContainer
3155index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003156 IndexData *index_data;
3157 index_data = (IndexData *)client_data;
3158 printCheck(index_data);
3159
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003160 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003161 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003162}
3163
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003164static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003165 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003166 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003167 const CXIdxObjCCategoryDeclInfo *CatInfo;
3168 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003169 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003170 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003171 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003172 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003173 index_data = (IndexData *)client_data;
3174
3175 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3176 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003177 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003178 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003179 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003180 printf(" | semantic-container: ");
3181 printCXIndexContainer(info->semanticContainer);
3182 printf(" | lexical-container: ");
3183 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003184 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003185 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003186 if (info->flags & CXIdxDeclFlag_Skipped) {
3187 assert(!info->isContainer);
3188 printf(" | isContainer: skipped");
3189 } else {
3190 printf(" | isContainer: %d", info->isContainer);
3191 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003192 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003193
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003194 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003195 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003196 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003197 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003198 printf("\n");
3199 }
3200
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003201 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3202 const char *kindName = 0;
3203 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3204 switch (K) {
3205 case CXIdxObjCContainer_ForwardRef:
3206 kindName = "forward-ref"; break;
3207 case CXIdxObjCContainer_Interface:
3208 kindName = "interface"; break;
3209 case CXIdxObjCContainer_Implementation:
3210 kindName = "implementation"; break;
3211 }
3212 printCheck(index_data);
3213 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3214 }
3215
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003216 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003217 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3218 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003219 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003220 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003221 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003222 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003223 printf("\n");
3224 }
3225
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003226 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3227 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003228 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003229 printf("\n");
3230 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003231 }
3232
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003233 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3234 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003235 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003236
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003237 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3238 if (PropInfo->getter) {
3239 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3240 printf("\n");
3241 }
3242 if (PropInfo->setter) {
3243 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3244 printf("\n");
3245 }
3246 }
3247
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003248 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3249 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3250 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3251 printf("\n");
3252 }
3253 }
3254
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003255 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003256 clang_index_setClientContainer(
3257 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003258 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003259}
3260
3261static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003262 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003263 printEntityInfo("[indexEntityReference]", client_data,
3264 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003265 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003266 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003267 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003268 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003269 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003270 printf(" | container: ");
3271 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003272 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003273 switch (info->kind) {
3274 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003275 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003276 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003277 printf("\n");
3278}
3279
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003280static int index_abortQuery(CXClientData client_data, void *reserved) {
3281 IndexData *index_data;
3282 index_data = (IndexData *)client_data;
3283 return index_data->abort;
3284}
3285
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003286static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003287 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003288 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003289 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003290 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003291 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003292 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003293 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003294 index_indexEntityReference
3295};
3296
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003297static unsigned getIndexOptions(void) {
3298 unsigned index_opts;
3299 index_opts = 0;
3300 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3301 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3302 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3303 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003304 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3305 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003306
3307 return index_opts;
3308}
3309
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003310static int index_compile_args(int num_args, const char **args,
3311 CXIndexAction idxAction,
3312 ImportedASTFilesData *importedASTs,
3313 const char *check_prefix) {
3314 IndexData index_data;
3315 unsigned index_opts;
3316 int result;
3317
3318 if (num_args == 0) {
3319 fprintf(stderr, "no compiler arguments\n");
3320 return -1;
3321 }
3322
3323 index_data.check_prefix = check_prefix;
3324 index_data.first_check_printed = 0;
3325 index_data.fail_for_error = 0;
3326 index_data.abort = 0;
3327 index_data.main_filename = "";
3328 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003329 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003330 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003331
3332 index_opts = getIndexOptions();
3333 result = clang_indexSourceFile(idxAction, &index_data,
3334 &IndexCB,sizeof(IndexCB), index_opts,
3335 0, args, num_args, 0, 0, 0,
3336 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003337 if (result != CXError_Success)
3338 describeLibclangFailure(result);
3339
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003340 if (index_data.fail_for_error)
3341 result = -1;
3342
Nico Weberdf686022014-05-07 21:09:42 +00003343 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003344 return result;
3345}
3346
3347static int index_ast_file(const char *ast_file,
3348 CXIndex Idx,
3349 CXIndexAction idxAction,
3350 ImportedASTFilesData *importedASTs,
3351 const char *check_prefix) {
3352 CXTranslationUnit TU;
3353 IndexData index_data;
3354 unsigned index_opts;
3355 int result;
3356
3357 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3358 return -1;
3359
3360 index_data.check_prefix = check_prefix;
3361 index_data.first_check_printed = 0;
3362 index_data.fail_for_error = 0;
3363 index_data.abort = 0;
3364 index_data.main_filename = "";
3365 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003366 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003367 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003368
3369 index_opts = getIndexOptions();
3370 result = clang_indexTranslationUnit(idxAction, &index_data,
3371 &IndexCB,sizeof(IndexCB),
3372 index_opts, TU);
3373 if (index_data.fail_for_error)
3374 result = -1;
3375
3376 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003377 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003378 return result;
3379}
3380
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003381static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003382 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003383 CXIndex Idx;
3384 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003385 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003386 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003387
3388 check_prefix = 0;
3389 if (argc > 0) {
3390 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3391 check_prefix = argv[0] + strlen("-check-prefix=");
3392 ++argv;
3393 --argc;
3394 }
3395 }
3396
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003397 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003398 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003399 fprintf(stderr, "Could not create Index\n");
3400 return 1;
3401 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003402 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003403 importedASTs = 0;
3404 if (full)
3405 importedASTs = importedASTs_create();
3406
3407 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3408 if (result != 0)
3409 goto finished;
3410
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003411 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003412 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003413 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3414 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3415 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003416 }
3417 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003418
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003419finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003420 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003421 clang_IndexAction_dispose(idxAction);
3422 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003423 return result;
3424}
3425
3426static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003427 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003428 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003429 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003430 int result;
3431
3432 check_prefix = 0;
3433 if (argc > 0) {
3434 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3435 check_prefix = argv[0] + strlen("-check-prefix=");
3436 ++argv;
3437 --argc;
3438 }
3439 }
3440
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003441 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003442 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003443 fprintf(stderr, "Could not create Index\n");
3444 return 1;
3445 }
3446 idxAction = clang_IndexAction_create(Idx);
3447
3448 result = index_ast_file(argv[0], Idx, idxAction,
3449 /*importedASTs=*/0, check_prefix);
3450
3451 clang_IndexAction_dispose(idxAction);
3452 clang_disposeIndex(Idx);
3453 return result;
3454}
3455
3456static int index_compile_db(int argc, const char **argv) {
3457 const char *check_prefix;
3458 CXIndex Idx;
3459 CXIndexAction idxAction;
3460 int errorCode = 0;
3461
3462 check_prefix = 0;
3463 if (argc > 0) {
3464 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3465 check_prefix = argv[0] + strlen("-check-prefix=");
3466 ++argv;
3467 --argc;
3468 }
3469 }
3470
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003471 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003472 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003473 return -1;
3474 }
3475
3476 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003477 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003478 fprintf(stderr, "Could not create Index\n");
3479 return 1;
3480 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003481 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003482
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003483 {
3484 const char *database = argv[0];
3485 CXCompilationDatabase db = 0;
3486 CXCompileCommands CCmds = 0;
3487 CXCompileCommand CCmd;
3488 CXCompilationDatabase_Error ec;
3489 CXString wd;
3490#define MAX_COMPILE_ARGS 512
3491 CXString cxargs[MAX_COMPILE_ARGS];
3492 const char *args[MAX_COMPILE_ARGS];
3493 char *tmp;
3494 unsigned len;
3495 char *buildDir;
3496 int i, a, numCmds, numArgs;
3497
3498 len = strlen(database);
3499 tmp = (char *) malloc(len+1);
3500 memcpy(tmp, database, len+1);
3501 buildDir = dirname(tmp);
3502
3503 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3504
3505 if (db) {
3506
3507 if (ec!=CXCompilationDatabase_NoError) {
3508 printf("unexpected error %d code while loading compilation database\n", ec);
3509 errorCode = -1;
3510 goto cdb_end;
3511 }
3512
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003513 if (chdir(buildDir) != 0) {
3514 printf("Could not chdir to %s\n", buildDir);
3515 errorCode = -1;
3516 goto cdb_end;
3517 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003518
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003519 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003520 if (!CCmds) {
3521 printf("compilation db is empty\n");
3522 errorCode = -1;
3523 goto cdb_end;
3524 }
3525
3526 numCmds = clang_CompileCommands_getSize(CCmds);
3527
3528 if (numCmds==0) {
3529 fprintf(stderr, "should not get an empty compileCommand set\n");
3530 errorCode = -1;
3531 goto cdb_end;
3532 }
3533
3534 for (i=0; i<numCmds && errorCode == 0; ++i) {
3535 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3536
3537 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003538 if (chdir(clang_getCString(wd)) != 0) {
3539 printf("Could not chdir to %s\n", clang_getCString(wd));
3540 errorCode = -1;
3541 goto cdb_end;
3542 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003543 clang_disposeString(wd);
3544
3545 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3546 if (numArgs > MAX_COMPILE_ARGS){
3547 fprintf(stderr, "got more compile arguments than maximum\n");
3548 errorCode = -1;
3549 goto cdb_end;
3550 }
3551 for (a=0; a<numArgs; ++a) {
3552 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3553 args[a] = clang_getCString(cxargs[a]);
3554 }
3555
3556 errorCode = index_compile_args(numArgs, args, idxAction,
3557 /*importedASTs=*/0, check_prefix);
3558
3559 for (a=0; a<numArgs; ++a)
3560 clang_disposeString(cxargs[a]);
3561 }
3562 } else {
3563 printf("database loading failed with error code %d.\n", ec);
3564 errorCode = -1;
3565 }
3566
3567 cdb_end:
3568 clang_CompileCommands_dispose(CCmds);
3569 clang_CompilationDatabase_dispose(db);
3570 free(tmp);
3571
3572 }
3573
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003574 clang_IndexAction_dispose(idxAction);
3575 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003576 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003577}
3578
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003579int perform_token_annotation(int argc, const char **argv) {
3580 const char *input = argv[1];
3581 char *filename = 0;
3582 unsigned line, second_line;
3583 unsigned column, second_column;
3584 CXIndex CIdx;
3585 CXTranslationUnit TU = 0;
3586 int errorCode;
3587 struct CXUnsavedFile *unsaved_files = 0;
3588 int num_unsaved_files = 0;
3589 CXToken *tokens;
3590 unsigned num_tokens;
3591 CXSourceRange range;
3592 CXSourceLocation startLoc, endLoc;
3593 CXFile file = 0;
3594 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003595 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003596 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003597 unsigned i;
3598
3599 input += strlen("-test-annotate-tokens=");
3600 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3601 &second_line, &second_column)))
3602 return errorCode;
3603
Richard Smith1ea42eb2012-07-05 08:20:49 +00003604 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3605 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003606 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003607 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003608
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003609 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003610 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3611 argv + num_unsaved_files + 2,
3612 argc - num_unsaved_files - 3,
3613 unsaved_files,
3614 num_unsaved_files,
3615 getDefaultParsingOptions(), &TU);
3616 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003617 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003618 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003619 clang_disposeIndex(CIdx);
3620 free(filename);
3621 free_remapped_files(unsaved_files, num_unsaved_files);
3622 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003623 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003624 errorCode = 0;
3625
Richard Smith1ea42eb2012-07-05 08:20:49 +00003626 if (checkForErrors(TU) != 0) {
3627 errorCode = -1;
3628 goto teardown;
3629 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003630
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003631 if (getenv("CINDEXTEST_EDITING")) {
3632 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003633 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3634 clang_defaultReparseOptions(TU));
3635 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003636 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003637 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003638 errorCode = -1;
3639 goto teardown;
3640 }
3641 }
3642 }
3643
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003644 if (checkForErrors(TU) != 0) {
3645 errorCode = -1;
3646 goto teardown;
3647 }
3648
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003649 file = clang_getFile(TU, filename);
3650 if (!file) {
3651 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3652 errorCode = -1;
3653 goto teardown;
3654 }
3655
3656 startLoc = clang_getLocation(TU, file, line, column);
3657 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003658 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003659 column);
3660 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003661 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003662 }
3663
3664 endLoc = clang_getLocation(TU, file, second_line, second_column);
3665 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003666 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003667 second_line, second_column);
3668 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003669 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003670 }
3671
3672 range = clang_getRange(startLoc, endLoc);
3673 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003674
3675 if (checkForErrors(TU) != 0) {
3676 errorCode = -1;
3677 goto teardown;
3678 }
3679
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003680 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3681 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003682
3683 if (checkForErrors(TU) != 0) {
3684 errorCode = -1;
3685 goto teardown;
3686 }
3687
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003688 skipped_ranges = clang_getSkippedRanges(TU, file);
3689 for (i = 0; i != skipped_ranges->count; ++i) {
3690 unsigned start_line, start_column, end_line, end_column;
3691 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3692 0, &start_line, &start_column, 0);
3693 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3694 0, &end_line, &end_column, 0);
3695 printf("Skipping: ");
3696 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3697 printf("\n");
3698 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003699 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003700
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003701 for (i = 0; i != num_tokens; ++i) {
3702 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003703 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3704 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003705 unsigned start_line, start_column, end_line, end_column;
3706
3707 switch (clang_getTokenKind(tokens[i])) {
3708 case CXToken_Punctuation: kind = "Punctuation"; break;
3709 case CXToken_Keyword: kind = "Keyword"; break;
3710 case CXToken_Identifier: kind = "Identifier"; break;
3711 case CXToken_Literal: kind = "Literal"; break;
3712 case CXToken_Comment: kind = "Comment"; break;
3713 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003714 clang_getSpellingLocation(clang_getRangeStart(extent),
3715 0, &start_line, &start_column, 0);
3716 clang_getSpellingLocation(clang_getRangeEnd(extent),
3717 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003718 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003719 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003720 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003721 if (!clang_isInvalid(cursors[i].kind)) {
3722 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003723 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003724 }
3725 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003726 }
3727 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003728 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003729
3730 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003731 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003732 clang_disposeTranslationUnit(TU);
3733 clang_disposeIndex(CIdx);
3734 free(filename);
3735 free_remapped_files(unsaved_files, num_unsaved_files);
3736 return errorCode;
3737}
3738
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003739static int
3740perform_test_compilation_db(const char *database, int argc, const char **argv) {
3741 CXCompilationDatabase db;
3742 CXCompileCommands CCmds;
3743 CXCompileCommand CCmd;
3744 CXCompilationDatabase_Error ec;
3745 CXString wd;
3746 CXString arg;
3747 int errorCode = 0;
3748 char *tmp;
3749 unsigned len;
3750 char *buildDir;
3751 int i, j, a, numCmds, numArgs;
3752
3753 len = strlen(database);
3754 tmp = (char *) malloc(len+1);
3755 memcpy(tmp, database, len+1);
3756 buildDir = dirname(tmp);
3757
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003758 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003759
3760 if (db) {
3761
3762 if (ec!=CXCompilationDatabase_NoError) {
3763 printf("unexpected error %d code while loading compilation database\n", ec);
3764 errorCode = -1;
3765 goto cdb_end;
3766 }
3767
3768 for (i=0; i<argc && errorCode==0; ) {
3769 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003770 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003771
3772 if (!CCmds) {
3773 printf("file %s not found in compilation db\n", argv[i+1]);
3774 errorCode = -1;
3775 break;
3776 }
3777
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003778 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003779
3780 if (numCmds==0) {
3781 fprintf(stderr, "should not get an empty compileCommand set for file"
3782 " '%s'\n", argv[i+1]);
3783 errorCode = -1;
3784 break;
3785 }
3786
3787 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003788 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003789
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003790 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003791 printf("workdir:'%s'", clang_getCString(wd));
3792 clang_disposeString(wd);
3793
3794 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003795 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003796 for (a=0; a<numArgs; ++a) {
3797 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003798 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003799 printf("%s", clang_getCString(arg));
3800 clang_disposeString(arg);
3801 }
3802 printf("'\n");
3803 }
3804
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003805 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003806
3807 i += 2;
3808 }
3809 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003810 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003811 } else {
3812 printf("database loading failed with error code %d.\n", ec);
3813 errorCode = -1;
3814 }
3815
3816cdb_end:
3817 free(tmp);
3818
3819 return errorCode;
3820}
3821
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003822/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003823/* USR printing. */
3824/******************************************************************************/
3825
3826static int insufficient_usr(const char *kind, const char *usage) {
3827 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3828 return 1;
3829}
3830
3831static unsigned isUSR(const char *s) {
3832 return s[0] == 'c' && s[1] == ':';
3833}
3834
3835static int not_usr(const char *s, const char *arg) {
3836 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3837 return 1;
3838}
3839
3840static void print_usr(CXString usr) {
3841 const char *s = clang_getCString(usr);
3842 printf("%s\n", s);
3843 clang_disposeString(usr);
3844}
3845
3846static void display_usrs() {
3847 fprintf(stderr, "-print-usrs options:\n"
3848 " ObjCCategory <class name> <category name>\n"
3849 " ObjCClass <class name>\n"
3850 " ObjCIvar <ivar name> <class USR>\n"
3851 " ObjCMethod <selector> [0=class method|1=instance method] "
3852 "<class USR>\n"
3853 " ObjCProperty <property name> <class USR>\n"
3854 " ObjCProtocol <protocol name>\n");
3855}
3856
3857int print_usrs(const char **I, const char **E) {
3858 while (I != E) {
3859 const char *kind = *I;
3860 unsigned len = strlen(kind);
3861 switch (len) {
3862 case 8:
3863 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3864 if (I + 2 >= E)
3865 return insufficient_usr(kind, "<ivar name> <class USR>");
3866 if (!isUSR(I[2]))
3867 return not_usr("<class USR>", I[2]);
3868 else {
3869 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003870 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003871 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003872 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3873 }
3874
3875 I += 3;
3876 continue;
3877 }
3878 break;
3879 case 9:
3880 if (memcmp(kind, "ObjCClass", 9) == 0) {
3881 if (I + 1 >= E)
3882 return insufficient_usr(kind, "<class name>");
3883 print_usr(clang_constructUSR_ObjCClass(I[1]));
3884 I += 2;
3885 continue;
3886 }
3887 break;
3888 case 10:
3889 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3890 if (I + 3 >= E)
3891 return insufficient_usr(kind, "<method selector> "
3892 "[0=class method|1=instance method] <class USR>");
3893 if (!isUSR(I[3]))
3894 return not_usr("<class USR>", I[3]);
3895 else {
3896 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003897 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003898 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003899 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3900 }
3901 I += 4;
3902 continue;
3903 }
3904 break;
3905 case 12:
3906 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3907 if (I + 2 >= E)
3908 return insufficient_usr(kind, "<class name> <category name>");
3909 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3910 I += 3;
3911 continue;
3912 }
3913 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3914 if (I + 1 >= E)
3915 return insufficient_usr(kind, "<protocol name>");
3916 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3917 I += 2;
3918 continue;
3919 }
3920 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3921 if (I + 2 >= E)
3922 return insufficient_usr(kind, "<property name> <class USR>");
3923 if (!isUSR(I[2]))
3924 return not_usr("<class USR>", I[2]);
3925 else {
3926 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003927 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003928 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003929 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3930 }
3931 I += 3;
3932 continue;
3933 }
3934 break;
3935 default:
3936 break;
3937 }
3938 break;
3939 }
3940
3941 if (I != E) {
3942 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3943 display_usrs();
3944 return 1;
3945 }
3946 return 0;
3947}
3948
3949int print_usrs_file(const char *file_name) {
3950 char line[2048];
3951 const char *args[128];
3952 unsigned numChars = 0;
3953
3954 FILE *fp = fopen(file_name, "r");
3955 if (!fp) {
3956 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3957 return 1;
3958 }
3959
3960 /* This code is not really all that safe, but it works fine for testing. */
3961 while (!feof(fp)) {
3962 char c = fgetc(fp);
3963 if (c == '\n') {
3964 unsigned i = 0;
3965 const char *s = 0;
3966
3967 if (numChars == 0)
3968 continue;
3969
3970 line[numChars] = '\0';
3971 numChars = 0;
3972
3973 if (line[0] == '/' && line[1] == '/')
3974 continue;
3975
3976 s = strtok(line, " ");
3977 while (s) {
3978 args[i] = s;
3979 ++i;
3980 s = strtok(0, " ");
3981 }
3982 if (print_usrs(&args[0], &args[i]))
3983 return 1;
3984 }
3985 else
3986 line[numChars++] = c;
3987 }
3988
3989 fclose(fp);
3990 return 0;
3991}
3992
3993/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003994/* Command line processing. */
3995/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003996int write_pch_file(const char *filename, int argc, const char *argv[]) {
3997 CXIndex Idx;
3998 CXTranslationUnit TU;
3999 struct CXUnsavedFile *unsaved_files = 0;
4000 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004001 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00004002 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00004003
Stefanus Du Toitb3318502013-03-01 21:41:22 +00004004 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00004005
4006 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
4007 clang_disposeIndex(Idx);
4008 return -1;
4009 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004010
4011 Err = clang_parseTranslationUnit2(
4012 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
4013 unsaved_files, num_unsaved_files,
4014 CXTranslationUnit_Incomplete |
4015 CXTranslationUnit_DetailedPreprocessingRecord |
4016 CXTranslationUnit_ForSerialization,
4017 &TU);
4018 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00004019 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004020 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00004021 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004022 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00004023 clang_disposeIndex(Idx);
4024 return 1;
4025 }
4026
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004027 switch (clang_saveTranslationUnit(TU, filename,
4028 clang_defaultSaveOptions(TU))) {
4029 case CXSaveError_None:
4030 break;
4031
4032 case CXSaveError_TranslationErrors:
4033 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4034 filename);
4035 result = 2;
4036 break;
4037
4038 case CXSaveError_InvalidTU:
4039 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4040 filename);
4041 result = 3;
4042 break;
4043
4044 case CXSaveError_Unknown:
4045 default:
4046 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4047 result = 1;
4048 break;
4049 }
4050
Douglas Gregore9386682010-08-13 05:36:37 +00004051 clang_disposeTranslationUnit(TU);
4052 free_remapped_files(unsaved_files, num_unsaved_files);
4053 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004054 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004055}
4056
4057/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004058/* Serialized diagnostics. */
4059/******************************************************************************/
4060
4061static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4062 switch (error) {
4063 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4064 case CXLoadDiag_None: break;
4065 case CXLoadDiag_Unknown: return "Unknown";
4066 case CXLoadDiag_InvalidFile: return "Invalid File";
4067 }
4068 return "None";
4069}
4070
4071static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4072 switch (severity) {
4073 case CXDiagnostic_Note: return "note";
4074 case CXDiagnostic_Error: return "error";
4075 case CXDiagnostic_Fatal: return "fatal";
4076 case CXDiagnostic_Ignored: return "ignored";
4077 case CXDiagnostic_Warning: return "warning";
4078 }
4079 return "unknown";
4080}
4081
4082static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004083 if (indent == 0)
4084 return;
4085 fprintf(stderr, "+");
4086 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004087 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004088 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004089 --indent;
4090 }
4091}
4092
4093static void printLocation(CXSourceLocation L) {
4094 CXFile File;
4095 CXString FileName;
4096 unsigned line, column, offset;
4097
4098 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4099 FileName = clang_getFileName(File);
4100
4101 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4102 clang_disposeString(FileName);
4103}
4104
4105static void printRanges(CXDiagnostic D, unsigned indent) {
4106 unsigned i, n = clang_getDiagnosticNumRanges(D);
4107
4108 for (i = 0; i < n; ++i) {
4109 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004110 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004111 Start = clang_getRangeStart(SR);
4112 End = clang_getRangeEnd(SR);
4113
4114 printIndent(indent);
4115 fprintf(stderr, "Range: ");
4116 printLocation(Start);
4117 fprintf(stderr, " ");
4118 printLocation(End);
4119 fprintf(stderr, "\n");
4120 }
4121}
4122
4123static void printFixIts(CXDiagnostic D, unsigned indent) {
4124 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004125 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004126 for (i = 0 ; i < n; ++i) {
4127 CXSourceRange ReplacementRange;
4128 CXString text;
4129 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4130
4131 printIndent(indent);
4132 fprintf(stderr, "FIXIT: (");
4133 printLocation(clang_getRangeStart(ReplacementRange));
4134 fprintf(stderr, " - ");
4135 printLocation(clang_getRangeEnd(ReplacementRange));
4136 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4137 clang_disposeString(text);
4138 }
4139}
4140
4141static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004142 unsigned i, n;
4143
Ted Kremenekd010ba42011-11-10 08:43:12 +00004144 if (!Diags)
4145 return;
4146
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004147 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004148 for (i = 0; i < n; ++i) {
4149 CXSourceLocation DiagLoc;
4150 CXDiagnostic D;
4151 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004152 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004153 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004154 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004155
4156 D = clang_getDiagnosticInSet(Diags, i);
4157 DiagLoc = clang_getDiagnosticLocation(D);
4158 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4159 FileName = clang_getFileName(File);
4160 DiagSpelling = clang_getDiagnosticSpelling(D);
4161
4162 printIndent(indent);
4163
4164 fprintf(stderr, "%s:%d:%d: %s: %s",
4165 clang_getCString(FileName),
4166 line,
4167 column,
4168 getSeverityString(clang_getDiagnosticSeverity(D)),
4169 clang_getCString(DiagSpelling));
4170
4171 DiagOption = clang_getDiagnosticOption(D, 0);
4172 DiagOptionStr = clang_getCString(DiagOption);
4173 if (DiagOptionStr) {
4174 fprintf(stderr, " [%s]", DiagOptionStr);
4175 }
4176
Ted Kremenek26a6d492012-04-12 00:03:31 +00004177 DiagCat = clang_getDiagnosticCategoryText(D);
4178 DiagCatStr = clang_getCString(DiagCat);
4179 if (DiagCatStr) {
4180 fprintf(stderr, " [%s]", DiagCatStr);
4181 }
4182
Ted Kremenekd010ba42011-11-10 08:43:12 +00004183 fprintf(stderr, "\n");
4184
4185 printRanges(D, indent);
4186 printFixIts(D, indent);
4187
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004188 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004189 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4190
4191 clang_disposeString(FileName);
4192 clang_disposeString(DiagSpelling);
4193 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004194 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004195 }
4196}
4197
4198static int read_diagnostics(const char *filename) {
4199 enum CXLoadDiag_Error error;
4200 CXString errorString;
4201 CXDiagnosticSet Diags = 0;
4202
4203 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4204 if (!Diags) {
4205 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4206 getDiagnosticCodeStr(error),
4207 clang_getCString(errorString));
4208 clang_disposeString(errorString);
4209 return 1;
4210 }
4211
4212 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004213 fprintf(stderr, "Number of diagnostics: %d\n",
4214 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004215 clang_disposeDiagnosticSet(Diags);
4216 return 0;
4217}
4218
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004219static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004220 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004221 return 0;
4222}
4223
Ted Kremenekd010ba42011-11-10 08:43:12 +00004224/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004225/* Command line processing. */
4226/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004227
Douglas Gregor720d0052010-01-20 21:32:04 +00004228static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004229 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004230 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004231 if (strcmp(s, "-usrs") == 0)
4232 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004233 if (strncmp(s, "-memory-usage", 13) == 0)
4234 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004235 return NULL;
4236}
4237
Ted Kremenekef3339b2009-11-17 18:09:14 +00004238static void print_usage(void) {
4239 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004240 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004241 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004242 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004243 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4244 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004245 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4246 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004247 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004248 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004249 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004250 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004251 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004252 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004253 "[FileCheck prefix]\n");
4254 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004255 " c-index-test -test-load-tu <AST file> <symbol filter> "
4256 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004257 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4258 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004259 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004260 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004261 " c-index-test -test-load-source-memory-usage "
4262 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004263 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4264 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004265 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004266 " c-index-test -test-load-source-usrs-memory-usage "
4267 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004268 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4269 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004270 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004271 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004272 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004273 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004274 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004275 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004276 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004277 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004278 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004279 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004280 " c-index-test -write-pch <file> <compiler arguments>\n");
4281 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004282 " c-index-test -compilation-db [lookup <filename>] database\n");
4283 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004284 " c-index-test -print-build-session-timestamp\n");
4285 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004286 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004287 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004288 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004289 " all - load all symbols, including those from PCH\n"
4290 " local - load all symbols except those in PCH\n"
4291 " category - only load ObjC categories (non-PCH)\n"
4292 " interface - only load ObjC interfaces (non-PCH)\n"
4293 " protocol - only load ObjC protocols (non-PCH)\n"
4294 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004295 " typedef - only load typdefs (non-PCH)\n"
4296 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004297}
4298
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004299/***/
4300
4301int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004302 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004303 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4304 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004305 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004306 return perform_code_completion(argc, argv, 0);
4307 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4308 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004309 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004310 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4311 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4312 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4313 inspect_evaluate_cursor);
4314 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4315 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4316 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004317 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4318 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004319 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4320 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004321 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004322 return index_file(argc - 2, argv + 2, /*full=*/0);
4323 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4324 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004325 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4326 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004327 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4328 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004329 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004330 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004331 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004332 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4333 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004334 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004335 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4336 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4337 if (I) {
4338 int trials = atoi(argv[2]);
4339 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4340 NULL);
4341 }
4342 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004343 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004344 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004345
4346 PostVisitTU postVisit = 0;
4347 if (strstr(argv[1], "-memory-usage"))
4348 postVisit = PrintMemoryUsage;
4349
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004350 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004351 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4352 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004353 }
4354 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004355 return perform_file_scan(argv[2], argv[3],
4356 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004357 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4358 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004359 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4360 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4361 PrintInclusionStack);
4362 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4363 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4364 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004365 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4366 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4367 NULL);
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004368 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4369 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4370 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004371 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004372 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004373 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004374 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4375 return perform_test_load_source(argc - 2, argv + 2, "all",
4376 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004377 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4378 return perform_test_load_source(argc - 2, argv + 2, "all",
4379 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004380 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4381 return perform_test_load_source(argc - 2, argv + 2, "all",
4382 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004383 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4384 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004385 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4386 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004387 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4388 if (argc > 2)
4389 return print_usrs(argv + 2, argv + argc);
4390 else {
4391 display_usrs();
4392 return 1;
4393 }
4394 }
4395 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4396 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004397 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4398 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004399 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4400 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004401 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4402 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004403
Ted Kremenekef3339b2009-11-17 18:09:14 +00004404 print_usage();
4405 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004406}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004407
4408/***/
4409
4410/* We intentionally run in a separate thread to ensure we at least minimal
4411 * testing of a multithreaded environment (for example, having a reduced stack
4412 * size). */
4413
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004414typedef struct thread_info {
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004415 int (*main_func)(int argc, const char **argv);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004416 int argc;
4417 const char **argv;
4418 int result;
4419} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004420void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004421 thread_info *client_data = client_data_v;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004422 client_data->result = client_data->main_func(client_data->argc,
4423 client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004424}
4425
4426static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004427 /* stdout, and surprisingly even stderr, are not always flushed on process
4428 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004429 fflush(stdout);
4430 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004431}
4432
4433int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004434 thread_info client_data;
4435
Reid Klecknere931c062014-06-05 00:13:43 +00004436 atexit(flush_atexit);
4437
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004438#ifdef CLANG_HAVE_LIBXML
4439 LIBXML_TEST_VERSION
4440#endif
4441
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004442 client_data.main_func = cindextest_main;
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004443 client_data.argc = argc;
4444 client_data.argv = argv;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004445
Richard Smithdfed58a2016-06-09 00:53:41 +00004446 if (argc > 1 && strcmp(argv[1], "core") == 0)
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004447 client_data.main_func = indextest_core_main;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004448
4449 if (getenv("CINDEXTEST_NOTHREADS"))
4450 return client_data.main_func(client_data.argc, client_data.argv);
4451
Daniel Dunbar23397c32010-11-04 01:26:31 +00004452 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004453 return client_data.result;
4454}