blob: b2f9120baf98d6bdea3b54b7425d0d398eb28e75 [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
Ted Kremenek1cd27d52009-11-17 18:13:31 +000026/******************************************************************************/
27/* Utility functions. */
28/******************************************************************************/
29
John Thompsonde258b52009-10-27 13:42:56 +000030#ifdef _MSC_VER
31char *basename(const char* path)
32{
33 char* base1 = (char*)strrchr(path, '/');
34 char* base2 = (char*)strrchr(path, '\\');
35 if (base1 && base2)
36 return((base1 > base2) ? base1 + 1 : base2 + 1);
37 else if (base1)
38 return(base1 + 1);
39 else if (base2)
40 return(base2 + 1);
41
42 return((char*)path);
43}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000044char *dirname(char* path)
45{
46 char* base1 = (char*)strrchr(path, '/');
47 char* base2 = (char*)strrchr(path, '\\');
48 if (base1 && base2)
49 if (base1 > base2)
50 *base1 = 0;
51 else
52 *base2 = 0;
53 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000054 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000055 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000056 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000057
58 return path;
59}
John Thompsonde258b52009-10-27 13:42:56 +000060#else
Steve Naroffa7753c42009-09-24 20:03:06 +000061extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000062extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000063#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000064
Douglas Gregorf2430ba2010-07-25 17:39:21 +000065/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000066static unsigned getDefaultParsingOptions() {
67 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
68
69 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000070 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000071 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
72 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000073 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
74 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000075 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
76 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000077 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
78 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000079 if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
80 options |= CXTranslationUnit_CreatePreambleOnFirstParse;
81
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000082 return options;
83}
84
Patrik Hagglund55701d22014-02-17 11:54:08 +000085/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000086static int checkForErrors(CXTranslationUnit TU);
87
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000088static void describeLibclangFailure(enum CXErrorCode Err) {
89 switch (Err) {
90 case CXError_Success:
91 fprintf(stderr, "Success\n");
92 return;
93
94 case CXError_Failure:
95 fprintf(stderr, "Failure (no details available)\n");
96 return;
97
98 case CXError_Crashed:
99 fprintf(stderr, "Failure: libclang crashed\n");
100 return;
101
102 case CXError_InvalidArguments:
103 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
104 return;
105
106 case CXError_ASTReadError:
107 fprintf(stderr, "Failure: AST deserialization error occurred\n");
108 return;
109 }
110}
111
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000112static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
113 unsigned end_line, unsigned end_column) {
114 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000115 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000116}
117
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000118static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
119 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000120 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
121 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000122 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000123 describeLibclangFailure(Err);
124 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000125 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000126 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000127 return 1;
128}
129
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000130void free_remapped_files(struct CXUnsavedFile *unsaved_files,
131 int num_unsaved_files) {
132 int i;
133 for (i = 0; i != num_unsaved_files; ++i) {
134 free((char *)unsaved_files[i].Filename);
135 free((char *)unsaved_files[i].Contents);
136 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000137 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000138}
139
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000140static int parse_remapped_files_with_opt(const char *opt_name,
141 int argc, const char **argv,
142 int start_arg,
143 struct CXUnsavedFile **unsaved_files,
144 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000145 int i;
146 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000147 int prefix_len = strlen(opt_name);
148 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000149 *unsaved_files = 0;
150 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000151
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000152 /* Count the number of remapped files. */
153 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000154 if (strncmp(argv[arg], opt_name, prefix_len))
155 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000156
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000157 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
158 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000159 ++*num_unsaved_files;
160 }
Ted Kremenek29004672010-02-17 00:41:32 +0000161
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000162 if (*num_unsaved_files == 0)
163 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000164
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000165 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000166 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
167 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000168 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000170 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000171 int filename_len;
172 char *filename;
173 char *contents;
174 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000175 const char *sep = strchr(arg_string, ',');
176 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000177 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000178 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000179 free_remapped_files(*unsaved_files, i);
180 *unsaved_files = 0;
181 *num_unsaved_files = 0;
182 return -1;
183 }
Ted Kremenek29004672010-02-17 00:41:32 +0000184
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000185 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000186 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000187 if (!to_file) {
188 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000189 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000190 free_remapped_files(*unsaved_files, i);
191 *unsaved_files = 0;
192 *num_unsaved_files = 0;
193 return -1;
194 }
Ted Kremenek29004672010-02-17 00:41:32 +0000195
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000196 /* Determine the length of the file we're remapping to. */
197 fseek(to_file, 0, SEEK_END);
198 unsaved->Length = ftell(to_file);
199 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000200
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000201 /* Read the contents of the file we're remapping to. */
202 contents = (char *)malloc(unsaved->Length + 1);
203 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
204 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000205 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000206 fclose(to_file);
207 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000208 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000209 *unsaved_files = 0;
210 *num_unsaved_files = 0;
211 return -1;
212 }
213 contents[unsaved->Length] = 0;
214 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000215
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000216 /* Close the file. */
217 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000218
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000219 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000220 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000221 filename = (char *)malloc(filename_len + 1);
222 memcpy(filename, arg_string, filename_len);
223 filename[filename_len] = 0;
224 unsaved->Filename = filename;
225 }
Ted Kremenek29004672010-02-17 00:41:32 +0000226
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000227 return 0;
228}
229
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000230static int parse_remapped_files(int argc, const char **argv, int start_arg,
231 struct CXUnsavedFile **unsaved_files,
232 int *num_unsaved_files) {
233 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
234 unsaved_files, num_unsaved_files);
235}
236
237static int parse_remapped_files_with_try(int try_idx,
238 int argc, const char **argv,
239 int start_arg,
240 struct CXUnsavedFile **unsaved_files,
241 int *num_unsaved_files) {
242 struct CXUnsavedFile *unsaved_files_no_try_idx;
243 int num_unsaved_files_no_try_idx;
244 struct CXUnsavedFile *unsaved_files_try_idx;
245 int num_unsaved_files_try_idx;
246 int ret;
247 char opt_name[32];
248
249 ret = parse_remapped_files(argc, argv, start_arg,
250 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
251 if (ret)
252 return ret;
253
254 sprintf(opt_name, "-remap-file-%d=", try_idx);
255 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
256 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
257 if (ret)
258 return ret;
259
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000260 if (num_unsaved_files_no_try_idx == 0) {
261 *unsaved_files = unsaved_files_try_idx;
262 *num_unsaved_files = num_unsaved_files_try_idx;
263 return 0;
264 }
265 if (num_unsaved_files_try_idx == 0) {
266 *unsaved_files = unsaved_files_no_try_idx;
267 *num_unsaved_files = num_unsaved_files_no_try_idx;
268 return 0;
269 }
270
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000271 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
272 *unsaved_files
273 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
274 sizeof(struct CXUnsavedFile) *
275 *num_unsaved_files);
276 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
277 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
278 num_unsaved_files_try_idx);
279 free(unsaved_files_try_idx);
280 return 0;
281}
282
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000283static const char *parse_comments_schema(int argc, const char **argv) {
284 const char *CommentsSchemaArg = "-comments-xml-schema=";
285 const char *CommentSchemaFile = NULL;
286
287 if (argc == 0)
288 return CommentSchemaFile;
289
290 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
291 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
292
293 return CommentSchemaFile;
294}
295
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000296/******************************************************************************/
297/* Pretty-printing. */
298/******************************************************************************/
299
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000300static const char *FileCheckPrefix = "CHECK";
301
302static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000303 if (CStr != NULL && CStr[0] != '\0') {
304 for ( ; *CStr; ++CStr) {
305 const char C = *CStr;
306 switch (C) {
307 case '\n': printf("\\n"); break;
308 case '\r': printf("\\r"); break;
309 case '\t': printf("\\t"); break;
310 case '\v': printf("\\v"); break;
311 case '\f': printf("\\f"); break;
312 default: putchar(C); break;
313 }
314 }
315 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000316}
317
318static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
319 printf(" %s=[", Prefix);
320 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000321 printf("]");
322}
323
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000324static void PrintCXStringAndDispose(CXString Str) {
325 PrintCString(clang_getCString(Str));
326 clang_disposeString(Str);
327}
328
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000329static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
330 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
331}
332
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000333static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
334 CXString Str) {
335 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
336 clang_disposeString(Str);
337}
338
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000339static void PrintRange(CXSourceRange R, const char *str) {
340 CXFile begin_file, end_file;
341 unsigned begin_line, begin_column, end_line, end_column;
342
343 clang_getSpellingLocation(clang_getRangeStart(R),
344 &begin_file, &begin_line, &begin_column, 0);
345 clang_getSpellingLocation(clang_getRangeEnd(R),
346 &end_file, &end_line, &end_column, 0);
347 if (!begin_file || !end_file)
348 return;
349
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000350 if (str)
351 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000352 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
353}
354
Douglas Gregor97c75712010-10-02 22:49:11 +0000355int want_display_name = 0;
356
Douglas Gregord6225d32012-05-08 00:14:45 +0000357static void printVersion(const char *Prefix, CXVersion Version) {
358 if (Version.Major < 0)
359 return;
360 printf("%s%d", Prefix, Version.Major);
361
362 if (Version.Minor < 0)
363 return;
364 printf(".%d", Version.Minor);
365
366 if (Version.Subminor < 0)
367 return;
368 printf(".%d", Version.Subminor);
369}
370
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000371struct CommentASTDumpingContext {
372 int IndentLevel;
373};
374
375static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
376 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000377 unsigned i;
378 unsigned e;
379 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
380
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000381 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000382 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000383 printf(" ");
384
385 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000386 switch (Kind) {
387 case CXComment_Null:
388 printf("CXComment_Null");
389 break;
390 case CXComment_Text:
391 printf("CXComment_Text");
392 PrintCXStringWithPrefixAndDispose("Text",
393 clang_TextComment_getText(Comment));
394 if (clang_Comment_isWhitespace(Comment))
395 printf(" IsWhitespace");
396 if (clang_InlineContentComment_hasTrailingNewline(Comment))
397 printf(" HasTrailingNewline");
398 break;
399 case CXComment_InlineCommand:
400 printf("CXComment_InlineCommand");
401 PrintCXStringWithPrefixAndDispose(
402 "CommandName",
403 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000404 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
405 case CXCommentInlineCommandRenderKind_Normal:
406 printf(" RenderNormal");
407 break;
408 case CXCommentInlineCommandRenderKind_Bold:
409 printf(" RenderBold");
410 break;
411 case CXCommentInlineCommandRenderKind_Monospaced:
412 printf(" RenderMonospaced");
413 break;
414 case CXCommentInlineCommandRenderKind_Emphasized:
415 printf(" RenderEmphasized");
416 break;
417 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000418 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000419 i != e; ++i) {
420 printf(" Arg[%u]=", i);
421 PrintCXStringAndDispose(
422 clang_InlineCommandComment_getArgText(Comment, i));
423 }
424 if (clang_InlineContentComment_hasTrailingNewline(Comment))
425 printf(" HasTrailingNewline");
426 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000427 case CXComment_HTMLStartTag: {
428 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000429 printf("CXComment_HTMLStartTag");
430 PrintCXStringWithPrefixAndDispose(
431 "Name",
432 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000433 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000434 if (NumAttrs != 0) {
435 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000436 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000437 printf(" ");
438 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
439 printf("=");
440 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
441 }
442 }
443 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
444 printf(" SelfClosing");
445 if (clang_InlineContentComment_hasTrailingNewline(Comment))
446 printf(" HasTrailingNewline");
447 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000448 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000449 case CXComment_HTMLEndTag:
450 printf("CXComment_HTMLEndTag");
451 PrintCXStringWithPrefixAndDispose(
452 "Name",
453 clang_HTMLTagComment_getTagName(Comment));
454 if (clang_InlineContentComment_hasTrailingNewline(Comment))
455 printf(" HasTrailingNewline");
456 break;
457 case CXComment_Paragraph:
458 printf("CXComment_Paragraph");
459 if (clang_Comment_isWhitespace(Comment))
460 printf(" IsWhitespace");
461 break;
462 case CXComment_BlockCommand:
463 printf("CXComment_BlockCommand");
464 PrintCXStringWithPrefixAndDispose(
465 "CommandName",
466 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000467 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000468 i != e; ++i) {
469 printf(" Arg[%u]=", i);
470 PrintCXStringAndDispose(
471 clang_BlockCommandComment_getArgText(Comment, i));
472 }
473 break;
474 case CXComment_ParamCommand:
475 printf("CXComment_ParamCommand");
476 switch (clang_ParamCommandComment_getDirection(Comment)) {
477 case CXCommentParamPassDirection_In:
478 printf(" in");
479 break;
480 case CXCommentParamPassDirection_Out:
481 printf(" out");
482 break;
483 case CXCommentParamPassDirection_InOut:
484 printf(" in,out");
485 break;
486 }
487 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
488 printf(" explicitly");
489 else
490 printf(" implicitly");
491 PrintCXStringWithPrefixAndDispose(
492 "ParamName",
493 clang_ParamCommandComment_getParamName(Comment));
494 if (clang_ParamCommandComment_isParamIndexValid(Comment))
495 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
496 else
497 printf(" ParamIndex=Invalid");
498 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000499 case CXComment_TParamCommand:
500 printf("CXComment_TParamCommand");
501 PrintCXStringWithPrefixAndDispose(
502 "ParamName",
503 clang_TParamCommandComment_getParamName(Comment));
504 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
505 printf(" ParamPosition={");
506 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
507 i != e; ++i) {
508 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
509 if (i != e - 1)
510 printf(", ");
511 }
512 printf("}");
513 } else
514 printf(" ParamPosition=Invalid");
515 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000516 case CXComment_VerbatimBlockCommand:
517 printf("CXComment_VerbatimBlockCommand");
518 PrintCXStringWithPrefixAndDispose(
519 "CommandName",
520 clang_BlockCommandComment_getCommandName(Comment));
521 break;
522 case CXComment_VerbatimBlockLine:
523 printf("CXComment_VerbatimBlockLine");
524 PrintCXStringWithPrefixAndDispose(
525 "Text",
526 clang_VerbatimBlockLineComment_getText(Comment));
527 break;
528 case CXComment_VerbatimLine:
529 printf("CXComment_VerbatimLine");
530 PrintCXStringWithPrefixAndDispose(
531 "Text",
532 clang_VerbatimLineComment_getText(Comment));
533 break;
534 case CXComment_FullComment:
535 printf("CXComment_FullComment");
536 break;
537 }
538 if (Kind != CXComment_Null) {
539 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000540 unsigned i;
541 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000542 printf("\n// %s: ", FileCheckPrefix);
543 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
544 }
545 }
546 printf(")");
547 Ctx->IndentLevel--;
548}
549
550static void DumpCXComment(CXComment Comment) {
551 struct CommentASTDumpingContext Ctx;
552 Ctx.IndentLevel = 1;
553 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
554 DumpCXCommentInternal(&Ctx, Comment);
555 printf("]");
556}
557
Chandler Carruthb2faa592014-05-02 23:30:59 +0000558static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000559#ifdef CLANG_HAVE_LIBXML
560 xmlRelaxNGParserCtxtPtr RNGParser;
561 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000562 xmlDocPtr Doc;
563 xmlRelaxNGValidCtxtPtr ValidationCtxt;
564 int status;
565
Chandler Carruthb2faa592014-05-02 23:30:59 +0000566 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000567 return;
568
Chandler Carruthb2faa592014-05-02 23:30:59 +0000569 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
570 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000571 printf(" libXMLError");
572 return;
573 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000574 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000575
576 Doc = xmlParseDoc((const xmlChar *) Str);
577
578 if (!Doc) {
579 xmlErrorPtr Error = xmlGetLastError();
580 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
581 return;
582 }
583
Chandler Carruthb2faa592014-05-02 23:30:59 +0000584 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000585 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
586 if (!status)
587 printf(" CommentXMLValid");
588 else if (status > 0) {
589 xmlErrorPtr Error = xmlGetLastError();
590 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
591 } else
592 printf(" libXMLError");
593
594 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
595 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000596 xmlRelaxNGFree(Schema);
597 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000598#endif
599}
600
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000601static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000602 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000603 {
604 CXString RawComment;
605 const char *RawCommentCString;
606 CXString BriefComment;
607 const char *BriefCommentCString;
608
609 RawComment = clang_Cursor_getRawCommentText(Cursor);
610 RawCommentCString = clang_getCString(RawComment);
611 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
612 PrintCStringWithPrefix("RawComment", RawCommentCString);
613 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
614
615 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
616 BriefCommentCString = clang_getCString(BriefComment);
617 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
618 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
619 clang_disposeString(BriefComment);
620 }
621 clang_disposeString(RawComment);
622 }
623
624 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000625 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000626 if (clang_Comment_getKind(Comment) != CXComment_Null) {
627 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
628 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000629 {
630 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000631 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000632 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000633 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000634 clang_disposeString(XML);
635 }
636
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000637 DumpCXComment(Comment);
638 }
639 }
640}
641
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000642typedef struct {
643 unsigned line;
644 unsigned col;
645} LineCol;
646
647static int lineCol_cmp(const void *p1, const void *p2) {
648 const LineCol *lhs = p1;
649 const LineCol *rhs = p2;
650 if (lhs->line != rhs->line)
651 return (int)lhs->line - (int)rhs->line;
652 return (int)lhs->col - (int)rhs->col;
653}
654
Chandler Carruthb2faa592014-05-02 23:30:59 +0000655static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000656 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000657 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000658 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000659 printf("Invalid Cursor => %s", clang_getCString(ks));
660 clang_disposeString(ks);
661 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000662 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000663 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000664 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000665 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000666 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000667 CXCursor *overridden;
668 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000669 unsigned RefNameRangeNr;
670 CXSourceRange CursorExtent;
671 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000672 int AlwaysUnavailable;
673 int AlwaysDeprecated;
674 CXString UnavailableMessage;
675 CXString DeprecatedMessage;
676 CXPlatformAvailability PlatformAvailability[2];
677 int NumPlatformAvailability;
678 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000679
Ted Kremenek29004672010-02-17 00:41:32 +0000680 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000681 string = want_display_name? clang_getCursorDisplayName(Cursor)
682 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000683 printf("%s=%s", clang_getCString(ks),
684 clang_getCString(string));
685 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000686 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000687
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000688 Referenced = clang_getCursorReferenced(Cursor);
689 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000690 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
691 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
692 printf("[");
693 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000694 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000695 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000696 if (I)
697 printf(", ");
698
Douglas Gregor2967e282010-09-14 00:20:32 +0000699 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000700 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000701 printf("%d:%d", line, column);
702 }
703 printf("]");
704 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000705 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000706 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000707 printf(":%d:%d", line, column);
708 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000709 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000710
711 if (clang_isCursorDefinition(Cursor))
712 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000713
714 switch (clang_getCursorAvailability(Cursor)) {
715 case CXAvailability_Available:
716 break;
717
718 case CXAvailability_Deprecated:
719 printf(" (deprecated)");
720 break;
721
722 case CXAvailability_NotAvailable:
723 printf(" (unavailable)");
724 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000725
726 case CXAvailability_NotAccessible:
727 printf(" (inaccessible)");
728 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000729 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000730
Douglas Gregord6225d32012-05-08 00:14:45 +0000731 NumPlatformAvailability
732 = clang_getCursorPlatformAvailability(Cursor,
733 &AlwaysDeprecated,
734 &DeprecatedMessage,
735 &AlwaysUnavailable,
736 &UnavailableMessage,
737 PlatformAvailability, 2);
738 if (AlwaysUnavailable) {
739 printf(" (always unavailable: \"%s\")",
740 clang_getCString(UnavailableMessage));
741 } else if (AlwaysDeprecated) {
742 printf(" (always deprecated: \"%s\")",
743 clang_getCString(DeprecatedMessage));
744 } else {
745 for (I = 0; I != NumPlatformAvailability; ++I) {
746 if (I >= 2)
747 break;
748
749 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
750 if (PlatformAvailability[I].Unavailable)
751 printf(", unavailable");
752 else {
753 printVersion(", introduced=", PlatformAvailability[I].Introduced);
754 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
755 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
756 }
757 if (clang_getCString(PlatformAvailability[I].Message)[0])
758 printf(", message=\"%s\"",
759 clang_getCString(PlatformAvailability[I].Message));
760 printf(")");
761 }
762 }
763 for (I = 0; I != NumPlatformAvailability; ++I) {
764 if (I >= 2)
765 break;
766 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
767 }
768
769 clang_disposeString(DeprecatedMessage);
770 clang_disposeString(UnavailableMessage);
771
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000772 if (clang_CXXField_isMutable(Cursor))
773 printf(" (mutable)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000774 if (clang_CXXMethod_isStatic(Cursor))
775 printf(" (static)");
776 if (clang_CXXMethod_isVirtual(Cursor))
777 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000778 if (clang_CXXMethod_isConst(Cursor))
779 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000780 if (clang_CXXMethod_isPureVirtual(Cursor))
781 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000782 if (clang_Cursor_isVariadic(Cursor))
783 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000784 if (clang_Cursor_isObjCOptional(Cursor))
785 printf(" (@optional)");
786
Ted Kremeneka5940822010-08-26 01:42:22 +0000787 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000788 CXType T =
789 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
790 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000791 printf(" [IBOutletCollection=%s]", clang_getCString(S));
792 clang_disposeString(S);
793 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000794
795 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
796 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
797 unsigned isVirtual = clang_isVirtualBase(Cursor);
798 const char *accessStr = 0;
799
800 switch (access) {
801 case CX_CXXInvalidAccessSpecifier:
802 accessStr = "invalid"; break;
803 case CX_CXXPublic:
804 accessStr = "public"; break;
805 case CX_CXXProtected:
806 accessStr = "protected"; break;
807 case CX_CXXPrivate:
808 accessStr = "private"; break;
809 }
810
811 printf(" [access=%s isVirtual=%s]", accessStr,
812 isVirtual ? "true" : "false");
813 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000814
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000815 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
816 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000817 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
818 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000819 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000820 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000821 clang_getCString(Name), line, column);
822 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000823
824 if (Cursor.kind == CXCursor_FunctionDecl) {
825 /* Collect the template parameter kinds from the base template. */
826 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
827 unsigned I;
828 for (I = 0; I < NumTemplateArgs; I++) {
829 enum CXTemplateArgumentKind TAK =
830 clang_Cursor_getTemplateArgumentKind(Cursor, I);
831 switch(TAK) {
832 case CXTemplateArgumentKind_Type:
833 {
834 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
835 CXString S = clang_getTypeSpelling(T);
836 printf(" [Template arg %d: kind: %d, type: %s]",
837 I, TAK, clang_getCString(S));
838 clang_disposeString(S);
839 }
840 break;
841 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000842 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000843 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
844 break;
845 default:
846 printf(" [Template arg %d: kind: %d]\n", I, TAK);
847 }
848 }
849 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000850 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000851
852 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
853 if (num_overridden) {
854 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000855 LineCol lineCols[50];
856 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000857 printf(" [Overrides ");
858 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000859 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000860 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000861 lineCols[I].line = line;
862 lineCols[I].col = column;
863 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000864 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000865 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
866 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000867 if (I)
868 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000869 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000870 }
871 printf("]");
872 clang_disposeOverriddenCursors(overridden);
873 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000874
875 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000876 CXFile File = clang_getIncludedFile(Cursor);
877 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000878 printf(" (%s)", clang_getCString(Included));
879 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000880
881 if (clang_isFileMultipleIncludeGuarded(TU, File))
882 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000883 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000884
885 CursorExtent = clang_getCursorExtent(Cursor);
886 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
887 CXNameRange_WantQualifier
888 | CXNameRange_WantSinglePiece
889 | CXNameRange_WantTemplateArgs,
890 0);
891 if (!clang_equalRanges(CursorExtent, RefNameRange))
892 PrintRange(RefNameRange, "SingleRefName");
893
894 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
895 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
896 CXNameRange_WantQualifier
897 | CXNameRange_WantTemplateArgs,
898 RefNameRangeNr);
899 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
900 break;
901 if (!clang_equalRanges(CursorExtent, RefNameRange))
902 PrintRange(RefNameRange, "RefName");
903 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000904
Chandler Carruthb2faa592014-05-02 23:30:59 +0000905 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000906
907 {
908 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
909 if (PropAttrs != CXObjCPropertyAttr_noattr) {
910 printf(" [");
911 #define PRINT_PROP_ATTR(A) \
912 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
913 PRINT_PROP_ATTR(readonly);
914 PRINT_PROP_ATTR(getter);
915 PRINT_PROP_ATTR(assign);
916 PRINT_PROP_ATTR(readwrite);
917 PRINT_PROP_ATTR(retain);
918 PRINT_PROP_ATTR(copy);
919 PRINT_PROP_ATTR(nonatomic);
920 PRINT_PROP_ATTR(setter);
921 PRINT_PROP_ATTR(atomic);
922 PRINT_PROP_ATTR(weak);
923 PRINT_PROP_ATTR(strong);
924 PRINT_PROP_ATTR(unsafe_unretained);
925 printf("]");
926 }
927 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000928
929 {
930 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
931 if (QT != CXObjCDeclQualifier_None) {
932 printf(" [");
933 #define PRINT_OBJC_QUAL(A) \
934 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
935 PRINT_OBJC_QUAL(In);
936 PRINT_OBJC_QUAL(Inout);
937 PRINT_OBJC_QUAL(Out);
938 PRINT_OBJC_QUAL(Bycopy);
939 PRINT_OBJC_QUAL(Byref);
940 PRINT_OBJC_QUAL(Oneway);
941 printf("]");
942 }
943 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000944 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000945}
Steve Naroff1054e602009-08-31 00:59:03 +0000946
Ted Kremenek29004672010-02-17 00:41:32 +0000947static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000948 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000949 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000950 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000951 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000952 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000953 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000954 clang_disposeString(source);
955 return "<invalid loc>";
956 }
957 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000958 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000959 clang_disposeString(source);
960 return b;
961 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000962}
963
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000964/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000965/* Callbacks. */
966/******************************************************************************/
967
968typedef void (*PostVisitTU)(CXTranslationUnit);
969
Douglas Gregor33cdd812010-02-18 18:08:43 +0000970void PrintDiagnostic(CXDiagnostic Diagnostic) {
971 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000972 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000973 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000974 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000975 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
976 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000977 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000978
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000979 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000980 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000981
Douglas Gregord770f732010-02-22 23:17:23 +0000982 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
983 fprintf(stderr, "%s\n", clang_getCString(Msg));
984 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000985
Douglas Gregor229bebd2010-11-09 06:24:54 +0000986 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
987 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000988 if (!file)
989 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000990
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000991 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000992 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000993 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000994 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000995 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
996 CXSourceLocation start = clang_getRangeStart(range);
997 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000998 unsigned start_line, start_column, end_line, end_column;
999 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001000 clang_getSpellingLocation(start, &start_file, &start_line,
1001 &start_column, 0);
1002 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001003 if (clang_equalLocations(start, end)) {
1004 /* Insertion. */
1005 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001006 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001007 clang_getCString(insertion_text), start_line, start_column);
1008 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1009 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001010 if (start_file == file && end_file == file) {
1011 fprintf(out, "FIX-IT: Remove ");
1012 PrintExtent(out, start_line, start_column, end_line, end_column);
1013 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001014 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001015 } else {
1016 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001017 if (start_file == end_file) {
1018 fprintf(out, "FIX-IT: Replace ");
1019 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001020 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001021 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001022 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001023 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001024 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001025}
1026
Ted Kremenek914c7e62012-02-14 02:46:03 +00001027void PrintDiagnosticSet(CXDiagnosticSet Set) {
1028 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1029 for ( ; i != n ; ++i) {
1030 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1031 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001032 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001033 if (ChildDiags)
1034 PrintDiagnosticSet(ChildDiags);
1035 }
1036}
1037
1038void PrintDiagnostics(CXTranslationUnit TU) {
1039 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1040 PrintDiagnosticSet(TUSet);
1041 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001042}
1043
Ted Kremenek83f642e2011-04-18 22:47:10 +00001044void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001045 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001046 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001047 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001048 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001049 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001050 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001051 unsigned long amount = usage.entries[i].amount;
1052 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001053 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001054 ((double) amount)/(1024*1024));
1055 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001056 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001057 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001058 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001059}
1060
Ted Kremenekb478ff42010-01-26 17:59:48 +00001061/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001062/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001063/******************************************************************************/
1064
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001065static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001066 CXSourceRange extent = clang_getCursorExtent(C);
1067 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001068}
1069
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001070/* Data used by the visitors. */
1071typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001072 CXTranslationUnit TU;
1073 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001074 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001075} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001076
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001077
Ted Kremenek29004672010-02-17 00:41:32 +00001078enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001079 CXCursor Parent,
1080 CXClientData ClientData) {
1081 VisitorData *Data = (VisitorData *)ClientData;
1082 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001083 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001084 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001085 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001086 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001087 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001088 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001089 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001090 if (clang_isDeclaration(Cursor.kind)) {
1091 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1092 const char *accessStr = 0;
1093
1094 switch (access) {
1095 case CX_CXXInvalidAccessSpecifier: break;
1096 case CX_CXXPublic:
1097 accessStr = "public"; break;
1098 case CX_CXXProtected:
1099 accessStr = "protected"; break;
1100 case CX_CXXPrivate:
1101 accessStr = "private"; break;
1102 }
1103
1104 if (accessStr)
1105 printf(" [access=%s]", accessStr);
1106 }
Ted Kremenek29004672010-02-17 00:41:32 +00001107 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001108 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001109 }
Ted Kremenek29004672010-02-17 00:41:32 +00001110
Douglas Gregor720d0052010-01-20 21:32:04 +00001111 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001112}
Steve Naroffa1c72842009-08-28 15:28:48 +00001113
Ted Kremenek29004672010-02-17 00:41:32 +00001114static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001115 CXCursor Parent,
1116 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001117 const char *startBuf, *endBuf;
1118 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1119 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001120 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001121
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001122 if (Cursor.kind != CXCursor_FunctionDecl ||
1123 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001124 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001125
1126 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1127 &startLine, &startColumn,
1128 &endLine, &endColumn);
1129 /* Probe the entire body, looking for both decls and refs. */
1130 curLine = startLine;
1131 curColumn = startColumn;
1132
1133 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001134 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001135 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001136 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001137
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001138 if (*startBuf == '\n') {
1139 startBuf++;
1140 curLine++;
1141 curColumn = 1;
1142 } else if (*startBuf != '\t')
1143 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001144
Douglas Gregor66a58812010-01-18 22:46:11 +00001145 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001146 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001147
Douglas Gregor4f46e782010-01-19 21:36:55 +00001148 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001149 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001150 CXSourceLocation RefLoc
1151 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001152 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001153 if (Ref.kind == CXCursor_NoDeclFound) {
1154 /* Nothing found here; that's fine. */
1155 } else if (Ref.kind != CXCursor_FunctionDecl) {
1156 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1157 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001158 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001159 printf("\n");
1160 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001161 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001162 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001163 startBuf++;
1164 }
Ted Kremenek29004672010-02-17 00:41:32 +00001165
Douglas Gregor720d0052010-01-20 21:32:04 +00001166 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001167}
1168
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001169/******************************************************************************/
1170/* USR testing. */
1171/******************************************************************************/
1172
Douglas Gregor720d0052010-01-20 21:32:04 +00001173enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1174 CXClientData ClientData) {
1175 VisitorData *Data = (VisitorData *)ClientData;
1176 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001177 CXString USR = clang_getCursorUSR(C);
1178 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001179 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001180 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001181 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001182 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001183 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1184
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001185 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001186 printf("\n");
1187 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001188
Douglas Gregor720d0052010-01-20 21:32:04 +00001189 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001190 }
1191
Douglas Gregor720d0052010-01-20 21:32:04 +00001192 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001193}
1194
1195/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001196/* Inclusion stack testing. */
1197/******************************************************************************/
1198
1199void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1200 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001201
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001202 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001203 CXString fname;
1204
1205 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001206 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001207 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001208
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001209 for (i = 0; i < includeStackLen; ++i) {
1210 CXFile includingFile;
1211 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001212 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1213 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001214 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001215 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001216 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001217 }
1218 printf("\n");
1219}
1220
1221void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001222 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001223}
1224
1225/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001226/* Linkage testing. */
1227/******************************************************************************/
1228
1229static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1230 CXClientData d) {
1231 const char *linkage = 0;
1232
1233 if (clang_isInvalid(clang_getCursorKind(cursor)))
1234 return CXChildVisit_Recurse;
1235
1236 switch (clang_getCursorLinkage(cursor)) {
1237 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001238 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1239 case CXLinkage_Internal: linkage = "Internal"; break;
1240 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1241 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001242 }
1243
1244 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001245 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001246 printf("linkage=%s\n", linkage);
1247 }
1248
1249 return CXChildVisit_Recurse;
1250}
1251
1252/******************************************************************************/
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00001253/* Visibility testing. */
1254/******************************************************************************/
1255
1256static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1257 CXClientData d) {
1258 const char *visibility = 0;
1259
1260 if (clang_isInvalid(clang_getCursorKind(cursor)))
1261 return CXChildVisit_Recurse;
1262
1263 switch (clang_getCursorVisibility(cursor)) {
1264 case CXVisibility_Invalid: break;
1265 case CXVisibility_Hidden: visibility = "Hidden"; break;
1266 case CXVisibility_Protected: visibility = "Protected"; break;
1267 case CXVisibility_Default: visibility = "Default"; break;
1268 }
1269
1270 if (visibility) {
1271 PrintCursor(cursor, NULL);
1272 printf("visibility=%s\n", visibility);
1273 }
1274
1275 return CXChildVisit_Recurse;
1276}
1277
1278/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001279/* Typekind testing. */
1280/******************************************************************************/
1281
Dmitri Gribenko00353722013-02-15 21:15:49 +00001282static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1283 CXString TypeSpelling, TypeKindSpelling;
1284
1285 TypeSpelling = clang_getTypeSpelling(T);
1286 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1287 printf(Format,
1288 clang_getCString(TypeSpelling),
1289 clang_getCString(TypeKindSpelling));
1290 clang_disposeString(TypeSpelling);
1291 clang_disposeString(TypeKindSpelling);
1292}
1293
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001294static enum CXVisitorResult FieldVisitor(CXCursor C,
1295 CXClientData client_data) {
1296 (*(int *) client_data)+=1;
1297 return CXVisit_Continue;
1298}
1299
Dmitri Gribenko00353722013-02-15 21:15:49 +00001300static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1301 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001302 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001303 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001304 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001305 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001306 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001307 if (clang_isConstQualifiedType(T))
1308 printf(" const");
1309 if (clang_isVolatileQualifiedType(T))
1310 printf(" volatile");
1311 if (clang_isRestrictQualifiedType(T))
1312 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001313 if (RQ == CXRefQualifier_LValue)
1314 printf(" lvalue-ref-qualifier");
1315 if (RQ == CXRefQualifier_RValue)
1316 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001317 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001318 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001319 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001320 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001321 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001322 }
1323 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001324 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001325 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001326 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001327 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001328 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001329 }
1330 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001331 /* Print the argument types if they exist. */
1332 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001333 int NumArgs = clang_Cursor_getNumArguments(cursor);
1334 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001335 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001336 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001337 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001338 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001339 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001340 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001341 }
1342 }
1343 printf("]");
1344 }
1345 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001346 /* Print the template argument types if they exist. */
1347 {
1348 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1349 if (NumTArgs != -1 && NumTArgs != 0) {
1350 int i;
1351 printf(" [templateargs/%d=", NumTArgs);
1352 for (i = 0; i < NumTArgs; ++i) {
1353 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1354 if (TArg.kind != CXType_Invalid) {
1355 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1356 }
1357 }
1358 printf("]");
1359 }
1360 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001361 /* Print if this is a non-POD type. */
1362 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001363 /* Print the pointee type. */
1364 {
1365 CXType PT = clang_getPointeeType(T);
1366 if (PT.kind != CXType_Invalid) {
1367 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1368 }
1369 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001370 /* Print the number of fields if they exist. */
1371 {
1372 int numFields = 0;
1373 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1374 if (numFields != 0) {
1375 printf(" [nbFields=%d]", numFields);
1376 }
1377 /* Print if it is an anonymous record. */
1378 {
1379 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1380 if (isAnon != 0) {
1381 printf(" [isAnon=%d]", isAnon);
1382 }
1383 }
1384 }
1385 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001386
Ted Kremenek6bca9842010-05-14 21:29:26 +00001387 printf("\n");
1388 }
1389 return CXChildVisit_Recurse;
1390}
1391
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001392static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1393 CXClientData d) {
1394 CXType T;
1395 enum CXCursorKind K = clang_getCursorKind(cursor);
1396 if (clang_isInvalid(K))
1397 return CXChildVisit_Recurse;
1398 T = clang_getCursorType(cursor);
1399 PrintCursor(cursor, NULL);
1400 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1401 /* Print the type sizeof if applicable. */
1402 {
1403 long long Size = clang_Type_getSizeOf(T);
1404 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001405 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001406 }
1407 }
1408 /* Print the type alignof if applicable. */
1409 {
1410 long long Align = clang_Type_getAlignOf(T);
1411 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001412 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001413 }
1414 }
1415 /* Print the record field offset if applicable. */
1416 {
Nico Weber82098cb2014-04-24 04:14:12 +00001417 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1418 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001419 /* recurse to get the first parent record that is not anonymous. */
1420 CXCursor Parent, Record;
1421 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001422 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001423 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001424 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001425 Record = Parent;
1426 Parent = clang_getCursorSemanticParent(Record);
1427 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1428 /* Recurse as long as the parent is a CXType_Record and the Record
1429 is anonymous */
1430 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1431 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001432 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001433 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001434 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001435 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1436 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001437 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001438 } else {
1439 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001440 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001441 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001442 }
1443 }
Nico Weber82098cb2014-04-24 04:14:12 +00001444 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001445 }
1446 /* Print if its a bitfield */
1447 {
1448 int IsBitfield = clang_Cursor_isBitField(cursor);
1449 if (IsBitfield)
1450 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1451 }
1452 printf("\n");
1453 return CXChildVisit_Recurse;
1454}
1455
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001456/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001457/* Mangling testing. */
1458/******************************************************************************/
1459
1460static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1461 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001462 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001463 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1464 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001465 PrintCursor(cursor, NULL);
1466 MangledName = clang_Cursor_getMangling(cursor);
1467 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001468 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001469 return CXChildVisit_Continue;
1470}
1471
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001472static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1473 CXClientData d) {
1474 unsigned I, E;
1475 CXStringSet *Manglings = NULL;
1476 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1477 return CXChildVisit_Recurse;
1478 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1479 return CXChildVisit_Recurse;
1480 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1481 return CXChildVisit_Continue;
1482 PrintCursor(cursor, NULL);
1483 Manglings = clang_Cursor_getCXXManglings(cursor);
1484 for (I = 0, E = Manglings->Count; I < E; ++I)
1485 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1486 clang_disposeStringSet(Manglings);
1487 printf("\n");
1488 return CXChildVisit_Recurse;
1489}
1490
Eli Bendersky44a206f2014-07-31 18:04:56 +00001491/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001492/* Bitwidth testing. */
1493/******************************************************************************/
1494
1495static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1496 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001497 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001498 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1499 return CXChildVisit_Recurse;
1500
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001501 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001502 if (Bitwidth >= 0) {
1503 PrintCursor(cursor, NULL);
1504 printf(" bitwidth=%d\n", Bitwidth);
1505 }
1506
1507 return CXChildVisit_Recurse;
1508}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001509
1510/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001511/* Type declaration testing */
1512/******************************************************************************/
1513
1514static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1515 CXClientData d) {
1516 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1517
1518 if (clang_isDeclaration(typeDeclaration.kind)) {
1519 PrintCursor(cursor, NULL);
1520 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1521 }
1522
1523 return CXChildVisit_Recurse;
1524}
1525
1526/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001527/* Loading ASTs/source. */
1528/******************************************************************************/
1529
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001530static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001531 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001532 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001533 PostVisitTU PV,
1534 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001535
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001536 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001537 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001538
1539 if (Visitor) {
1540 enum CXCursorKind K = CXCursor_NotImplemented;
1541 enum CXCursorKind *ck = &K;
1542 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001543
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001544 /* Perform some simple filtering. */
1545 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001546 else if (!strcmp(filter, "all-display") ||
1547 !strcmp(filter, "local-display")) {
1548 ck = NULL;
1549 want_display_name = 1;
1550 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001551 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001552 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1553 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1554 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1555 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1556 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1557 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1558 else {
1559 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1560 return 1;
1561 }
Ted Kremenek29004672010-02-17 00:41:32 +00001562
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001563 Data.TU = TU;
1564 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001565 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001566 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001567 }
Ted Kremenek29004672010-02-17 00:41:32 +00001568
Ted Kremenekb478ff42010-01-26 17:59:48 +00001569 if (PV)
1570 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001571
Douglas Gregor33cdd812010-02-18 18:08:43 +00001572 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001573 if (checkForErrors(TU) != 0) {
1574 clang_disposeTranslationUnit(TU);
1575 return -1;
1576 }
1577
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001578 clang_disposeTranslationUnit(TU);
1579 return 0;
1580}
1581
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001582int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001583 const char *prefix, CXCursorVisitor Visitor,
1584 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001585 CXIndex Idx;
1586 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001587 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001588 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001589 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001590 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001591
Ted Kremenek50228be2010-02-11 07:41:25 +00001592 if (!CreateTranslationUnit(Idx, file, &TU)) {
1593 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001594 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001595 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001596
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001597 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001598 clang_disposeIndex(Idx);
1599 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001600}
1601
Ted Kremenekb478ff42010-01-26 17:59:48 +00001602int perform_test_load_source(int argc, const char **argv,
1603 const char *filter, CXCursorVisitor Visitor,
1604 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001605 CXIndex Idx;
1606 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001607 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001608 struct CXUnsavedFile *unsaved_files = 0;
1609 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001610 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001611 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001612 unsigned Repeats = 0;
1613 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001614
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001615 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001616 (!strcmp(filter, "local") ||
1617 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001618 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001619
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001620 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1621 argc--;
1622 argv++;
1623 }
1624
Ted Kremenek50228be2010-02-11 07:41:25 +00001625 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1626 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001627 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001628 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001629
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001630 if (getenv("CINDEXTEST_EDITING"))
1631 Repeats = 5;
1632
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001633 Err = clang_parseTranslationUnit2(Idx, 0,
1634 argv + num_unsaved_files,
1635 argc - num_unsaved_files,
1636 unsaved_files, num_unsaved_files,
1637 getDefaultParsingOptions(), &TU);
1638 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001639 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001640 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001641 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001642 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001643 return 1;
1644 }
1645
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001646 for (I = 0; I != Repeats; ++I) {
1647 if (checkForErrors(TU) != 0)
1648 return -1;
1649
1650 if (Repeats > 1) {
1651 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1652 clang_defaultReparseOptions(TU));
1653 if (Err != CXError_Success) {
1654 describeLibclangFailure(Err);
1655 free_remapped_files(unsaved_files, num_unsaved_files);
1656 clang_disposeIndex(Idx);
1657 return 1;
1658 }
1659 }
1660 }
1661
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001662 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1663 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001664 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001665 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001666 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001667}
1668
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001669int perform_test_reparse_source(int argc, const char **argv, int trials,
1670 const char *filter, CXCursorVisitor Visitor,
1671 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001672 CXIndex Idx;
1673 CXTranslationUnit TU;
1674 struct CXUnsavedFile *unsaved_files = 0;
1675 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001676 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001677 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001678 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001679 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001680 int remap_after_trial = 0;
1681 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001682
1683 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1684 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001685 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001686
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001687 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1688 clang_disposeIndex(Idx);
1689 return -1;
1690 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001691
1692 for (i = 0; i < argc; ++i) {
1693 if (strcmp(argv[i], "--") == 0)
1694 break;
1695 }
1696 if (i < argc)
1697 compiler_arg_idx = i+1;
1698 if (num_unsaved_files > compiler_arg_idx)
1699 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001700
Daniel Dunbarec29d712010-08-18 23:09:16 +00001701 /* Load the initial translation unit -- we do this without honoring remapped
1702 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001703 Err = clang_parseTranslationUnit2(Idx, 0,
1704 argv + compiler_arg_idx,
1705 argc - compiler_arg_idx,
1706 0, 0, getDefaultParsingOptions(), &TU);
1707 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001708 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001709 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001710 free_remapped_files(unsaved_files, num_unsaved_files);
1711 clang_disposeIndex(Idx);
1712 return 1;
1713 }
1714
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001715 if (checkForErrors(TU) != 0)
1716 return -1;
1717
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001718 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1719 remap_after_trial =
1720 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1721 }
1722
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001723 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001724 free_remapped_files(unsaved_files, num_unsaved_files);
1725 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1726 &unsaved_files, &num_unsaved_files)) {
1727 clang_disposeTranslationUnit(TU);
1728 clang_disposeIndex(Idx);
1729 return -1;
1730 }
1731
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001732 Err = clang_reparseTranslationUnit(
1733 TU,
1734 trial >= remap_after_trial ? num_unsaved_files : 0,
1735 trial >= remap_after_trial ? unsaved_files : 0,
1736 clang_defaultReparseOptions(TU));
1737 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001738 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001739 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001740 clang_disposeTranslationUnit(TU);
1741 free_remapped_files(unsaved_files, num_unsaved_files);
1742 clang_disposeIndex(Idx);
1743 return -1;
1744 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001745
1746 if (checkForErrors(TU) != 0)
1747 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001748 }
1749
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001750 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001751
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001752 free_remapped_files(unsaved_files, num_unsaved_files);
1753 clang_disposeIndex(Idx);
1754 return result;
1755}
1756
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001757/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001758/* Logic for testing clang_getCursor(). */
1759/******************************************************************************/
1760
Douglas Gregor37aa4932011-05-04 00:14:37 +00001761static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001762 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001763 unsigned end_line, unsigned end_col,
1764 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001765 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001766 if (prefix)
1767 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001768 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1769 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001770 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001771 printf("\n");
1772}
1773
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001774static int perform_file_scan(const char *ast_file, const char *source_file,
1775 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001776 CXIndex Idx;
1777 CXTranslationUnit TU;
1778 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001779 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001780 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001781 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001782 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001783
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001784 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001785 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001786 fprintf(stderr, "Could not create Index\n");
1787 return 1;
1788 }
Ted Kremenek29004672010-02-17 00:41:32 +00001789
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001790 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1791 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001792
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001793 if ((fp = fopen(source_file, "r")) == NULL) {
1794 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001795 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001796 return 1;
1797 }
Ted Kremenek29004672010-02-17 00:41:32 +00001798
Douglas Gregor816fd362010-01-22 21:44:22 +00001799 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001800 for (;;) {
1801 CXCursor cursor;
1802 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001803
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001804 if (c == '\n') {
1805 ++line;
1806 col = 1;
1807 } else
1808 ++col;
1809
1810 /* Check the cursor at this position, and dump the previous one if we have
1811 * found something new.
1812 */
1813 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1814 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1815 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001816 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001817 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001818 start_line = line;
1819 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001820 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001821 if (c == EOF)
1822 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001823
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001824 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001825 }
Ted Kremenek29004672010-02-17 00:41:32 +00001826
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001827 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001828 clang_disposeTranslationUnit(TU);
1829 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001830 return 0;
1831}
1832
1833/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001834/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001835/******************************************************************************/
1836
Douglas Gregor9eb77012009-11-07 00:00:49 +00001837/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1838 on failure. If successful, the pointer *filename will contain newly-allocated
1839 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001840int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001841 unsigned *column, unsigned *second_line,
1842 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001843 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001844 const char *last_colon = strrchr(input, ':');
1845 unsigned values[4], i;
1846 unsigned num_values = (second_line && second_column)? 4 : 2;
1847
Douglas Gregor9eb77012009-11-07 00:00:49 +00001848 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001849 if (!last_colon || last_colon == input) {
1850 if (num_values == 4)
1851 fprintf(stderr, "could not parse filename:line:column:line:column in "
1852 "'%s'\n", input);
1853 else
1854 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001855 return 1;
1856 }
1857
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001858 for (i = 0; i != num_values; ++i) {
1859 const char *prev_colon;
1860
1861 /* Parse the next line or column. */
1862 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1863 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001864 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001865 (i % 2 ? "column" : "line"), input);
1866 return 1;
1867 }
Ted Kremenek29004672010-02-17 00:41:32 +00001868
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001869 if (i + 1 == num_values)
1870 break;
1871
1872 /* Find the previous colon. */
1873 prev_colon = last_colon - 1;
1874 while (prev_colon != input && *prev_colon != ':')
1875 --prev_colon;
1876 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001877 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001878 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001879 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001880 }
1881
1882 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001883 }
1884
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001885 *line = values[0];
1886 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001887
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001888 if (second_line && second_column) {
1889 *second_line = values[2];
1890 *second_column = values[3];
1891 }
1892
Douglas Gregorf96ea292009-11-09 18:19:57 +00001893 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001894 *filename = (char*)malloc(last_colon - input + 1);
1895 memcpy(*filename, input, last_colon - input);
1896 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001897 return 0;
1898}
1899
1900const char *
1901clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1902 switch (Kind) {
1903 case CXCompletionChunk_Optional: return "Optional";
1904 case CXCompletionChunk_TypedText: return "TypedText";
1905 case CXCompletionChunk_Text: return "Text";
1906 case CXCompletionChunk_Placeholder: return "Placeholder";
1907 case CXCompletionChunk_Informative: return "Informative";
1908 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1909 case CXCompletionChunk_LeftParen: return "LeftParen";
1910 case CXCompletionChunk_RightParen: return "RightParen";
1911 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1912 case CXCompletionChunk_RightBracket: return "RightBracket";
1913 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1914 case CXCompletionChunk_RightBrace: return "RightBrace";
1915 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1916 case CXCompletionChunk_RightAngle: return "RightAngle";
1917 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001918 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001919 case CXCompletionChunk_Colon: return "Colon";
1920 case CXCompletionChunk_SemiColon: return "SemiColon";
1921 case CXCompletionChunk_Equal: return "Equal";
1922 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1923 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001924 }
Ted Kremenek29004672010-02-17 00:41:32 +00001925
Douglas Gregor9eb77012009-11-07 00:00:49 +00001926 return "Unknown";
1927}
1928
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001929static int checkForErrors(CXTranslationUnit TU) {
1930 unsigned Num, i;
1931 CXDiagnostic Diag;
1932 CXString DiagStr;
1933
1934 if (!getenv("CINDEXTEST_FAILONERROR"))
1935 return 0;
1936
1937 Num = clang_getNumDiagnostics(TU);
1938 for (i = 0; i != Num; ++i) {
1939 Diag = clang_getDiagnostic(TU, i);
1940 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1941 DiagStr = clang_formatDiagnostic(Diag,
1942 clang_defaultDiagnosticDisplayOptions());
1943 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1944 clang_disposeString(DiagStr);
1945 clang_disposeDiagnostic(Diag);
1946 return -1;
1947 }
1948 clang_disposeDiagnostic(Diag);
1949 }
1950
1951 return 0;
1952}
1953
Nico Weber8d19dff2014-05-07 21:05:22 +00001954static void print_completion_string(CXCompletionString completion_string,
1955 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001956 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001957
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001958 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001959 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001960 CXString text;
1961 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001962 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001963 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001964
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001965 if (Kind == CXCompletionChunk_Optional) {
1966 fprintf(file, "{Optional ");
1967 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001968 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001969 file);
1970 fprintf(file, "}");
1971 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001972 }
1973
1974 if (Kind == CXCompletionChunk_VerticalSpace) {
1975 fprintf(file, "{VerticalSpace }");
1976 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001977 }
Ted Kremenek29004672010-02-17 00:41:32 +00001978
Douglas Gregorf81f5282009-11-09 17:05:28 +00001979 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001980 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001981 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001982 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001983 cstr ? cstr : "");
1984 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001985 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001986
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001987}
1988
Nico Weber8d19dff2014-05-07 21:05:22 +00001989static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001990 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001991 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001992 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001993 enum CXCursorKind ParentKind;
1994 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001995 CXString BriefComment;
1996 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001997
Ted Kremenek29004672010-02-17 00:41:32 +00001998 fprintf(file, "%s:", clang_getCString(ks));
1999 clang_disposeString(ks);
2000
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002001 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00002002 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00002003 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00002004 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
2005 case CXAvailability_Available:
2006 break;
2007
2008 case CXAvailability_Deprecated:
2009 fprintf(file, " (deprecated)");
2010 break;
2011
2012 case CXAvailability_NotAvailable:
2013 fprintf(file, " (unavailable)");
2014 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002015
2016 case CXAvailability_NotAccessible:
2017 fprintf(file, " (inaccessible)");
2018 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002019 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002020
2021 annotationCount = clang_getCompletionNumAnnotations(
2022 completion_result->CompletionString);
2023 if (annotationCount) {
2024 unsigned i;
2025 fprintf(file, " (");
2026 for (i = 0; i < annotationCount; ++i) {
2027 if (i != 0)
2028 fprintf(file, ", ");
2029 fprintf(file, "\"%s\"",
2030 clang_getCString(clang_getCompletionAnnotation(
2031 completion_result->CompletionString, i)));
2032 }
2033 fprintf(file, ")");
2034 }
2035
Douglas Gregor78254c82012-03-27 23:34:16 +00002036 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2037 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2038 &ParentKind);
2039 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002040 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002041 fprintf(file, " (parent: %s '%s')",
2042 clang_getCString(KindSpelling),
2043 clang_getCString(ParentName));
2044 clang_disposeString(KindSpelling);
2045 }
2046 clang_disposeString(ParentName);
2047 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002048
2049 BriefComment = clang_getCompletionBriefComment(
2050 completion_result->CompletionString);
2051 BriefCommentCString = clang_getCString(BriefComment);
2052 if (BriefCommentCString && *BriefCommentCString != '\0') {
2053 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2054 }
2055 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002056
Douglas Gregorf757a122010-08-23 23:00:57 +00002057 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002058}
2059
Douglas Gregor21325842011-07-07 16:03:39 +00002060void print_completion_contexts(unsigned long long contexts, FILE *file) {
2061 fprintf(file, "Completion contexts:\n");
2062 if (contexts == CXCompletionContext_Unknown) {
2063 fprintf(file, "Unknown\n");
2064 }
2065 if (contexts & CXCompletionContext_AnyType) {
2066 fprintf(file, "Any type\n");
2067 }
2068 if (contexts & CXCompletionContext_AnyValue) {
2069 fprintf(file, "Any value\n");
2070 }
2071 if (contexts & CXCompletionContext_ObjCObjectValue) {
2072 fprintf(file, "Objective-C object value\n");
2073 }
2074 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2075 fprintf(file, "Objective-C selector value\n");
2076 }
2077 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2078 fprintf(file, "C++ class type value\n");
2079 }
2080 if (contexts & CXCompletionContext_DotMemberAccess) {
2081 fprintf(file, "Dot member access\n");
2082 }
2083 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2084 fprintf(file, "Arrow member access\n");
2085 }
2086 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2087 fprintf(file, "Objective-C property access\n");
2088 }
2089 if (contexts & CXCompletionContext_EnumTag) {
2090 fprintf(file, "Enum tag\n");
2091 }
2092 if (contexts & CXCompletionContext_UnionTag) {
2093 fprintf(file, "Union tag\n");
2094 }
2095 if (contexts & CXCompletionContext_StructTag) {
2096 fprintf(file, "Struct tag\n");
2097 }
2098 if (contexts & CXCompletionContext_ClassTag) {
2099 fprintf(file, "Class name\n");
2100 }
2101 if (contexts & CXCompletionContext_Namespace) {
2102 fprintf(file, "Namespace or namespace alias\n");
2103 }
2104 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2105 fprintf(file, "Nested name specifier\n");
2106 }
2107 if (contexts & CXCompletionContext_ObjCInterface) {
2108 fprintf(file, "Objective-C interface\n");
2109 }
2110 if (contexts & CXCompletionContext_ObjCProtocol) {
2111 fprintf(file, "Objective-C protocol\n");
2112 }
2113 if (contexts & CXCompletionContext_ObjCCategory) {
2114 fprintf(file, "Objective-C category\n");
2115 }
2116 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2117 fprintf(file, "Objective-C instance method\n");
2118 }
2119 if (contexts & CXCompletionContext_ObjCClassMessage) {
2120 fprintf(file, "Objective-C class method\n");
2121 }
2122 if (contexts & CXCompletionContext_ObjCSelectorName) {
2123 fprintf(file, "Objective-C selector name\n");
2124 }
2125 if (contexts & CXCompletionContext_MacroName) {
2126 fprintf(file, "Macro name\n");
2127 }
2128 if (contexts & CXCompletionContext_NaturalLanguage) {
2129 fprintf(file, "Natural language\n");
2130 }
2131}
2132
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002133int my_stricmp(const char *s1, const char *s2) {
2134 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002135 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002136 if (c1 < c2)
2137 return -1;
2138 else if (c1 > c2)
2139 return 1;
2140
2141 ++s1;
2142 ++s2;
2143 }
2144
2145 if (*s1)
2146 return 1;
2147 else if (*s2)
2148 return -1;
2149 return 0;
2150}
2151
Douglas Gregor47815d52010-07-12 18:38:41 +00002152int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002153 const char *input = argv[1];
2154 char *filename = 0;
2155 unsigned line;
2156 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002157 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002158 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002159 struct CXUnsavedFile *unsaved_files = 0;
2160 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002161 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002162 enum CXErrorCode Err;
2163 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002164 unsigned I, Repeats = 1;
2165 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2166
2167 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2168 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002169 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2170 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002171
Douglas Gregor47815d52010-07-12 18:38:41 +00002172 if (timing_only)
2173 input += strlen("-code-completion-timing=");
2174 else
2175 input += strlen("-code-completion-at=");
2176
Ted Kremenek29004672010-02-17 00:41:32 +00002177 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002178 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002179 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002180
Douglas Gregor9485bf92009-12-02 09:21:34 +00002181 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2182 return -1;
2183
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002184 CIdx = clang_createIndex(0, 0);
2185
2186 if (getenv("CINDEXTEST_EDITING"))
2187 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002188
2189 Err = clang_parseTranslationUnit2(CIdx, 0,
2190 argv + num_unsaved_files + 2,
2191 argc - num_unsaved_files - 2,
2192 0, 0, getDefaultParsingOptions(), &TU);
2193 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002194 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002195 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002196 return 1;
2197 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002198
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002199 Err = clang_reparseTranslationUnit(TU, 0, 0,
2200 clang_defaultReparseOptions(TU));
2201
2202 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002203 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002204 describeLibclangFailure(Err);
2205 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002206 return 1;
2207 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002208
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002209 for (I = 0; I != Repeats; ++I) {
2210 results = clang_codeCompleteAt(TU, filename, line, column,
2211 unsaved_files, num_unsaved_files,
2212 completionOptions);
2213 if (!results) {
2214 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002215 return 1;
2216 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002217 if (I != Repeats-1)
2218 clang_disposeCodeCompleteResults(results);
2219 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002220
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002221 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002222 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002223 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002224 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002225 CXString objCSelector;
2226 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002227 if (!timing_only) {
2228 /* Sort the code-completion results based on the typed text. */
2229 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2230
Douglas Gregor47815d52010-07-12 18:38:41 +00002231 for (i = 0; i != n; ++i)
2232 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002233 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002234 n = clang_codeCompleteGetNumDiagnostics(results);
2235 for (i = 0; i != n; ++i) {
2236 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2237 PrintDiagnostic(diag);
2238 clang_disposeDiagnostic(diag);
2239 }
Douglas Gregor21325842011-07-07 16:03:39 +00002240
2241 contexts = clang_codeCompleteGetContexts(results);
2242 print_completion_contexts(contexts, stdout);
2243
Douglas Gregorea777402011-07-26 15:24:30 +00002244 containerKind = clang_codeCompleteGetContainerKind(results,
2245 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002246
2247 if (containerKind != CXCursor_InvalidCode) {
2248 /* We have found a container */
2249 CXString containerUSR, containerKindSpelling;
2250 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2251 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2252 clang_disposeString(containerKindSpelling);
2253
2254 if (containerIsIncomplete) {
2255 printf("Container is incomplete\n");
2256 }
2257 else {
2258 printf("Container is complete\n");
2259 }
2260
2261 containerUSR = clang_codeCompleteGetContainerUSR(results);
2262 printf("Container USR: %s\n", clang_getCString(containerUSR));
2263 clang_disposeString(containerUSR);
2264 }
2265
Douglas Gregorea777402011-07-26 15:24:30 +00002266 objCSelector = clang_codeCompleteGetObjCSelector(results);
2267 selectorString = clang_getCString(objCSelector);
2268 if (selectorString && strlen(selectorString) > 0) {
2269 printf("Objective-C selector: %s\n", selectorString);
2270 }
2271 clang_disposeString(objCSelector);
2272
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002273 clang_disposeCodeCompleteResults(results);
2274 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002275 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002276 clang_disposeIndex(CIdx);
2277 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002278
Douglas Gregor9485bf92009-12-02 09:21:34 +00002279 free_remapped_files(unsaved_files, num_unsaved_files);
2280
Ted Kremenekef3339b2009-11-17 18:09:14 +00002281 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002282}
2283
Douglas Gregor082c3e62010-01-15 19:40:17 +00002284typedef struct {
2285 char *filename;
2286 unsigned line;
2287 unsigned column;
2288} CursorSourceLocation;
2289
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002290typedef void (*cursor_handler_t)(CXCursor cursor);
2291
2292static int inspect_cursor_at(int argc, const char **argv,
2293 const char *locations_flag,
2294 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002295 CXIndex CIdx;
2296 int errorCode;
2297 struct CXUnsavedFile *unsaved_files = 0;
2298 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002299 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002300 CXTranslationUnit TU;
2301 CXCursor Cursor;
2302 CursorSourceLocation *Locations = 0;
2303 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002304 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002305 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002306
Ted Kremenek29004672010-02-17 00:41:32 +00002307 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002308 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002309 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002310
Douglas Gregor082c3e62010-01-15 19:40:17 +00002311 /* Parse the locations. */
2312 assert(NumLocations > 0 && "Unable to count locations?");
2313 Locations = (CursorSourceLocation *)malloc(
2314 NumLocations * sizeof(CursorSourceLocation));
2315 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002316 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002317 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2318 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002319 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002320 return errorCode;
2321 }
Ted Kremenek29004672010-02-17 00:41:32 +00002322
2323 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002324 &num_unsaved_files))
2325 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002326
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002327 if (getenv("CINDEXTEST_EDITING"))
2328 Repeats = 5;
2329
2330 /* Parse the translation unit. When we're testing clang_getCursor() after
2331 reparsing, don't remap unsaved files until the second parse. */
2332 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002333 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2334 argv + num_unsaved_files + 1 + NumLocations,
2335 argc - num_unsaved_files - 2 - NumLocations,
2336 unsaved_files,
2337 Repeats > 1? 0 : num_unsaved_files,
2338 getDefaultParsingOptions(), &TU);
2339 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002340 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002341 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002342 return -1;
2343 }
Ted Kremenek29004672010-02-17 00:41:32 +00002344
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002345 if (checkForErrors(TU) != 0)
2346 return -1;
2347
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002348 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002349 if (Repeats > 1) {
2350 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2351 clang_defaultReparseOptions(TU));
2352 if (Err != CXError_Success) {
2353 describeLibclangFailure(Err);
2354 clang_disposeTranslationUnit(TU);
2355 return 1;
2356 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002357 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002358
2359 if (checkForErrors(TU) != 0)
2360 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002361
2362 for (Loc = 0; Loc < NumLocations; ++Loc) {
2363 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2364 if (!file)
2365 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002366
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002367 Cursor = clang_getCursor(TU,
2368 clang_getLocation(TU, file, Locations[Loc].line,
2369 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002370
2371 if (checkForErrors(TU) != 0)
2372 return -1;
2373
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002374 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002375 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002376 free(Locations[Loc].filename);
2377 }
2378 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002379 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002380
Douglas Gregor33cdd812010-02-18 18:08:43 +00002381 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002382 clang_disposeTranslationUnit(TU);
2383 clang_disposeIndex(CIdx);
2384 free(Locations);
2385 free_remapped_files(unsaved_files, num_unsaved_files);
2386 return 0;
2387}
2388
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002389static void inspect_print_cursor(CXCursor Cursor) {
2390 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2391 CXCompletionString completionString = clang_getCursorCompletionString(
2392 Cursor);
2393 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2394 CXString Spelling;
2395 const char *cspell;
2396 unsigned line, column;
2397 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2398 printf("%d:%d ", line, column);
2399 PrintCursor(Cursor, NULL);
2400 PrintCursorExtent(Cursor);
2401 Spelling = clang_getCursorSpelling(Cursor);
2402 cspell = clang_getCString(Spelling);
2403 if (cspell && strlen(cspell) != 0) {
2404 unsigned pieceIndex;
2405 printf(" Spelling=%s (", cspell);
2406 for (pieceIndex = 0; ; ++pieceIndex) {
2407 CXSourceRange range =
2408 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2409 if (clang_Range_isNull(range))
2410 break;
2411 PrintRange(range, 0);
2412 }
2413 printf(")");
2414 }
2415 clang_disposeString(Spelling);
2416 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2417 printf(" Selector index=%d",
2418 clang_Cursor_getObjCSelectorIndex(Cursor));
2419 if (clang_Cursor_isDynamicCall(Cursor))
2420 printf(" Dynamic-call");
2421 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2422 CXType T = clang_Cursor_getReceiverType(Cursor);
2423 CXString S = clang_getTypeKindSpelling(T.kind);
2424 printf(" Receiver-type=%s", clang_getCString(S));
2425 clang_disposeString(S);
2426 }
2427
2428 {
2429 CXModule mod = clang_Cursor_getModule(Cursor);
2430 CXFile astFile;
2431 CXString name, astFilename;
2432 unsigned i, numHeaders;
2433 if (mod) {
2434 astFile = clang_Module_getASTFile(mod);
2435 astFilename = clang_getFileName(astFile);
2436 name = clang_Module_getFullName(mod);
2437 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2438 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2439 clang_getCString(name), clang_getCString(astFilename),
2440 clang_Module_isSystem(mod), numHeaders);
2441 clang_disposeString(name);
2442 clang_disposeString(astFilename);
2443 for (i = 0; i < numHeaders; ++i) {
2444 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2445 CXString filename = clang_getFileName(file);
2446 printf("\n%s", clang_getCString(filename));
2447 clang_disposeString(filename);
2448 }
2449 }
2450 }
2451
2452 if (completionString != NULL) {
2453 printf("\nCompletion string: ");
2454 print_completion_string(completionString, stdout);
2455 }
2456 printf("\n");
2457}
2458
2459static void display_evaluate_results(CXEvalResult result) {
2460 switch (clang_EvalResult_getKind(result)) {
2461 case CXEval_Int:
2462 {
2463 int val = clang_EvalResult_getAsInt(result);
2464 printf("Kind: Int , Value: %d", val);
2465 break;
2466 }
2467 case CXEval_Float:
2468 {
2469 double val = clang_EvalResult_getAsDouble(result);
2470 printf("Kind: Float , Value: %f", val);
2471 break;
2472 }
2473 case CXEval_ObjCStrLiteral:
2474 {
2475 const char* str = clang_EvalResult_getAsStr(result);
2476 printf("Kind: ObjCString , Value: %s", str);
2477 break;
2478 }
2479 case CXEval_StrLiteral:
2480 {
2481 const char* str = clang_EvalResult_getAsStr(result);
2482 printf("Kind: CString , Value: %s", str);
2483 break;
2484 }
2485 case CXEval_CFStr:
2486 {
2487 const char* str = clang_EvalResult_getAsStr(result);
2488 printf("Kind: CFString , Value: %s", str);
2489 break;
2490 }
2491 default:
2492 printf("Unexposed");
2493 break;
2494 }
2495}
2496
2497static void inspect_evaluate_cursor(CXCursor Cursor) {
2498 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2499 CXString Spelling;
2500 const char *cspell;
2501 unsigned line, column;
2502 CXEvalResult ER;
2503
2504 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2505 printf("%d:%d ", line, column);
2506 PrintCursor(Cursor, NULL);
2507 PrintCursorExtent(Cursor);
2508 Spelling = clang_getCursorSpelling(Cursor);
2509 cspell = clang_getCString(Spelling);
2510 if (cspell && strlen(cspell) != 0) {
2511 unsigned pieceIndex;
2512 printf(" Spelling=%s (", cspell);
2513 for (pieceIndex = 0; ; ++pieceIndex) {
2514 CXSourceRange range =
2515 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2516 if (clang_Range_isNull(range))
2517 break;
2518 PrintRange(range, 0);
2519 }
2520 printf(")");
2521 }
2522 clang_disposeString(Spelling);
2523
2524 ER = clang_Cursor_Evaluate(Cursor);
2525 if (!ER) {
2526 printf("Not Evaluatable");
2527 } else {
2528 display_evaluate_results(ER);
2529 clang_EvalResult_dispose(ER);
2530 }
2531 printf("\n");
2532}
2533
2534static void inspect_macroinfo_cursor(CXCursor Cursor) {
2535 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2536 CXString Spelling;
2537 const char *cspell;
2538 unsigned line, column;
2539 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2540 printf("%d:%d ", line, column);
2541 PrintCursor(Cursor, NULL);
2542 PrintCursorExtent(Cursor);
2543 Spelling = clang_getCursorSpelling(Cursor);
2544 cspell = clang_getCString(Spelling);
2545 if (cspell && strlen(cspell) != 0) {
2546 unsigned pieceIndex;
2547 printf(" Spelling=%s (", cspell);
2548 for (pieceIndex = 0; ; ++pieceIndex) {
2549 CXSourceRange range =
2550 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2551 if (clang_Range_isNull(range))
2552 break;
2553 PrintRange(range, 0);
2554 }
2555 printf(")");
2556 }
2557 clang_disposeString(Spelling);
2558
2559 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2560 printf("[builtin macro]");
2561 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2562 printf("[function macro]");
2563 }
2564 printf("\n");
2565}
2566
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002567static enum CXVisitorResult findFileRefsVisit(void *context,
2568 CXCursor cursor, CXSourceRange range) {
2569 if (clang_Range_isNull(range))
2570 return CXVisit_Continue;
2571
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002572 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002573 PrintRange(range, "");
2574 printf("\n");
2575 return CXVisit_Continue;
2576}
2577
2578static int find_file_refs_at(int argc, const char **argv) {
2579 CXIndex CIdx;
2580 int errorCode;
2581 struct CXUnsavedFile *unsaved_files = 0;
2582 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002583 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002584 CXTranslationUnit TU;
2585 CXCursor Cursor;
2586 CursorSourceLocation *Locations = 0;
2587 unsigned NumLocations = 0, Loc;
2588 unsigned Repeats = 1;
2589 unsigned I;
2590
2591 /* Count the number of locations. */
2592 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2593 ++NumLocations;
2594
2595 /* Parse the locations. */
2596 assert(NumLocations > 0 && "Unable to count locations?");
2597 Locations = (CursorSourceLocation *)malloc(
2598 NumLocations * sizeof(CursorSourceLocation));
2599 for (Loc = 0; Loc < NumLocations; ++Loc) {
2600 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2601 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2602 &Locations[Loc].line,
2603 &Locations[Loc].column, 0, 0)))
2604 return errorCode;
2605 }
2606
2607 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2608 &num_unsaved_files))
2609 return -1;
2610
2611 if (getenv("CINDEXTEST_EDITING"))
2612 Repeats = 5;
2613
2614 /* Parse the translation unit. When we're testing clang_getCursor() after
2615 reparsing, don't remap unsaved files until the second parse. */
2616 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002617 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2618 argv + num_unsaved_files + 1 + NumLocations,
2619 argc - num_unsaved_files - 2 - NumLocations,
2620 unsaved_files,
2621 Repeats > 1? 0 : num_unsaved_files,
2622 getDefaultParsingOptions(), &TU);
2623 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002624 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002625 describeLibclangFailure(Err);
2626 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002627 return -1;
2628 }
2629
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002630 if (checkForErrors(TU) != 0)
2631 return -1;
2632
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002633 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002634 if (Repeats > 1) {
2635 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2636 clang_defaultReparseOptions(TU));
2637 if (Err != CXError_Success) {
2638 describeLibclangFailure(Err);
2639 clang_disposeTranslationUnit(TU);
2640 return 1;
2641 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002642 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002643
2644 if (checkForErrors(TU) != 0)
2645 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002646
2647 for (Loc = 0; Loc < NumLocations; ++Loc) {
2648 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2649 if (!file)
2650 continue;
2651
2652 Cursor = clang_getCursor(TU,
2653 clang_getLocation(TU, file, Locations[Loc].line,
2654 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002655
2656 if (checkForErrors(TU) != 0)
2657 return -1;
2658
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002659 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002660 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002661 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002662 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002663 clang_findReferencesInFile(Cursor, file, visitor);
2664 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002665
2666 if (checkForErrors(TU) != 0)
2667 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002668 }
2669 }
2670 }
2671
2672 PrintDiagnostics(TU);
2673 clang_disposeTranslationUnit(TU);
2674 clang_disposeIndex(CIdx);
2675 free(Locations);
2676 free_remapped_files(unsaved_files, num_unsaved_files);
2677 return 0;
2678}
2679
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002680static enum CXVisitorResult findFileIncludesVisit(void *context,
2681 CXCursor cursor, CXSourceRange range) {
2682 PrintCursor(cursor, NULL);
2683 PrintRange(range, "");
2684 printf("\n");
2685 return CXVisit_Continue;
2686}
2687
2688static int find_file_includes_in(int argc, const char **argv) {
2689 CXIndex CIdx;
2690 struct CXUnsavedFile *unsaved_files = 0;
2691 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002692 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002693 CXTranslationUnit TU;
2694 const char **Filenames = 0;
2695 unsigned NumFilenames = 0;
2696 unsigned Repeats = 1;
2697 unsigned I, FI;
2698
2699 /* Count the number of locations. */
2700 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2701 ++NumFilenames;
2702
2703 /* Parse the locations. */
2704 assert(NumFilenames > 0 && "Unable to count filenames?");
2705 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2706 for (I = 0; I < NumFilenames; ++I) {
2707 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2708 /* Copy the file name. */
2709 Filenames[I] = input;
2710 }
2711
2712 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2713 &num_unsaved_files))
2714 return -1;
2715
2716 if (getenv("CINDEXTEST_EDITING"))
2717 Repeats = 2;
2718
2719 /* Parse the translation unit. When we're testing clang_getCursor() after
2720 reparsing, don't remap unsaved files until the second parse. */
2721 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002722 Err = clang_parseTranslationUnit2(
2723 CIdx, argv[argc - 1],
2724 argv + num_unsaved_files + 1 + NumFilenames,
2725 argc - num_unsaved_files - 2 - NumFilenames,
2726 unsaved_files,
2727 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002728
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002729 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002730 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002731 describeLibclangFailure(Err);
2732 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002733 return -1;
2734 }
2735
2736 if (checkForErrors(TU) != 0)
2737 return -1;
2738
2739 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002740 if (Repeats > 1) {
2741 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2742 clang_defaultReparseOptions(TU));
2743 if (Err != CXError_Success) {
2744 describeLibclangFailure(Err);
2745 clang_disposeTranslationUnit(TU);
2746 return 1;
2747 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002748 }
2749
2750 if (checkForErrors(TU) != 0)
2751 return -1;
2752
2753 for (FI = 0; FI < NumFilenames; ++FI) {
2754 CXFile file = clang_getFile(TU, Filenames[FI]);
2755 if (!file)
2756 continue;
2757
2758 if (checkForErrors(TU) != 0)
2759 return -1;
2760
2761 if (I + 1 == Repeats) {
2762 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2763 clang_findIncludesInFile(TU, file, visitor);
2764
2765 if (checkForErrors(TU) != 0)
2766 return -1;
2767 }
2768 }
2769 }
2770
2771 PrintDiagnostics(TU);
2772 clang_disposeTranslationUnit(TU);
2773 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002774 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002775 free_remapped_files(unsaved_files, num_unsaved_files);
2776 return 0;
2777}
2778
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002779#define MAX_IMPORTED_ASTFILES 200
2780
2781typedef struct {
2782 char **filenames;
2783 unsigned num_files;
2784} ImportedASTFilesData;
2785
2786static ImportedASTFilesData *importedASTs_create() {
2787 ImportedASTFilesData *p;
2788 p = malloc(sizeof(ImportedASTFilesData));
2789 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2790 p->num_files = 0;
2791 return p;
2792}
2793
2794static void importedASTs_dispose(ImportedASTFilesData *p) {
2795 unsigned i;
2796 if (!p)
2797 return;
2798
2799 for (i = 0; i < p->num_files; ++i)
2800 free(p->filenames[i]);
2801 free(p->filenames);
2802 free(p);
2803}
2804
2805static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2806 unsigned i;
2807 assert(p && file);
2808 for (i = 0; i < p->num_files; ++i)
2809 if (strcmp(file, p->filenames[i]) == 0)
2810 return;
2811 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2812 p->filenames[p->num_files++] = strdup(file);
2813}
2814
Nico Weberdf686022014-05-07 21:09:42 +00002815typedef struct IndexDataStringList_ {
2816 struct IndexDataStringList_ *next;
2817 char data[1]; /* Dynamically sized. */
2818} IndexDataStringList;
2819
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002820typedef struct {
2821 const char *check_prefix;
2822 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002823 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002824 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002825 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002826 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002827 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002828 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002829} IndexData;
2830
Nico Weberdf686022014-05-07 21:09:42 +00002831static void free_client_data(IndexData *index_data) {
2832 IndexDataStringList *node = index_data->strings;
2833 while (node) {
2834 IndexDataStringList *next = node->next;
2835 free(node);
2836 node = next;
2837 }
2838 index_data->strings = NULL;
2839}
2840
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002841static void printCheck(IndexData *data) {
2842 if (data->check_prefix) {
2843 if (data->first_check_printed) {
2844 printf("// %s-NEXT: ", data->check_prefix);
2845 } else {
2846 printf("// %s : ", data->check_prefix);
2847 data->first_check_printed = 1;
2848 }
2849 }
2850}
2851
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002852static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002853 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002854 printf("%s", clang_getCString(filename));
2855 clang_disposeString(filename);
2856}
2857
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002858static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2859 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002860 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002861 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002862 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002863 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002864 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002865
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002866 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002867 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2868 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002869 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002870 return;
2871 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002872 if (!file) {
2873 printf("<no idxfile>");
2874 return;
2875 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002876 filename = clang_getFileName((CXFile)file);
2877 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002878 if (strcmp(cname, index_data->main_filename) == 0)
2879 isMainFile = 1;
2880 else
2881 isMainFile = 0;
2882 clang_disposeString(filename);
2883
2884 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002885 printCXIndexFile(file);
2886 printf(":");
2887 }
2888 printf("%d:%d", line, column);
2889}
2890
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002891static unsigned digitCount(unsigned val) {
2892 unsigned c = 1;
2893 while (1) {
2894 if (val < 10)
2895 return c;
2896 ++c;
2897 val /= 10;
2898 }
2899}
2900
Nico Weberdf686022014-05-07 21:09:42 +00002901static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2902 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002903 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002904 IndexData *index_data;
2905 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002906 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002907 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002908 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002909 unsigned line, column;
2910
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002911 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002912 if (!name)
2913 name = "<anon-tag>";
2914
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002915 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002916
2917 node =
2918 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2919 digitCount(line) + digitCount(column) + 2);
2920 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002921 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002922
2923 /* Remember string so it can be freed later. */
2924 index_data = (IndexData *)client_data;
2925 node->next = index_data->strings;
2926 index_data->strings = node;
2927
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002928 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002929}
2930
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002931static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2932 CXIdxClientContainer container;
2933 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002934 if (!container)
2935 printf("[<<NULL>>]");
2936 else
2937 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002938}
2939
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002940static const char *getEntityKindString(CXIdxEntityKind kind) {
2941 switch (kind) {
2942 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2943 case CXIdxEntity_Typedef: return "typedef";
2944 case CXIdxEntity_Function: return "function";
2945 case CXIdxEntity_Variable: return "variable";
2946 case CXIdxEntity_Field: return "field";
2947 case CXIdxEntity_EnumConstant: return "enumerator";
2948 case CXIdxEntity_ObjCClass: return "objc-class";
2949 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2950 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002951 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2952 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002953 case CXIdxEntity_ObjCProperty: return "objc-property";
2954 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2955 case CXIdxEntity_Enum: return "enum";
2956 case CXIdxEntity_Struct: return "struct";
2957 case CXIdxEntity_Union: return "union";
2958 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002959 case CXIdxEntity_CXXNamespace: return "namespace";
2960 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2961 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2962 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2963 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2964 case CXIdxEntity_CXXConstructor: return "constructor";
2965 case CXIdxEntity_CXXDestructor: return "destructor";
2966 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2967 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002968 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002969 }
2970 assert(0 && "Garbage entity kind");
2971 return 0;
2972}
2973
2974static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2975 switch (kind) {
2976 case CXIdxEntity_NonTemplate: return "";
2977 case CXIdxEntity_Template: return "-template";
2978 case CXIdxEntity_TemplatePartialSpecialization:
2979 return "-template-partial-spec";
2980 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002981 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002982 assert(0 && "Garbage entity kind");
2983 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002984}
2985
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002986static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2987 switch (kind) {
2988 case CXIdxEntityLang_None: return "<none>";
2989 case CXIdxEntityLang_C: return "C";
2990 case CXIdxEntityLang_ObjC: return "ObjC";
2991 case CXIdxEntityLang_CXX: return "C++";
2992 }
2993 assert(0 && "Garbage language kind");
2994 return 0;
2995}
2996
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002997static void printEntityInfo(const char *cb,
2998 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002999 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003000 const char *name;
3001 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003002 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003003 index_data = (IndexData *)client_data;
3004 printCheck(index_data);
3005
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00003006 if (!info) {
3007 printf("%s: <<NULL>>", cb);
3008 return;
3009 }
3010
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003011 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003012 if (!name)
3013 name = "<anon-tag>";
3014
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003015 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
3016 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003017 printf(" | name: %s", name);
3018 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00003019 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003020
3021 for (i = 0; i != info->numAttributes; ++i) {
3022 const CXIdxAttrInfo *Attr = info->attributes[i];
3023 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003024 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003025 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003026}
3027
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003028static void printBaseClassInfo(CXClientData client_data,
3029 const CXIdxBaseClassInfo *info) {
3030 printEntityInfo(" <base>", client_data, info->base);
3031 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003032 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003033 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003034 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003035}
3036
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003037static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3038 CXClientData client_data) {
3039 unsigned i;
3040 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3041 printEntityInfo(" <protocol>", client_data,
3042 ProtoInfo->protocols[i]->protocol);
3043 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003044 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003045 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003046 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003047 printf("\n");
3048 }
3049}
3050
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003051static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003052 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003053 CXString str;
3054 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003055 unsigned numDiags, i;
3056 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003057 IndexData *index_data;
3058 index_data = (IndexData *)client_data;
3059 printCheck(index_data);
3060
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003061 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3062 for (i = 0; i != numDiags; ++i) {
3063 diag = clang_getDiagnosticInSet(diagSet, i);
3064 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3065 cstr = clang_getCString(str);
3066 printf("[diagnostic]: %s\n", cstr);
3067 clang_disposeString(str);
3068
3069 if (getenv("CINDEXTEST_FAILONERROR") &&
3070 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3071 index_data->fail_for_error = 1;
3072 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003073 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003074}
3075
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003076static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3077 CXFile file, void *reserved) {
3078 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003079 CXString filename;
3080
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003081 index_data = (IndexData *)client_data;
3082 printCheck(index_data);
3083
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003084 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003085 index_data->main_filename = clang_getCString(filename);
3086 clang_disposeString(filename);
3087
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003088 printf("[enteredMainFile]: ");
3089 printCXIndexFile((CXIdxClientFile)file);
3090 printf("\n");
3091
3092 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003093}
3094
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003095static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003096 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003097 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003098 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003099 index_data = (IndexData *)client_data;
3100 printCheck(index_data);
3101
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003102 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003103 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003104 printf(" | name: \"%s\"", info->filename);
3105 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003106 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003107 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003108 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003109
3110 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3111 if (Mod) {
3112 CXString str = clang_Module_getFullName(Mod);
3113 const char *cstr = clang_getCString(str);
3114 printf(" | module: %s", cstr);
3115 clang_disposeString(str);
3116 }
3117
3118 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003119
3120 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003121}
3122
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003123static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3124 const CXIdxImportedASTFileInfo *info) {
3125 IndexData *index_data;
3126 index_data = (IndexData *)client_data;
3127 printCheck(index_data);
3128
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003129 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003130 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003131 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3132 clang_disposeString(filename);
3133 }
3134
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003135 printf("[importedASTFile]: ");
3136 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003137 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003138 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003139 printf(" | loc: ");
3140 printCXIndexLoc(info->loc, client_data);
3141 printf(" | name: \"%s\"", clang_getCString(name));
3142 printf(" | isImplicit: %d\n", info->isImplicit);
3143 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003144 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003145 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003146 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003147 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003148
3149 return (CXIdxClientFile)info->file;
3150}
3151
Nico Weber8d19dff2014-05-07 21:05:22 +00003152static CXIdxClientContainer
3153index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003154 IndexData *index_data;
3155 index_data = (IndexData *)client_data;
3156 printCheck(index_data);
3157
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003158 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003159 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003160}
3161
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003162static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003163 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003164 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003165 const CXIdxObjCCategoryDeclInfo *CatInfo;
3166 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003167 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003168 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003169 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003170 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003171 index_data = (IndexData *)client_data;
3172
3173 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3174 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003175 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003176 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003177 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003178 printf(" | semantic-container: ");
3179 printCXIndexContainer(info->semanticContainer);
3180 printf(" | lexical-container: ");
3181 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003182 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003183 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003184 if (info->flags & CXIdxDeclFlag_Skipped) {
3185 assert(!info->isContainer);
3186 printf(" | isContainer: skipped");
3187 } else {
3188 printf(" | isContainer: %d", info->isContainer);
3189 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003190 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003191
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003192 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003193 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003194 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003195 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003196 printf("\n");
3197 }
3198
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003199 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3200 const char *kindName = 0;
3201 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3202 switch (K) {
3203 case CXIdxObjCContainer_ForwardRef:
3204 kindName = "forward-ref"; break;
3205 case CXIdxObjCContainer_Interface:
3206 kindName = "interface"; break;
3207 case CXIdxObjCContainer_Implementation:
3208 kindName = "implementation"; break;
3209 }
3210 printCheck(index_data);
3211 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3212 }
3213
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003214 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003215 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3216 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003217 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003218 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003219 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003220 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003221 printf("\n");
3222 }
3223
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003224 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3225 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003226 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003227 printf("\n");
3228 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003229 }
3230
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003231 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3232 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003233 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003234
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003235 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3236 if (PropInfo->getter) {
3237 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3238 printf("\n");
3239 }
3240 if (PropInfo->setter) {
3241 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3242 printf("\n");
3243 }
3244 }
3245
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003246 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3247 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3248 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3249 printf("\n");
3250 }
3251 }
3252
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003253 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003254 clang_index_setClientContainer(
3255 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003256 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003257}
3258
3259static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003260 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003261 printEntityInfo("[indexEntityReference]", client_data,
3262 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003263 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003264 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003265 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003266 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003267 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003268 printf(" | container: ");
3269 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003270 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003271 switch (info->kind) {
3272 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003273 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003274 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003275 printf("\n");
3276}
3277
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003278static int index_abortQuery(CXClientData client_data, void *reserved) {
3279 IndexData *index_data;
3280 index_data = (IndexData *)client_data;
3281 return index_data->abort;
3282}
3283
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003284static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003285 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003286 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003287 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003288 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003289 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003290 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003291 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003292 index_indexEntityReference
3293};
3294
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003295static unsigned getIndexOptions(void) {
3296 unsigned index_opts;
3297 index_opts = 0;
3298 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3299 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3300 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3301 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003302 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3303 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003304
3305 return index_opts;
3306}
3307
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003308static int index_compile_args(int num_args, const char **args,
3309 CXIndexAction idxAction,
3310 ImportedASTFilesData *importedASTs,
3311 const char *check_prefix) {
3312 IndexData index_data;
3313 unsigned index_opts;
3314 int result;
3315
3316 if (num_args == 0) {
3317 fprintf(stderr, "no compiler arguments\n");
3318 return -1;
3319 }
3320
3321 index_data.check_prefix = check_prefix;
3322 index_data.first_check_printed = 0;
3323 index_data.fail_for_error = 0;
3324 index_data.abort = 0;
3325 index_data.main_filename = "";
3326 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003327 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003328 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003329
3330 index_opts = getIndexOptions();
3331 result = clang_indexSourceFile(idxAction, &index_data,
3332 &IndexCB,sizeof(IndexCB), index_opts,
3333 0, args, num_args, 0, 0, 0,
3334 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003335 if (result != CXError_Success)
3336 describeLibclangFailure(result);
3337
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003338 if (index_data.fail_for_error)
3339 result = -1;
3340
Nico Weberdf686022014-05-07 21:09:42 +00003341 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003342 return result;
3343}
3344
3345static int index_ast_file(const char *ast_file,
3346 CXIndex Idx,
3347 CXIndexAction idxAction,
3348 ImportedASTFilesData *importedASTs,
3349 const char *check_prefix) {
3350 CXTranslationUnit TU;
3351 IndexData index_data;
3352 unsigned index_opts;
3353 int result;
3354
3355 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3356 return -1;
3357
3358 index_data.check_prefix = check_prefix;
3359 index_data.first_check_printed = 0;
3360 index_data.fail_for_error = 0;
3361 index_data.abort = 0;
3362 index_data.main_filename = "";
3363 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003364 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003365 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003366
3367 index_opts = getIndexOptions();
3368 result = clang_indexTranslationUnit(idxAction, &index_data,
3369 &IndexCB,sizeof(IndexCB),
3370 index_opts, TU);
3371 if (index_data.fail_for_error)
3372 result = -1;
3373
3374 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003375 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003376 return result;
3377}
3378
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003379static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003380 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003381 CXIndex Idx;
3382 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003383 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003384 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003385
3386 check_prefix = 0;
3387 if (argc > 0) {
3388 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3389 check_prefix = argv[0] + strlen("-check-prefix=");
3390 ++argv;
3391 --argc;
3392 }
3393 }
3394
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003395 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003396 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003397 fprintf(stderr, "Could not create Index\n");
3398 return 1;
3399 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003400 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003401 importedASTs = 0;
3402 if (full)
3403 importedASTs = importedASTs_create();
3404
3405 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3406 if (result != 0)
3407 goto finished;
3408
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003409 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003410 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003411 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3412 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3413 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003414 }
3415 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003416
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003417finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003418 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003419 clang_IndexAction_dispose(idxAction);
3420 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003421 return result;
3422}
3423
3424static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003425 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003426 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003427 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003428 int result;
3429
3430 check_prefix = 0;
3431 if (argc > 0) {
3432 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3433 check_prefix = argv[0] + strlen("-check-prefix=");
3434 ++argv;
3435 --argc;
3436 }
3437 }
3438
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003439 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003440 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003441 fprintf(stderr, "Could not create Index\n");
3442 return 1;
3443 }
3444 idxAction = clang_IndexAction_create(Idx);
3445
3446 result = index_ast_file(argv[0], Idx, idxAction,
3447 /*importedASTs=*/0, check_prefix);
3448
3449 clang_IndexAction_dispose(idxAction);
3450 clang_disposeIndex(Idx);
3451 return result;
3452}
3453
3454static int index_compile_db(int argc, const char **argv) {
3455 const char *check_prefix;
3456 CXIndex Idx;
3457 CXIndexAction idxAction;
3458 int errorCode = 0;
3459
3460 check_prefix = 0;
3461 if (argc > 0) {
3462 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3463 check_prefix = argv[0] + strlen("-check-prefix=");
3464 ++argv;
3465 --argc;
3466 }
3467 }
3468
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003469 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003470 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003471 return -1;
3472 }
3473
3474 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003475 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003476 fprintf(stderr, "Could not create Index\n");
3477 return 1;
3478 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003479 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003480
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003481 {
3482 const char *database = argv[0];
3483 CXCompilationDatabase db = 0;
3484 CXCompileCommands CCmds = 0;
3485 CXCompileCommand CCmd;
3486 CXCompilationDatabase_Error ec;
3487 CXString wd;
3488#define MAX_COMPILE_ARGS 512
3489 CXString cxargs[MAX_COMPILE_ARGS];
3490 const char *args[MAX_COMPILE_ARGS];
3491 char *tmp;
3492 unsigned len;
3493 char *buildDir;
3494 int i, a, numCmds, numArgs;
3495
3496 len = strlen(database);
3497 tmp = (char *) malloc(len+1);
3498 memcpy(tmp, database, len+1);
3499 buildDir = dirname(tmp);
3500
3501 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3502
3503 if (db) {
3504
3505 if (ec!=CXCompilationDatabase_NoError) {
3506 printf("unexpected error %d code while loading compilation database\n", ec);
3507 errorCode = -1;
3508 goto cdb_end;
3509 }
3510
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003511 if (chdir(buildDir) != 0) {
3512 printf("Could not chdir to %s\n", buildDir);
3513 errorCode = -1;
3514 goto cdb_end;
3515 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003516
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003517 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003518 if (!CCmds) {
3519 printf("compilation db is empty\n");
3520 errorCode = -1;
3521 goto cdb_end;
3522 }
3523
3524 numCmds = clang_CompileCommands_getSize(CCmds);
3525
3526 if (numCmds==0) {
3527 fprintf(stderr, "should not get an empty compileCommand set\n");
3528 errorCode = -1;
3529 goto cdb_end;
3530 }
3531
3532 for (i=0; i<numCmds && errorCode == 0; ++i) {
3533 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3534
3535 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003536 if (chdir(clang_getCString(wd)) != 0) {
3537 printf("Could not chdir to %s\n", clang_getCString(wd));
3538 errorCode = -1;
3539 goto cdb_end;
3540 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003541 clang_disposeString(wd);
3542
3543 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3544 if (numArgs > MAX_COMPILE_ARGS){
3545 fprintf(stderr, "got more compile arguments than maximum\n");
3546 errorCode = -1;
3547 goto cdb_end;
3548 }
3549 for (a=0; a<numArgs; ++a) {
3550 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3551 args[a] = clang_getCString(cxargs[a]);
3552 }
3553
3554 errorCode = index_compile_args(numArgs, args, idxAction,
3555 /*importedASTs=*/0, check_prefix);
3556
3557 for (a=0; a<numArgs; ++a)
3558 clang_disposeString(cxargs[a]);
3559 }
3560 } else {
3561 printf("database loading failed with error code %d.\n", ec);
3562 errorCode = -1;
3563 }
3564
3565 cdb_end:
3566 clang_CompileCommands_dispose(CCmds);
3567 clang_CompilationDatabase_dispose(db);
3568 free(tmp);
3569
3570 }
3571
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003572 clang_IndexAction_dispose(idxAction);
3573 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003574 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003575}
3576
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003577int perform_token_annotation(int argc, const char **argv) {
3578 const char *input = argv[1];
3579 char *filename = 0;
3580 unsigned line, second_line;
3581 unsigned column, second_column;
3582 CXIndex CIdx;
3583 CXTranslationUnit TU = 0;
3584 int errorCode;
3585 struct CXUnsavedFile *unsaved_files = 0;
3586 int num_unsaved_files = 0;
3587 CXToken *tokens;
3588 unsigned num_tokens;
3589 CXSourceRange range;
3590 CXSourceLocation startLoc, endLoc;
3591 CXFile file = 0;
3592 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003593 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003594 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003595 unsigned i;
3596
3597 input += strlen("-test-annotate-tokens=");
3598 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3599 &second_line, &second_column)))
3600 return errorCode;
3601
Richard Smith1ea42eb2012-07-05 08:20:49 +00003602 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3603 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003604 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003605 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003606
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003607 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003608 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3609 argv + num_unsaved_files + 2,
3610 argc - num_unsaved_files - 3,
3611 unsaved_files,
3612 num_unsaved_files,
3613 getDefaultParsingOptions(), &TU);
3614 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003615 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003616 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003617 clang_disposeIndex(CIdx);
3618 free(filename);
3619 free_remapped_files(unsaved_files, num_unsaved_files);
3620 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003621 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003622 errorCode = 0;
3623
Richard Smith1ea42eb2012-07-05 08:20:49 +00003624 if (checkForErrors(TU) != 0) {
3625 errorCode = -1;
3626 goto teardown;
3627 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003628
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003629 if (getenv("CINDEXTEST_EDITING")) {
3630 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003631 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3632 clang_defaultReparseOptions(TU));
3633 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003634 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003635 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003636 errorCode = -1;
3637 goto teardown;
3638 }
3639 }
3640 }
3641
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003642 if (checkForErrors(TU) != 0) {
3643 errorCode = -1;
3644 goto teardown;
3645 }
3646
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003647 file = clang_getFile(TU, filename);
3648 if (!file) {
3649 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3650 errorCode = -1;
3651 goto teardown;
3652 }
3653
3654 startLoc = clang_getLocation(TU, file, line, column);
3655 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003656 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003657 column);
3658 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003659 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003660 }
3661
3662 endLoc = clang_getLocation(TU, file, second_line, second_column);
3663 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003664 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003665 second_line, second_column);
3666 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003667 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003668 }
3669
3670 range = clang_getRange(startLoc, endLoc);
3671 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003672
3673 if (checkForErrors(TU) != 0) {
3674 errorCode = -1;
3675 goto teardown;
3676 }
3677
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003678 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3679 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003680
3681 if (checkForErrors(TU) != 0) {
3682 errorCode = -1;
3683 goto teardown;
3684 }
3685
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003686 skipped_ranges = clang_getSkippedRanges(TU, file);
3687 for (i = 0; i != skipped_ranges->count; ++i) {
3688 unsigned start_line, start_column, end_line, end_column;
3689 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3690 0, &start_line, &start_column, 0);
3691 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3692 0, &end_line, &end_column, 0);
3693 printf("Skipping: ");
3694 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3695 printf("\n");
3696 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003697 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003698
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003699 for (i = 0; i != num_tokens; ++i) {
3700 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003701 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3702 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003703 unsigned start_line, start_column, end_line, end_column;
3704
3705 switch (clang_getTokenKind(tokens[i])) {
3706 case CXToken_Punctuation: kind = "Punctuation"; break;
3707 case CXToken_Keyword: kind = "Keyword"; break;
3708 case CXToken_Identifier: kind = "Identifier"; break;
3709 case CXToken_Literal: kind = "Literal"; break;
3710 case CXToken_Comment: kind = "Comment"; break;
3711 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003712 clang_getSpellingLocation(clang_getRangeStart(extent),
3713 0, &start_line, &start_column, 0);
3714 clang_getSpellingLocation(clang_getRangeEnd(extent),
3715 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003716 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003717 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003718 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003719 if (!clang_isInvalid(cursors[i].kind)) {
3720 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003721 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003722 }
3723 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003724 }
3725 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003726 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003727
3728 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003729 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003730 clang_disposeTranslationUnit(TU);
3731 clang_disposeIndex(CIdx);
3732 free(filename);
3733 free_remapped_files(unsaved_files, num_unsaved_files);
3734 return errorCode;
3735}
3736
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003737static int
3738perform_test_compilation_db(const char *database, int argc, const char **argv) {
3739 CXCompilationDatabase db;
3740 CXCompileCommands CCmds;
3741 CXCompileCommand CCmd;
3742 CXCompilationDatabase_Error ec;
3743 CXString wd;
3744 CXString arg;
3745 int errorCode = 0;
3746 char *tmp;
3747 unsigned len;
3748 char *buildDir;
3749 int i, j, a, numCmds, numArgs;
3750
3751 len = strlen(database);
3752 tmp = (char *) malloc(len+1);
3753 memcpy(tmp, database, len+1);
3754 buildDir = dirname(tmp);
3755
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003756 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003757
3758 if (db) {
3759
3760 if (ec!=CXCompilationDatabase_NoError) {
3761 printf("unexpected error %d code while loading compilation database\n", ec);
3762 errorCode = -1;
3763 goto cdb_end;
3764 }
3765
3766 for (i=0; i<argc && errorCode==0; ) {
3767 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003768 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003769
3770 if (!CCmds) {
3771 printf("file %s not found in compilation db\n", argv[i+1]);
3772 errorCode = -1;
3773 break;
3774 }
3775
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003776 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003777
3778 if (numCmds==0) {
3779 fprintf(stderr, "should not get an empty compileCommand set for file"
3780 " '%s'\n", argv[i+1]);
3781 errorCode = -1;
3782 break;
3783 }
3784
3785 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003786 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003787
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003788 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003789 printf("workdir:'%s'", clang_getCString(wd));
3790 clang_disposeString(wd);
3791
3792 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003793 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003794 for (a=0; a<numArgs; ++a) {
3795 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003796 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003797 printf("%s", clang_getCString(arg));
3798 clang_disposeString(arg);
3799 }
3800 printf("'\n");
3801 }
3802
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003803 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003804
3805 i += 2;
3806 }
3807 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003808 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003809 } else {
3810 printf("database loading failed with error code %d.\n", ec);
3811 errorCode = -1;
3812 }
3813
3814cdb_end:
3815 free(tmp);
3816
3817 return errorCode;
3818}
3819
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003820/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003821/* USR printing. */
3822/******************************************************************************/
3823
3824static int insufficient_usr(const char *kind, const char *usage) {
3825 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3826 return 1;
3827}
3828
3829static unsigned isUSR(const char *s) {
3830 return s[0] == 'c' && s[1] == ':';
3831}
3832
3833static int not_usr(const char *s, const char *arg) {
3834 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3835 return 1;
3836}
3837
3838static void print_usr(CXString usr) {
3839 const char *s = clang_getCString(usr);
3840 printf("%s\n", s);
3841 clang_disposeString(usr);
3842}
3843
3844static void display_usrs() {
3845 fprintf(stderr, "-print-usrs options:\n"
3846 " ObjCCategory <class name> <category name>\n"
3847 " ObjCClass <class name>\n"
3848 " ObjCIvar <ivar name> <class USR>\n"
3849 " ObjCMethod <selector> [0=class method|1=instance method] "
3850 "<class USR>\n"
3851 " ObjCProperty <property name> <class USR>\n"
3852 " ObjCProtocol <protocol name>\n");
3853}
3854
3855int print_usrs(const char **I, const char **E) {
3856 while (I != E) {
3857 const char *kind = *I;
3858 unsigned len = strlen(kind);
3859 switch (len) {
3860 case 8:
3861 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3862 if (I + 2 >= E)
3863 return insufficient_usr(kind, "<ivar name> <class USR>");
3864 if (!isUSR(I[2]))
3865 return not_usr("<class USR>", I[2]);
3866 else {
3867 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003868 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003869 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003870 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3871 }
3872
3873 I += 3;
3874 continue;
3875 }
3876 break;
3877 case 9:
3878 if (memcmp(kind, "ObjCClass", 9) == 0) {
3879 if (I + 1 >= E)
3880 return insufficient_usr(kind, "<class name>");
3881 print_usr(clang_constructUSR_ObjCClass(I[1]));
3882 I += 2;
3883 continue;
3884 }
3885 break;
3886 case 10:
3887 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3888 if (I + 3 >= E)
3889 return insufficient_usr(kind, "<method selector> "
3890 "[0=class method|1=instance method] <class USR>");
3891 if (!isUSR(I[3]))
3892 return not_usr("<class USR>", I[3]);
3893 else {
3894 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003895 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003896 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003897 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3898 }
3899 I += 4;
3900 continue;
3901 }
3902 break;
3903 case 12:
3904 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3905 if (I + 2 >= E)
3906 return insufficient_usr(kind, "<class name> <category name>");
3907 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3908 I += 3;
3909 continue;
3910 }
3911 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3912 if (I + 1 >= E)
3913 return insufficient_usr(kind, "<protocol name>");
3914 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3915 I += 2;
3916 continue;
3917 }
3918 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3919 if (I + 2 >= E)
3920 return insufficient_usr(kind, "<property name> <class USR>");
3921 if (!isUSR(I[2]))
3922 return not_usr("<class USR>", I[2]);
3923 else {
3924 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003925 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003926 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003927 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3928 }
3929 I += 3;
3930 continue;
3931 }
3932 break;
3933 default:
3934 break;
3935 }
3936 break;
3937 }
3938
3939 if (I != E) {
3940 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3941 display_usrs();
3942 return 1;
3943 }
3944 return 0;
3945}
3946
3947int print_usrs_file(const char *file_name) {
3948 char line[2048];
3949 const char *args[128];
3950 unsigned numChars = 0;
3951
3952 FILE *fp = fopen(file_name, "r");
3953 if (!fp) {
3954 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3955 return 1;
3956 }
3957
3958 /* This code is not really all that safe, but it works fine for testing. */
3959 while (!feof(fp)) {
3960 char c = fgetc(fp);
3961 if (c == '\n') {
3962 unsigned i = 0;
3963 const char *s = 0;
3964
3965 if (numChars == 0)
3966 continue;
3967
3968 line[numChars] = '\0';
3969 numChars = 0;
3970
3971 if (line[0] == '/' && line[1] == '/')
3972 continue;
3973
3974 s = strtok(line, " ");
3975 while (s) {
3976 args[i] = s;
3977 ++i;
3978 s = strtok(0, " ");
3979 }
3980 if (print_usrs(&args[0], &args[i]))
3981 return 1;
3982 }
3983 else
3984 line[numChars++] = c;
3985 }
3986
3987 fclose(fp);
3988 return 0;
3989}
3990
3991/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003992/* Command line processing. */
3993/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003994int write_pch_file(const char *filename, int argc, const char *argv[]) {
3995 CXIndex Idx;
3996 CXTranslationUnit TU;
3997 struct CXUnsavedFile *unsaved_files = 0;
3998 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003999 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00004000 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00004001
Stefanus Du Toitb3318502013-03-01 21:41:22 +00004002 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00004003
4004 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
4005 clang_disposeIndex(Idx);
4006 return -1;
4007 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004008
4009 Err = clang_parseTranslationUnit2(
4010 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
4011 unsaved_files, num_unsaved_files,
4012 CXTranslationUnit_Incomplete |
4013 CXTranslationUnit_DetailedPreprocessingRecord |
4014 CXTranslationUnit_ForSerialization,
4015 &TU);
4016 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00004017 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004018 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00004019 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004020 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00004021 clang_disposeIndex(Idx);
4022 return 1;
4023 }
4024
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004025 switch (clang_saveTranslationUnit(TU, filename,
4026 clang_defaultSaveOptions(TU))) {
4027 case CXSaveError_None:
4028 break;
4029
4030 case CXSaveError_TranslationErrors:
4031 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4032 filename);
4033 result = 2;
4034 break;
4035
4036 case CXSaveError_InvalidTU:
4037 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4038 filename);
4039 result = 3;
4040 break;
4041
4042 case CXSaveError_Unknown:
4043 default:
4044 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4045 result = 1;
4046 break;
4047 }
4048
Douglas Gregore9386682010-08-13 05:36:37 +00004049 clang_disposeTranslationUnit(TU);
4050 free_remapped_files(unsaved_files, num_unsaved_files);
4051 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004052 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004053}
4054
4055/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004056/* Serialized diagnostics. */
4057/******************************************************************************/
4058
4059static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4060 switch (error) {
4061 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4062 case CXLoadDiag_None: break;
4063 case CXLoadDiag_Unknown: return "Unknown";
4064 case CXLoadDiag_InvalidFile: return "Invalid File";
4065 }
4066 return "None";
4067}
4068
4069static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4070 switch (severity) {
4071 case CXDiagnostic_Note: return "note";
4072 case CXDiagnostic_Error: return "error";
4073 case CXDiagnostic_Fatal: return "fatal";
4074 case CXDiagnostic_Ignored: return "ignored";
4075 case CXDiagnostic_Warning: return "warning";
4076 }
4077 return "unknown";
4078}
4079
4080static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004081 if (indent == 0)
4082 return;
4083 fprintf(stderr, "+");
4084 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004085 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004086 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004087 --indent;
4088 }
4089}
4090
4091static void printLocation(CXSourceLocation L) {
4092 CXFile File;
4093 CXString FileName;
4094 unsigned line, column, offset;
4095
4096 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4097 FileName = clang_getFileName(File);
4098
4099 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4100 clang_disposeString(FileName);
4101}
4102
4103static void printRanges(CXDiagnostic D, unsigned indent) {
4104 unsigned i, n = clang_getDiagnosticNumRanges(D);
4105
4106 for (i = 0; i < n; ++i) {
4107 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004108 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004109 Start = clang_getRangeStart(SR);
4110 End = clang_getRangeEnd(SR);
4111
4112 printIndent(indent);
4113 fprintf(stderr, "Range: ");
4114 printLocation(Start);
4115 fprintf(stderr, " ");
4116 printLocation(End);
4117 fprintf(stderr, "\n");
4118 }
4119}
4120
4121static void printFixIts(CXDiagnostic D, unsigned indent) {
4122 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004123 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004124 for (i = 0 ; i < n; ++i) {
4125 CXSourceRange ReplacementRange;
4126 CXString text;
4127 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4128
4129 printIndent(indent);
4130 fprintf(stderr, "FIXIT: (");
4131 printLocation(clang_getRangeStart(ReplacementRange));
4132 fprintf(stderr, " - ");
4133 printLocation(clang_getRangeEnd(ReplacementRange));
4134 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4135 clang_disposeString(text);
4136 }
4137}
4138
4139static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004140 unsigned i, n;
4141
Ted Kremenekd010ba42011-11-10 08:43:12 +00004142 if (!Diags)
4143 return;
4144
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004145 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004146 for (i = 0; i < n; ++i) {
4147 CXSourceLocation DiagLoc;
4148 CXDiagnostic D;
4149 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004150 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004151 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004152 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004153
4154 D = clang_getDiagnosticInSet(Diags, i);
4155 DiagLoc = clang_getDiagnosticLocation(D);
4156 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4157 FileName = clang_getFileName(File);
4158 DiagSpelling = clang_getDiagnosticSpelling(D);
4159
4160 printIndent(indent);
4161
4162 fprintf(stderr, "%s:%d:%d: %s: %s",
4163 clang_getCString(FileName),
4164 line,
4165 column,
4166 getSeverityString(clang_getDiagnosticSeverity(D)),
4167 clang_getCString(DiagSpelling));
4168
4169 DiagOption = clang_getDiagnosticOption(D, 0);
4170 DiagOptionStr = clang_getCString(DiagOption);
4171 if (DiagOptionStr) {
4172 fprintf(stderr, " [%s]", DiagOptionStr);
4173 }
4174
Ted Kremenek26a6d492012-04-12 00:03:31 +00004175 DiagCat = clang_getDiagnosticCategoryText(D);
4176 DiagCatStr = clang_getCString(DiagCat);
4177 if (DiagCatStr) {
4178 fprintf(stderr, " [%s]", DiagCatStr);
4179 }
4180
Ted Kremenekd010ba42011-11-10 08:43:12 +00004181 fprintf(stderr, "\n");
4182
4183 printRanges(D, indent);
4184 printFixIts(D, indent);
4185
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004186 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004187 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4188
4189 clang_disposeString(FileName);
4190 clang_disposeString(DiagSpelling);
4191 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004192 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004193 }
4194}
4195
4196static int read_diagnostics(const char *filename) {
4197 enum CXLoadDiag_Error error;
4198 CXString errorString;
4199 CXDiagnosticSet Diags = 0;
4200
4201 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4202 if (!Diags) {
4203 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4204 getDiagnosticCodeStr(error),
4205 clang_getCString(errorString));
4206 clang_disposeString(errorString);
4207 return 1;
4208 }
4209
4210 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004211 fprintf(stderr, "Number of diagnostics: %d\n",
4212 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004213 clang_disposeDiagnosticSet(Diags);
4214 return 0;
4215}
4216
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004217static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004218 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004219 return 0;
4220}
4221
Ted Kremenekd010ba42011-11-10 08:43:12 +00004222/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004223/* Command line processing. */
4224/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004225
Douglas Gregor720d0052010-01-20 21:32:04 +00004226static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004227 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004228 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004229 if (strcmp(s, "-usrs") == 0)
4230 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004231 if (strncmp(s, "-memory-usage", 13) == 0)
4232 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004233 return NULL;
4234}
4235
Ted Kremenekef3339b2009-11-17 18:09:14 +00004236static void print_usage(void) {
4237 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004238 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004239 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004240 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004241 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4242 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004243 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4244 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004245 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004246 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004247 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004248 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004249 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004250 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004251 "[FileCheck prefix]\n");
4252 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004253 " c-index-test -test-load-tu <AST file> <symbol filter> "
4254 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004255 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4256 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004257 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004258 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004259 " c-index-test -test-load-source-memory-usage "
4260 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004261 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4262 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004263 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004264 " c-index-test -test-load-source-usrs-memory-usage "
4265 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004266 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4267 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004268 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004269 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004270 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004271 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004272 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004273 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004274 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004275 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004276 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004277 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004278 " c-index-test -write-pch <file> <compiler arguments>\n");
4279 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004280 " c-index-test -compilation-db [lookup <filename>] database\n");
4281 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004282 " c-index-test -print-build-session-timestamp\n");
4283 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004284 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004285 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004286 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004287 " all - load all symbols, including those from PCH\n"
4288 " local - load all symbols except those in PCH\n"
4289 " category - only load ObjC categories (non-PCH)\n"
4290 " interface - only load ObjC interfaces (non-PCH)\n"
4291 " protocol - only load ObjC protocols (non-PCH)\n"
4292 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004293 " typedef - only load typdefs (non-PCH)\n"
4294 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004295}
4296
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004297/***/
4298
4299int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004300 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004301 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4302 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004303 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004304 return perform_code_completion(argc, argv, 0);
4305 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4306 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004307 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004308 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4309 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4310 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4311 inspect_evaluate_cursor);
4312 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4313 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4314 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004315 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4316 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004317 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4318 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004319 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004320 return index_file(argc - 2, argv + 2, /*full=*/0);
4321 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4322 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004323 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4324 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004325 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4326 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004327 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004328 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004329 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004330 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4331 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004332 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004333 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4334 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4335 if (I) {
4336 int trials = atoi(argv[2]);
4337 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4338 NULL);
4339 }
4340 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004341 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004342 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004343
4344 PostVisitTU postVisit = 0;
4345 if (strstr(argv[1], "-memory-usage"))
4346 postVisit = PrintMemoryUsage;
4347
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004348 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004349 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4350 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004351 }
4352 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004353 return perform_file_scan(argv[2], argv[3],
4354 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004355 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4356 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004357 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4358 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4359 PrintInclusionStack);
4360 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4361 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4362 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004363 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4364 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4365 NULL);
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004366 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4367 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4368 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004369 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004370 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004371 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004372 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4373 return perform_test_load_source(argc - 2, argv + 2, "all",
4374 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004375 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4376 return perform_test_load_source(argc - 2, argv + 2, "all",
4377 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004378 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4379 return perform_test_load_source(argc - 2, argv + 2, "all",
4380 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004381 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4382 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004383 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4384 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004385 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4386 if (argc > 2)
4387 return print_usrs(argv + 2, argv + argc);
4388 else {
4389 display_usrs();
4390 return 1;
4391 }
4392 }
4393 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4394 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004395 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4396 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004397 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4398 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004399 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4400 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004401
Ted Kremenekef3339b2009-11-17 18:09:14 +00004402 print_usage();
4403 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004404}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004405
4406/***/
4407
4408/* We intentionally run in a separate thread to ensure we at least minimal
4409 * testing of a multithreaded environment (for example, having a reduced stack
4410 * size). */
4411
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004412typedef struct thread_info {
4413 int argc;
4414 const char **argv;
4415 int result;
4416} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004417void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004418 thread_info *client_data = client_data_v;
4419 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004420}
4421
4422static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004423 /* stdout, and surprisingly even stderr, are not always flushed on process
4424 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004425 fflush(stdout);
4426 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004427}
4428
4429int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004430 thread_info client_data;
4431
Reid Klecknere931c062014-06-05 00:13:43 +00004432 atexit(flush_atexit);
4433
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004434#ifdef CLANG_HAVE_LIBXML
4435 LIBXML_TEST_VERSION
4436#endif
4437
Douglas Gregorf428bf82010-10-27 16:00:01 +00004438 if (getenv("CINDEXTEST_NOTHREADS"))
4439 return cindextest_main(argc, argv);
4440
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004441 client_data.argc = argc;
4442 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004443 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004444 return client_data.result;
4445}