blob: f50c8855f60fe4e5da8835ee852db649f20f237d [file] [log] [blame]
Steve Naroff69b10fd2009-09-01 15:55:40 +00001/* c-index-test.c */
Steve Naroffa1c72842009-08-28 15:28:48 +00002
3#include "clang-c/Index.h"
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004#include "clang-c/CXCompilationDatabase.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +00005#include "clang-c/BuildSystem.h"
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00006#include "llvm/Config/config.h"
Douglas Gregor49f67ce2010-08-26 13:48:20 +00007#include <ctype.h>
Douglas Gregor9eb77012009-11-07 00:00:49 +00008#include <stdlib.h>
Steve Naroff1054e602009-08-31 00:59:03 +00009#include <stdio.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000010#include <string.h>
Douglas Gregor082c3e62010-01-15 19:40:17 +000011#include <assert.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000012
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +000013#ifdef CLANG_HAVE_LIBXML
14#include <libxml/parser.h>
15#include <libxml/relaxng.h>
16#include <libxml/xmlerror.h>
17#endif
18
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +000019#ifdef _WIN32
20# include <direct.h>
21#else
22# include <unistd.h>
23#endif
24
Ted Kremenek1cd27d52009-11-17 18:13:31 +000025/******************************************************************************/
26/* Utility functions. */
27/******************************************************************************/
28
John Thompsonde258b52009-10-27 13:42:56 +000029#ifdef _MSC_VER
30char *basename(const char* path)
31{
32 char* base1 = (char*)strrchr(path, '/');
33 char* base2 = (char*)strrchr(path, '\\');
34 if (base1 && base2)
35 return((base1 > base2) ? base1 + 1 : base2 + 1);
36 else if (base1)
37 return(base1 + 1);
38 else if (base2)
39 return(base2 + 1);
40
41 return((char*)path);
42}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000043char *dirname(char* path)
44{
45 char* base1 = (char*)strrchr(path, '/');
46 char* base2 = (char*)strrchr(path, '\\');
47 if (base1 && base2)
48 if (base1 > base2)
49 *base1 = 0;
50 else
51 *base2 = 0;
52 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000053 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000054 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000055 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000056
57 return path;
58}
John Thompsonde258b52009-10-27 13:42:56 +000059#else
Steve Naroffa7753c42009-09-24 20:03:06 +000060extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000061extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000062#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000063
Douglas Gregorf2430ba2010-07-25 17:39:21 +000064/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000065static unsigned getDefaultParsingOptions() {
66 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
67
68 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000069 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000070 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
71 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000072 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
73 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000074 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
75 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000076 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
77 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000078
79 return options;
80}
81
Patrik Hagglund55701d22014-02-17 11:54:08 +000082/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000083static int checkForErrors(CXTranslationUnit TU);
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085static void describeLibclangFailure(enum CXErrorCode Err) {
86 switch (Err) {
87 case CXError_Success:
88 fprintf(stderr, "Success\n");
89 return;
90
91 case CXError_Failure:
92 fprintf(stderr, "Failure (no details available)\n");
93 return;
94
95 case CXError_Crashed:
96 fprintf(stderr, "Failure: libclang crashed\n");
97 return;
98
99 case CXError_InvalidArguments:
100 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
101 return;
102
103 case CXError_ASTReadError:
104 fprintf(stderr, "Failure: AST deserialization error occurred\n");
105 return;
106 }
107}
108
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000109static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
110 unsigned end_line, unsigned end_column) {
111 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000112 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000113}
114
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000115static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
116 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000117 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
118 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000119 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000120 describeLibclangFailure(Err);
121 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000122 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000123 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000124 return 1;
125}
126
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000127void free_remapped_files(struct CXUnsavedFile *unsaved_files,
128 int num_unsaved_files) {
129 int i;
130 for (i = 0; i != num_unsaved_files; ++i) {
131 free((char *)unsaved_files[i].Filename);
132 free((char *)unsaved_files[i].Contents);
133 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000134 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000135}
136
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000137static int parse_remapped_files_with_opt(const char *opt_name,
138 int argc, const char **argv,
139 int start_arg,
140 struct CXUnsavedFile **unsaved_files,
141 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000142 int i;
143 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000144 int prefix_len = strlen(opt_name);
145 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000146 *unsaved_files = 0;
147 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000148
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000149 /* Count the number of remapped files. */
150 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000151 if (strncmp(argv[arg], opt_name, prefix_len))
152 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000153
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000154 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
155 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000156 ++*num_unsaved_files;
157 }
Ted Kremenek29004672010-02-17 00:41:32 +0000158
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000159 if (*num_unsaved_files == 0)
160 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000161
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000162 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000163 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
164 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000165 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000166 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000167 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000168 int filename_len;
169 char *filename;
170 char *contents;
171 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000172 const char *sep = strchr(arg_string, ',');
173 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000174 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000175 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000176 free_remapped_files(*unsaved_files, i);
177 *unsaved_files = 0;
178 *num_unsaved_files = 0;
179 return -1;
180 }
Ted Kremenek29004672010-02-17 00:41:32 +0000181
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000182 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000183 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000184 if (!to_file) {
185 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000186 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000187 free_remapped_files(*unsaved_files, i);
188 *unsaved_files = 0;
189 *num_unsaved_files = 0;
190 return -1;
191 }
Ted Kremenek29004672010-02-17 00:41:32 +0000192
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000193 /* Determine the length of the file we're remapping to. */
194 fseek(to_file, 0, SEEK_END);
195 unsaved->Length = ftell(to_file);
196 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000197
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000198 /* Read the contents of the file we're remapping to. */
199 contents = (char *)malloc(unsaved->Length + 1);
200 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
201 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000202 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000203 fclose(to_file);
204 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000205 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000206 *unsaved_files = 0;
207 *num_unsaved_files = 0;
208 return -1;
209 }
210 contents[unsaved->Length] = 0;
211 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000212
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000213 /* Close the file. */
214 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000215
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000216 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000217 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000218 filename = (char *)malloc(filename_len + 1);
219 memcpy(filename, arg_string, filename_len);
220 filename[filename_len] = 0;
221 unsaved->Filename = filename;
222 }
Ted Kremenek29004672010-02-17 00:41:32 +0000223
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000224 return 0;
225}
226
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000227static int parse_remapped_files(int argc, const char **argv, int start_arg,
228 struct CXUnsavedFile **unsaved_files,
229 int *num_unsaved_files) {
230 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
231 unsaved_files, num_unsaved_files);
232}
233
234static int parse_remapped_files_with_try(int try_idx,
235 int argc, const char **argv,
236 int start_arg,
237 struct CXUnsavedFile **unsaved_files,
238 int *num_unsaved_files) {
239 struct CXUnsavedFile *unsaved_files_no_try_idx;
240 int num_unsaved_files_no_try_idx;
241 struct CXUnsavedFile *unsaved_files_try_idx;
242 int num_unsaved_files_try_idx;
243 int ret;
244 char opt_name[32];
245
246 ret = parse_remapped_files(argc, argv, start_arg,
247 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
248 if (ret)
249 return ret;
250
251 sprintf(opt_name, "-remap-file-%d=", try_idx);
252 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
253 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
254 if (ret)
255 return ret;
256
257 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
258 *unsaved_files
259 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
260 sizeof(struct CXUnsavedFile) *
261 *num_unsaved_files);
262 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
263 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
264 num_unsaved_files_try_idx);
265 free(unsaved_files_try_idx);
266 return 0;
267}
268
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000269static const char *parse_comments_schema(int argc, const char **argv) {
270 const char *CommentsSchemaArg = "-comments-xml-schema=";
271 const char *CommentSchemaFile = NULL;
272
273 if (argc == 0)
274 return CommentSchemaFile;
275
276 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
277 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
278
279 return CommentSchemaFile;
280}
281
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000282/******************************************************************************/
283/* Pretty-printing. */
284/******************************************************************************/
285
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000286static const char *FileCheckPrefix = "CHECK";
287
288static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000289 if (CStr != NULL && CStr[0] != '\0') {
290 for ( ; *CStr; ++CStr) {
291 const char C = *CStr;
292 switch (C) {
293 case '\n': printf("\\n"); break;
294 case '\r': printf("\\r"); break;
295 case '\t': printf("\\t"); break;
296 case '\v': printf("\\v"); break;
297 case '\f': printf("\\f"); break;
298 default: putchar(C); break;
299 }
300 }
301 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000302}
303
304static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
305 printf(" %s=[", Prefix);
306 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000307 printf("]");
308}
309
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000310static void PrintCXStringAndDispose(CXString Str) {
311 PrintCString(clang_getCString(Str));
312 clang_disposeString(Str);
313}
314
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000315static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
316 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
317}
318
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000319static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
320 CXString Str) {
321 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
322 clang_disposeString(Str);
323}
324
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000325static void PrintRange(CXSourceRange R, const char *str) {
326 CXFile begin_file, end_file;
327 unsigned begin_line, begin_column, end_line, end_column;
328
329 clang_getSpellingLocation(clang_getRangeStart(R),
330 &begin_file, &begin_line, &begin_column, 0);
331 clang_getSpellingLocation(clang_getRangeEnd(R),
332 &end_file, &end_line, &end_column, 0);
333 if (!begin_file || !end_file)
334 return;
335
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000336 if (str)
337 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000338 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
339}
340
Douglas Gregor97c75712010-10-02 22:49:11 +0000341int want_display_name = 0;
342
Douglas Gregord6225d32012-05-08 00:14:45 +0000343static void printVersion(const char *Prefix, CXVersion Version) {
344 if (Version.Major < 0)
345 return;
346 printf("%s%d", Prefix, Version.Major);
347
348 if (Version.Minor < 0)
349 return;
350 printf(".%d", Version.Minor);
351
352 if (Version.Subminor < 0)
353 return;
354 printf(".%d", Version.Subminor);
355}
356
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000357struct CommentASTDumpingContext {
358 int IndentLevel;
359};
360
361static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
362 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000363 unsigned i;
364 unsigned e;
365 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
366
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000367 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000368 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000369 printf(" ");
370
371 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000372 switch (Kind) {
373 case CXComment_Null:
374 printf("CXComment_Null");
375 break;
376 case CXComment_Text:
377 printf("CXComment_Text");
378 PrintCXStringWithPrefixAndDispose("Text",
379 clang_TextComment_getText(Comment));
380 if (clang_Comment_isWhitespace(Comment))
381 printf(" IsWhitespace");
382 if (clang_InlineContentComment_hasTrailingNewline(Comment))
383 printf(" HasTrailingNewline");
384 break;
385 case CXComment_InlineCommand:
386 printf("CXComment_InlineCommand");
387 PrintCXStringWithPrefixAndDispose(
388 "CommandName",
389 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000390 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
391 case CXCommentInlineCommandRenderKind_Normal:
392 printf(" RenderNormal");
393 break;
394 case CXCommentInlineCommandRenderKind_Bold:
395 printf(" RenderBold");
396 break;
397 case CXCommentInlineCommandRenderKind_Monospaced:
398 printf(" RenderMonospaced");
399 break;
400 case CXCommentInlineCommandRenderKind_Emphasized:
401 printf(" RenderEmphasized");
402 break;
403 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000404 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000405 i != e; ++i) {
406 printf(" Arg[%u]=", i);
407 PrintCXStringAndDispose(
408 clang_InlineCommandComment_getArgText(Comment, i));
409 }
410 if (clang_InlineContentComment_hasTrailingNewline(Comment))
411 printf(" HasTrailingNewline");
412 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000413 case CXComment_HTMLStartTag: {
414 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000415 printf("CXComment_HTMLStartTag");
416 PrintCXStringWithPrefixAndDispose(
417 "Name",
418 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000419 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000420 if (NumAttrs != 0) {
421 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000422 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000423 printf(" ");
424 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
425 printf("=");
426 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
427 }
428 }
429 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
430 printf(" SelfClosing");
431 if (clang_InlineContentComment_hasTrailingNewline(Comment))
432 printf(" HasTrailingNewline");
433 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000434 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000435 case CXComment_HTMLEndTag:
436 printf("CXComment_HTMLEndTag");
437 PrintCXStringWithPrefixAndDispose(
438 "Name",
439 clang_HTMLTagComment_getTagName(Comment));
440 if (clang_InlineContentComment_hasTrailingNewline(Comment))
441 printf(" HasTrailingNewline");
442 break;
443 case CXComment_Paragraph:
444 printf("CXComment_Paragraph");
445 if (clang_Comment_isWhitespace(Comment))
446 printf(" IsWhitespace");
447 break;
448 case CXComment_BlockCommand:
449 printf("CXComment_BlockCommand");
450 PrintCXStringWithPrefixAndDispose(
451 "CommandName",
452 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000453 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000454 i != e; ++i) {
455 printf(" Arg[%u]=", i);
456 PrintCXStringAndDispose(
457 clang_BlockCommandComment_getArgText(Comment, i));
458 }
459 break;
460 case CXComment_ParamCommand:
461 printf("CXComment_ParamCommand");
462 switch (clang_ParamCommandComment_getDirection(Comment)) {
463 case CXCommentParamPassDirection_In:
464 printf(" in");
465 break;
466 case CXCommentParamPassDirection_Out:
467 printf(" out");
468 break;
469 case CXCommentParamPassDirection_InOut:
470 printf(" in,out");
471 break;
472 }
473 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
474 printf(" explicitly");
475 else
476 printf(" implicitly");
477 PrintCXStringWithPrefixAndDispose(
478 "ParamName",
479 clang_ParamCommandComment_getParamName(Comment));
480 if (clang_ParamCommandComment_isParamIndexValid(Comment))
481 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
482 else
483 printf(" ParamIndex=Invalid");
484 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000485 case CXComment_TParamCommand:
486 printf("CXComment_TParamCommand");
487 PrintCXStringWithPrefixAndDispose(
488 "ParamName",
489 clang_TParamCommandComment_getParamName(Comment));
490 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
491 printf(" ParamPosition={");
492 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
493 i != e; ++i) {
494 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
495 if (i != e - 1)
496 printf(", ");
497 }
498 printf("}");
499 } else
500 printf(" ParamPosition=Invalid");
501 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000502 case CXComment_VerbatimBlockCommand:
503 printf("CXComment_VerbatimBlockCommand");
504 PrintCXStringWithPrefixAndDispose(
505 "CommandName",
506 clang_BlockCommandComment_getCommandName(Comment));
507 break;
508 case CXComment_VerbatimBlockLine:
509 printf("CXComment_VerbatimBlockLine");
510 PrintCXStringWithPrefixAndDispose(
511 "Text",
512 clang_VerbatimBlockLineComment_getText(Comment));
513 break;
514 case CXComment_VerbatimLine:
515 printf("CXComment_VerbatimLine");
516 PrintCXStringWithPrefixAndDispose(
517 "Text",
518 clang_VerbatimLineComment_getText(Comment));
519 break;
520 case CXComment_FullComment:
521 printf("CXComment_FullComment");
522 break;
523 }
524 if (Kind != CXComment_Null) {
525 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000526 unsigned i;
527 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000528 printf("\n// %s: ", FileCheckPrefix);
529 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
530 }
531 }
532 printf(")");
533 Ctx->IndentLevel--;
534}
535
536static void DumpCXComment(CXComment Comment) {
537 struct CommentASTDumpingContext Ctx;
538 Ctx.IndentLevel = 1;
539 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
540 DumpCXCommentInternal(&Ctx, Comment);
541 printf("]");
542}
543
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000544typedef struct {
545 const char *CommentSchemaFile;
546#ifdef CLANG_HAVE_LIBXML
547 xmlRelaxNGParserCtxtPtr RNGParser;
548 xmlRelaxNGPtr Schema;
549#endif
550} CommentXMLValidationData;
551
552static void ValidateCommentXML(const char *Str,
553 CommentXMLValidationData *ValidationData) {
554#ifdef CLANG_HAVE_LIBXML
555 xmlDocPtr Doc;
556 xmlRelaxNGValidCtxtPtr ValidationCtxt;
557 int status;
558
559 if (!ValidationData || !ValidationData->CommentSchemaFile)
560 return;
561
562 if (!ValidationData->RNGParser) {
563 ValidationData->RNGParser =
564 xmlRelaxNGNewParserCtxt(ValidationData->CommentSchemaFile);
565 ValidationData->Schema = xmlRelaxNGParse(ValidationData->RNGParser);
566 }
567 if (!ValidationData->RNGParser) {
568 printf(" libXMLError");
569 return;
570 }
571
572 Doc = xmlParseDoc((const xmlChar *) Str);
573
574 if (!Doc) {
575 xmlErrorPtr Error = xmlGetLastError();
576 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
577 return;
578 }
579
580 ValidationCtxt = xmlRelaxNGNewValidCtxt(ValidationData->Schema);
581 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
582 if (!status)
583 printf(" CommentXMLValid");
584 else if (status > 0) {
585 xmlErrorPtr Error = xmlGetLastError();
586 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
587 } else
588 printf(" libXMLError");
589
590 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
591 xmlFreeDoc(Doc);
592#endif
593}
594
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000595static void PrintCursorComments(CXCursor Cursor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000596 CommentXMLValidationData *ValidationData) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000597 {
598 CXString RawComment;
599 const char *RawCommentCString;
600 CXString BriefComment;
601 const char *BriefCommentCString;
602
603 RawComment = clang_Cursor_getRawCommentText(Cursor);
604 RawCommentCString = clang_getCString(RawComment);
605 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
606 PrintCStringWithPrefix("RawComment", RawCommentCString);
607 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
608
609 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
610 BriefCommentCString = clang_getCString(BriefComment);
611 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
612 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
613 clang_disposeString(BriefComment);
614 }
615 clang_disposeString(RawComment);
616 }
617
618 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000619 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000620 if (clang_Comment_getKind(Comment) != CXComment_Null) {
621 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
622 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000623 {
624 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000625 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000626 PrintCXStringWithPrefix("FullCommentAsXML", XML);
627 ValidateCommentXML(clang_getCString(XML), ValidationData);
628 clang_disposeString(XML);
629 }
630
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000631 DumpCXComment(Comment);
632 }
633 }
634}
635
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000636typedef struct {
637 unsigned line;
638 unsigned col;
639} LineCol;
640
641static int lineCol_cmp(const void *p1, const void *p2) {
642 const LineCol *lhs = p1;
643 const LineCol *rhs = p2;
644 if (lhs->line != rhs->line)
645 return (int)lhs->line - (int)rhs->line;
646 return (int)lhs->col - (int)rhs->col;
647}
648
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000649static void PrintCursor(CXCursor Cursor,
650 CommentXMLValidationData *ValidationData) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000651 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000652 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000653 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000654 printf("Invalid Cursor => %s", clang_getCString(ks));
655 clang_disposeString(ks);
656 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000657 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000658 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000659 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000660 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000661 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000662 CXCursor *overridden;
663 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000664 unsigned RefNameRangeNr;
665 CXSourceRange CursorExtent;
666 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000667 int AlwaysUnavailable;
668 int AlwaysDeprecated;
669 CXString UnavailableMessage;
670 CXString DeprecatedMessage;
671 CXPlatformAvailability PlatformAvailability[2];
672 int NumPlatformAvailability;
673 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000674
Ted Kremenek29004672010-02-17 00:41:32 +0000675 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000676 string = want_display_name? clang_getCursorDisplayName(Cursor)
677 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000678 printf("%s=%s", clang_getCString(ks),
679 clang_getCString(string));
680 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000681 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000682
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000683 Referenced = clang_getCursorReferenced(Cursor);
684 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000685 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
686 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
687 printf("[");
688 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000689 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000690 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000691 if (I)
692 printf(", ");
693
Douglas Gregor2967e282010-09-14 00:20:32 +0000694 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000695 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000696 printf("%d:%d", line, column);
697 }
698 printf("]");
699 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000700 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000701 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000702 printf(":%d:%d", line, column);
703 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000704 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000705
706 if (clang_isCursorDefinition(Cursor))
707 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000708
709 switch (clang_getCursorAvailability(Cursor)) {
710 case CXAvailability_Available:
711 break;
712
713 case CXAvailability_Deprecated:
714 printf(" (deprecated)");
715 break;
716
717 case CXAvailability_NotAvailable:
718 printf(" (unavailable)");
719 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000720
721 case CXAvailability_NotAccessible:
722 printf(" (inaccessible)");
723 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000724 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000725
Douglas Gregord6225d32012-05-08 00:14:45 +0000726 NumPlatformAvailability
727 = clang_getCursorPlatformAvailability(Cursor,
728 &AlwaysDeprecated,
729 &DeprecatedMessage,
730 &AlwaysUnavailable,
731 &UnavailableMessage,
732 PlatformAvailability, 2);
733 if (AlwaysUnavailable) {
734 printf(" (always unavailable: \"%s\")",
735 clang_getCString(UnavailableMessage));
736 } else if (AlwaysDeprecated) {
737 printf(" (always deprecated: \"%s\")",
738 clang_getCString(DeprecatedMessage));
739 } else {
740 for (I = 0; I != NumPlatformAvailability; ++I) {
741 if (I >= 2)
742 break;
743
744 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
745 if (PlatformAvailability[I].Unavailable)
746 printf(", unavailable");
747 else {
748 printVersion(", introduced=", PlatformAvailability[I].Introduced);
749 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
750 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
751 }
752 if (clang_getCString(PlatformAvailability[I].Message)[0])
753 printf(", message=\"%s\"",
754 clang_getCString(PlatformAvailability[I].Message));
755 printf(")");
756 }
757 }
758 for (I = 0; I != NumPlatformAvailability; ++I) {
759 if (I >= 2)
760 break;
761 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
762 }
763
764 clang_disposeString(DeprecatedMessage);
765 clang_disposeString(UnavailableMessage);
766
Douglas Gregora8d0c772011-05-13 15:54:42 +0000767 if (clang_CXXMethod_isStatic(Cursor))
768 printf(" (static)");
769 if (clang_CXXMethod_isVirtual(Cursor))
770 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000771 if (clang_CXXMethod_isConst(Cursor))
772 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000773 if (clang_CXXMethod_isPureVirtual(Cursor))
774 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000775 if (clang_Cursor_isVariadic(Cursor))
776 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000777 if (clang_Cursor_isObjCOptional(Cursor))
778 printf(" (@optional)");
779
Ted Kremeneka5940822010-08-26 01:42:22 +0000780 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000781 CXType T =
782 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
783 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000784 printf(" [IBOutletCollection=%s]", clang_getCString(S));
785 clang_disposeString(S);
786 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000787
788 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
789 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
790 unsigned isVirtual = clang_isVirtualBase(Cursor);
791 const char *accessStr = 0;
792
793 switch (access) {
794 case CX_CXXInvalidAccessSpecifier:
795 accessStr = "invalid"; break;
796 case CX_CXXPublic:
797 accessStr = "public"; break;
798 case CX_CXXProtected:
799 accessStr = "protected"; break;
800 case CX_CXXPrivate:
801 accessStr = "private"; break;
802 }
803
804 printf(" [access=%s isVirtual=%s]", accessStr,
805 isVirtual ? "true" : "false");
806 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000807
808 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
809 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000810 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
811 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000812 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000813 printf(" [Specialization of %s:%d:%d]",
814 clang_getCString(Name), line, column);
815 clang_disposeString(Name);
816 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000817
818 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
819 if (num_overridden) {
820 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000821 LineCol lineCols[50];
822 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000823 printf(" [Overrides ");
824 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000825 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000826 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000827 lineCols[I].line = line;
828 lineCols[I].col = column;
829 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000830 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000831 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
832 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000833 if (I)
834 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000835 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000836 }
837 printf("]");
838 clang_disposeOverriddenCursors(overridden);
839 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000840
841 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000842 CXFile File = clang_getIncludedFile(Cursor);
843 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000844 printf(" (%s)", clang_getCString(Included));
845 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000846
847 if (clang_isFileMultipleIncludeGuarded(TU, File))
848 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000849 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000850
851 CursorExtent = clang_getCursorExtent(Cursor);
852 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
853 CXNameRange_WantQualifier
854 | CXNameRange_WantSinglePiece
855 | CXNameRange_WantTemplateArgs,
856 0);
857 if (!clang_equalRanges(CursorExtent, RefNameRange))
858 PrintRange(RefNameRange, "SingleRefName");
859
860 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
861 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
862 CXNameRange_WantQualifier
863 | CXNameRange_WantTemplateArgs,
864 RefNameRangeNr);
865 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
866 break;
867 if (!clang_equalRanges(CursorExtent, RefNameRange))
868 PrintRange(RefNameRange, "RefName");
869 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000870
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000871 PrintCursorComments(Cursor, ValidationData);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000872
873 {
874 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
875 if (PropAttrs != CXObjCPropertyAttr_noattr) {
876 printf(" [");
877 #define PRINT_PROP_ATTR(A) \
878 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
879 PRINT_PROP_ATTR(readonly);
880 PRINT_PROP_ATTR(getter);
881 PRINT_PROP_ATTR(assign);
882 PRINT_PROP_ATTR(readwrite);
883 PRINT_PROP_ATTR(retain);
884 PRINT_PROP_ATTR(copy);
885 PRINT_PROP_ATTR(nonatomic);
886 PRINT_PROP_ATTR(setter);
887 PRINT_PROP_ATTR(atomic);
888 PRINT_PROP_ATTR(weak);
889 PRINT_PROP_ATTR(strong);
890 PRINT_PROP_ATTR(unsafe_unretained);
891 printf("]");
892 }
893 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000894
895 {
896 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
897 if (QT != CXObjCDeclQualifier_None) {
898 printf(" [");
899 #define PRINT_OBJC_QUAL(A) \
900 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
901 PRINT_OBJC_QUAL(In);
902 PRINT_OBJC_QUAL(Inout);
903 PRINT_OBJC_QUAL(Out);
904 PRINT_OBJC_QUAL(Bycopy);
905 PRINT_OBJC_QUAL(Byref);
906 PRINT_OBJC_QUAL(Oneway);
907 printf("]");
908 }
909 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000910 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000911}
Steve Naroff1054e602009-08-31 00:59:03 +0000912
Ted Kremenek29004672010-02-17 00:41:32 +0000913static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000914 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000915 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000916 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000917 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000918 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000919 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000920 clang_disposeString(source);
921 return "<invalid loc>";
922 }
923 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000924 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000925 clang_disposeString(source);
926 return b;
927 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000928}
929
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000930/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000931/* Callbacks. */
932/******************************************************************************/
933
934typedef void (*PostVisitTU)(CXTranslationUnit);
935
Douglas Gregor33cdd812010-02-18 18:08:43 +0000936void PrintDiagnostic(CXDiagnostic Diagnostic) {
937 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000938 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000939 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000940 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000941 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
942 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000943 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000944
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000945 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000946 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000947
Douglas Gregord770f732010-02-22 23:17:23 +0000948 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
949 fprintf(stderr, "%s\n", clang_getCString(Msg));
950 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000951
Douglas Gregor229bebd2010-11-09 06:24:54 +0000952 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
953 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000954 if (!file)
955 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000956
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000957 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000958 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000959 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000960 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000961 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
962 CXSourceLocation start = clang_getRangeStart(range);
963 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000964 unsigned start_line, start_column, end_line, end_column;
965 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +0000966 clang_getSpellingLocation(start, &start_file, &start_line,
967 &start_column, 0);
968 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +0000969 if (clang_equalLocations(start, end)) {
970 /* Insertion. */
971 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000972 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +0000973 clang_getCString(insertion_text), start_line, start_column);
974 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
975 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000976 if (start_file == file && end_file == file) {
977 fprintf(out, "FIX-IT: Remove ");
978 PrintExtent(out, start_line, start_column, end_line, end_column);
979 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +0000980 }
Douglas Gregor836ec942010-02-19 18:16:06 +0000981 } else {
982 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000983 if (start_file == end_file) {
984 fprintf(out, "FIX-IT: Replace ");
985 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +0000986 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +0000987 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000988 break;
989 }
Douglas Gregor836ec942010-02-19 18:16:06 +0000990 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +0000991 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000992}
993
Ted Kremenek914c7e62012-02-14 02:46:03 +0000994void PrintDiagnosticSet(CXDiagnosticSet Set) {
995 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
996 for ( ; i != n ; ++i) {
997 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
998 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000999 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001000 if (ChildDiags)
1001 PrintDiagnosticSet(ChildDiags);
1002 }
1003}
1004
1005void PrintDiagnostics(CXTranslationUnit TU) {
1006 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1007 PrintDiagnosticSet(TUSet);
1008 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001009}
1010
Ted Kremenek83f642e2011-04-18 22:47:10 +00001011void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001012 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001013 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001014 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001015 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001016 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001017 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001018 unsigned long amount = usage.entries[i].amount;
1019 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001020 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001021 ((double) amount)/(1024*1024));
1022 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001023 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001024 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001025 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001026}
1027
Ted Kremenekb478ff42010-01-26 17:59:48 +00001028/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001029/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001030/******************************************************************************/
1031
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001032static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001033 CXSourceRange extent = clang_getCursorExtent(C);
1034 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001035}
1036
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001037/* Data used by the visitors. */
1038typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001039 CXTranslationUnit TU;
1040 enum CXCursorKind *Filter;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001041 CommentXMLValidationData ValidationData;
Douglas Gregor720d0052010-01-20 21:32:04 +00001042} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001043
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001044
Ted Kremenek29004672010-02-17 00:41:32 +00001045enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001046 CXCursor Parent,
1047 CXClientData ClientData) {
1048 VisitorData *Data = (VisitorData *)ClientData;
1049 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001050 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001051 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001052 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001053 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001054 GetCursorSource(Cursor), line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001055 PrintCursor(Cursor, &Data->ValidationData);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001056 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001057 if (clang_isDeclaration(Cursor.kind)) {
1058 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1059 const char *accessStr = 0;
1060
1061 switch (access) {
1062 case CX_CXXInvalidAccessSpecifier: break;
1063 case CX_CXXPublic:
1064 accessStr = "public"; break;
1065 case CX_CXXProtected:
1066 accessStr = "protected"; break;
1067 case CX_CXXPrivate:
1068 accessStr = "private"; break;
1069 }
1070
1071 if (accessStr)
1072 printf(" [access=%s]", accessStr);
1073 }
Ted Kremenek29004672010-02-17 00:41:32 +00001074 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001075 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001076 }
Ted Kremenek29004672010-02-17 00:41:32 +00001077
Douglas Gregor720d0052010-01-20 21:32:04 +00001078 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001079}
Steve Naroffa1c72842009-08-28 15:28:48 +00001080
Ted Kremenek29004672010-02-17 00:41:32 +00001081static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001082 CXCursor Parent,
1083 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001084 const char *startBuf, *endBuf;
1085 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1086 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001087 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001088
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001089 if (Cursor.kind != CXCursor_FunctionDecl ||
1090 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001091 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001092
1093 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1094 &startLine, &startColumn,
1095 &endLine, &endColumn);
1096 /* Probe the entire body, looking for both decls and refs. */
1097 curLine = startLine;
1098 curColumn = startColumn;
1099
1100 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001101 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001102 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001103 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001104
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001105 if (*startBuf == '\n') {
1106 startBuf++;
1107 curLine++;
1108 curColumn = 1;
1109 } else if (*startBuf != '\t')
1110 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001111
Douglas Gregor66a58812010-01-18 22:46:11 +00001112 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001113 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001114
Douglas Gregor4f46e782010-01-19 21:36:55 +00001115 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001116 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001117 CXSourceLocation RefLoc
1118 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001119 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001120 if (Ref.kind == CXCursor_NoDeclFound) {
1121 /* Nothing found here; that's fine. */
1122 } else if (Ref.kind != CXCursor_FunctionDecl) {
1123 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1124 curLine, curColumn);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001125 PrintCursor(Ref, &Data->ValidationData);
Douglas Gregor66a58812010-01-18 22:46:11 +00001126 printf("\n");
1127 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001128 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001129 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001130 startBuf++;
1131 }
Ted Kremenek29004672010-02-17 00:41:32 +00001132
Douglas Gregor720d0052010-01-20 21:32:04 +00001133 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001134}
1135
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001136/******************************************************************************/
1137/* USR testing. */
1138/******************************************************************************/
1139
Douglas Gregor720d0052010-01-20 21:32:04 +00001140enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1141 CXClientData ClientData) {
1142 VisitorData *Data = (VisitorData *)ClientData;
1143 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001144 CXString USR = clang_getCursorUSR(C);
1145 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001146 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001147 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001148 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001149 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001150 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1151
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001152 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001153 printf("\n");
1154 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001155
Douglas Gregor720d0052010-01-20 21:32:04 +00001156 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001157 }
1158
Douglas Gregor720d0052010-01-20 21:32:04 +00001159 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001160}
1161
1162/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001163/* Inclusion stack testing. */
1164/******************************************************************************/
1165
1166void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1167 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001168
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001169 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001170 CXString fname;
1171
1172 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001173 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001174 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001175
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001176 for (i = 0; i < includeStackLen; ++i) {
1177 CXFile includingFile;
1178 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001179 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1180 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001181 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001182 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001183 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001184 }
1185 printf("\n");
1186}
1187
1188void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001189 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001190}
1191
1192/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001193/* Linkage testing. */
1194/******************************************************************************/
1195
1196static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1197 CXClientData d) {
1198 const char *linkage = 0;
1199
1200 if (clang_isInvalid(clang_getCursorKind(cursor)))
1201 return CXChildVisit_Recurse;
1202
1203 switch (clang_getCursorLinkage(cursor)) {
1204 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001205 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1206 case CXLinkage_Internal: linkage = "Internal"; break;
1207 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1208 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001209 }
1210
1211 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001212 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001213 printf("linkage=%s\n", linkage);
1214 }
1215
1216 return CXChildVisit_Recurse;
1217}
1218
1219/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001220/* Typekind testing. */
1221/******************************************************************************/
1222
Dmitri Gribenko00353722013-02-15 21:15:49 +00001223static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1224 CXString TypeSpelling, TypeKindSpelling;
1225
1226 TypeSpelling = clang_getTypeSpelling(T);
1227 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1228 printf(Format,
1229 clang_getCString(TypeSpelling),
1230 clang_getCString(TypeKindSpelling));
1231 clang_disposeString(TypeSpelling);
1232 clang_disposeString(TypeKindSpelling);
1233}
1234
1235static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1236 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001237 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001238 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001239 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001240 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001241 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001242 if (clang_isConstQualifiedType(T))
1243 printf(" const");
1244 if (clang_isVolatileQualifiedType(T))
1245 printf(" volatile");
1246 if (clang_isRestrictQualifiedType(T))
1247 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001248 if (RQ == CXRefQualifier_LValue)
1249 printf(" lvalue-ref-qualifier");
1250 if (RQ == CXRefQualifier_RValue)
1251 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001252 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001253 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001254 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001255 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001256 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001257 }
1258 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001259 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001260 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001261 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001262 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001263 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001264 }
1265 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001266 /* Print the argument types if they exist. */
1267 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001268 int NumArgs = clang_Cursor_getNumArguments(cursor);
1269 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001270 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001271 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001272 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001273 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001274 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001275 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001276 }
1277 }
1278 printf("]");
1279 }
1280 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001281 /* Print the template argument types if they exist. */
1282 {
1283 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1284 if (NumTArgs != -1 && NumTArgs != 0) {
1285 int i;
1286 printf(" [templateargs/%d=", NumTArgs);
1287 for (i = 0; i < NumTArgs; ++i) {
1288 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1289 if (TArg.kind != CXType_Invalid) {
1290 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1291 }
1292 }
1293 printf("]");
1294 }
1295 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001296 /* Print if this is a non-POD type. */
1297 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001298 /* Print the pointee type. */
1299 {
1300 CXType PT = clang_getPointeeType(T);
1301 if (PT.kind != CXType_Invalid) {
1302 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1303 }
1304 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001305
Ted Kremenek6bca9842010-05-14 21:29:26 +00001306 printf("\n");
1307 }
1308 return CXChildVisit_Recurse;
1309}
1310
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001311static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1312 CXClientData d) {
1313 CXType T;
1314 enum CXCursorKind K = clang_getCursorKind(cursor);
1315 if (clang_isInvalid(K))
1316 return CXChildVisit_Recurse;
1317 T = clang_getCursorType(cursor);
1318 PrintCursor(cursor, NULL);
1319 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1320 /* Print the type sizeof if applicable. */
1321 {
1322 long long Size = clang_Type_getSizeOf(T);
1323 if (Size >= 0 || Size < -1 ) {
1324 printf(" [sizeof=%lld]", Size);
1325 }
1326 }
1327 /* Print the type alignof if applicable. */
1328 {
1329 long long Align = clang_Type_getAlignOf(T);
1330 if (Align >= 0 || Align < -1) {
1331 printf(" [alignof=%lld]", Align);
1332 }
1333 }
1334 /* Print the record field offset if applicable. */
1335 {
Nico Weber82098cb2014-04-24 04:14:12 +00001336 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1337 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001338 /* recurse to get the root anonymous record parent */
1339 CXCursor Parent, Root;
Nico Weber82098cb2014-04-24 04:14:12 +00001340 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
1341 CXString RootParentSpelling;
1342 const char *RootParentName = 0;
Richard Smith131daca2014-03-06 21:59:38 +00001343 Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001344 do {
Nico Weber82098cb2014-04-24 04:14:12 +00001345 if (RootParentName != 0)
1346 clang_disposeString(RootParentSpelling);
1347
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001348 Root = Parent;
Nico Weber82098cb2014-04-24 04:14:12 +00001349 RootParentSpelling = clang_getCursorSpelling(Root);
1350 RootParentName = clang_getCString(RootParentSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001351 Parent = clang_getCursorSemanticParent(Root);
Nico Weber82098cb2014-04-24 04:14:12 +00001352 } while (clang_getCursorType(Parent).kind == CXType_Record &&
1353 !strcmp(RootParentName, ""));
1354 clang_disposeString(RootParentSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001355 /* if RootParentName is "", record is anonymous. */
1356 {
1357 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
1358 FieldName);
1359 printf(" [offsetof=%lld]", Offset);
1360 }
1361 }
Nico Weber82098cb2014-04-24 04:14:12 +00001362 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001363 }
1364 /* Print if its a bitfield */
1365 {
1366 int IsBitfield = clang_Cursor_isBitField(cursor);
1367 if (IsBitfield)
1368 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1369 }
1370 printf("\n");
1371 return CXChildVisit_Recurse;
1372}
1373
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001374/******************************************************************************/
1375/* Bitwidth testing. */
1376/******************************************************************************/
1377
1378static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1379 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001380 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001381 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1382 return CXChildVisit_Recurse;
1383
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001384 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001385 if (Bitwidth >= 0) {
1386 PrintCursor(cursor, NULL);
1387 printf(" bitwidth=%d\n", Bitwidth);
1388 }
1389
1390 return CXChildVisit_Recurse;
1391}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001392
1393/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001394/* Loading ASTs/source. */
1395/******************************************************************************/
1396
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001397static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001398 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001399 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001400 PostVisitTU PV,
1401 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001402
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001403 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001404 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001405
1406 if (Visitor) {
1407 enum CXCursorKind K = CXCursor_NotImplemented;
1408 enum CXCursorKind *ck = &K;
1409 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001410
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001411 /* Perform some simple filtering. */
1412 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001413 else if (!strcmp(filter, "all-display") ||
1414 !strcmp(filter, "local-display")) {
1415 ck = NULL;
1416 want_display_name = 1;
1417 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001418 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001419 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1420 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1421 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1422 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1423 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1424 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1425 else {
1426 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1427 return 1;
1428 }
Ted Kremenek29004672010-02-17 00:41:32 +00001429
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001430 Data.TU = TU;
1431 Data.Filter = ck;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001432 Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
1433#ifdef CLANG_HAVE_LIBXML
1434 Data.ValidationData.RNGParser = NULL;
1435 Data.ValidationData.Schema = NULL;
1436#endif
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001437 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001438 }
Ted Kremenek29004672010-02-17 00:41:32 +00001439
Ted Kremenekb478ff42010-01-26 17:59:48 +00001440 if (PV)
1441 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001442
Douglas Gregor33cdd812010-02-18 18:08:43 +00001443 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001444 if (checkForErrors(TU) != 0) {
1445 clang_disposeTranslationUnit(TU);
1446 return -1;
1447 }
1448
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001449 clang_disposeTranslationUnit(TU);
1450 return 0;
1451}
1452
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001453int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001454 const char *prefix, CXCursorVisitor Visitor,
1455 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001456 CXIndex Idx;
1457 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001458 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001459 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001460 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001461 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001462
Ted Kremenek50228be2010-02-11 07:41:25 +00001463 if (!CreateTranslationUnit(Idx, file, &TU)) {
1464 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001465 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001466 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001467
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001468 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001469 clang_disposeIndex(Idx);
1470 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001471}
1472
Ted Kremenekb478ff42010-01-26 17:59:48 +00001473int perform_test_load_source(int argc, const char **argv,
1474 const char *filter, CXCursorVisitor Visitor,
1475 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001476 CXIndex Idx;
1477 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001478 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001479 struct CXUnsavedFile *unsaved_files = 0;
1480 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001481 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001482 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001483
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001484 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001485 (!strcmp(filter, "local") ||
1486 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001487 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001488
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001489 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1490 argc--;
1491 argv++;
1492 }
1493
Ted Kremenek50228be2010-02-11 07:41:25 +00001494 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1495 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001496 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001497 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001498
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001499 Err = clang_parseTranslationUnit2(Idx, 0,
1500 argv + num_unsaved_files,
1501 argc - num_unsaved_files,
1502 unsaved_files, num_unsaved_files,
1503 getDefaultParsingOptions(), &TU);
1504 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001505 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001506 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001507 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001508 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001509 return 1;
1510 }
1511
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001512 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1513 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001514 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001515 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001516 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001517}
1518
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001519int perform_test_reparse_source(int argc, const char **argv, int trials,
1520 const char *filter, CXCursorVisitor Visitor,
1521 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001522 CXIndex Idx;
1523 CXTranslationUnit TU;
1524 struct CXUnsavedFile *unsaved_files = 0;
1525 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001526 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001527 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001528 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001529 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001530 int remap_after_trial = 0;
1531 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001532
1533 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1534 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001535 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001536
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001537 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1538 clang_disposeIndex(Idx);
1539 return -1;
1540 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001541
1542 for (i = 0; i < argc; ++i) {
1543 if (strcmp(argv[i], "--") == 0)
1544 break;
1545 }
1546 if (i < argc)
1547 compiler_arg_idx = i+1;
1548 if (num_unsaved_files > compiler_arg_idx)
1549 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001550
Daniel Dunbarec29d712010-08-18 23:09:16 +00001551 /* Load the initial translation unit -- we do this without honoring remapped
1552 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001553 Err = clang_parseTranslationUnit2(Idx, 0,
1554 argv + compiler_arg_idx,
1555 argc - compiler_arg_idx,
1556 0, 0, getDefaultParsingOptions(), &TU);
1557 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001558 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001559 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001560 free_remapped_files(unsaved_files, num_unsaved_files);
1561 clang_disposeIndex(Idx);
1562 return 1;
1563 }
1564
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001565 if (checkForErrors(TU) != 0)
1566 return -1;
1567
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001568 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1569 remap_after_trial =
1570 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1571 }
1572
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001573 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001574 free_remapped_files(unsaved_files, num_unsaved_files);
1575 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1576 &unsaved_files, &num_unsaved_files)) {
1577 clang_disposeTranslationUnit(TU);
1578 clang_disposeIndex(Idx);
1579 return -1;
1580 }
1581
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001582 Err = clang_reparseTranslationUnit(
1583 TU,
1584 trial >= remap_after_trial ? num_unsaved_files : 0,
1585 trial >= remap_after_trial ? unsaved_files : 0,
1586 clang_defaultReparseOptions(TU));
1587 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001588 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001589 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001590 clang_disposeTranslationUnit(TU);
1591 free_remapped_files(unsaved_files, num_unsaved_files);
1592 clang_disposeIndex(Idx);
1593 return -1;
1594 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001595
1596 if (checkForErrors(TU) != 0)
1597 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001598 }
1599
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001600 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001601
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001602 free_remapped_files(unsaved_files, num_unsaved_files);
1603 clang_disposeIndex(Idx);
1604 return result;
1605}
1606
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001607/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001608/* Logic for testing clang_getCursor(). */
1609/******************************************************************************/
1610
Douglas Gregor37aa4932011-05-04 00:14:37 +00001611static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001612 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001613 unsigned end_line, unsigned end_col,
1614 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001615 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001616 if (prefix)
1617 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001618 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1619 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001620 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001621 printf("\n");
1622}
1623
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001624static int perform_file_scan(const char *ast_file, const char *source_file,
1625 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001626 CXIndex Idx;
1627 CXTranslationUnit TU;
1628 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001629 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001630 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001631 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001632 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001633
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001634 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001635 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001636 fprintf(stderr, "Could not create Index\n");
1637 return 1;
1638 }
Ted Kremenek29004672010-02-17 00:41:32 +00001639
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001640 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1641 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001642
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001643 if ((fp = fopen(source_file, "r")) == NULL) {
1644 fprintf(stderr, "Could not open '%s'\n", source_file);
1645 return 1;
1646 }
Ted Kremenek29004672010-02-17 00:41:32 +00001647
Douglas Gregor816fd362010-01-22 21:44:22 +00001648 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001649 for (;;) {
1650 CXCursor cursor;
1651 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001652
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001653 if (c == '\n') {
1654 ++line;
1655 col = 1;
1656 } else
1657 ++col;
1658
1659 /* Check the cursor at this position, and dump the previous one if we have
1660 * found something new.
1661 */
1662 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1663 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1664 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001665 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001666 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001667 start_line = line;
1668 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001669 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001670 if (c == EOF)
1671 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001672
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001673 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001674 }
Ted Kremenek29004672010-02-17 00:41:32 +00001675
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001676 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001677 clang_disposeTranslationUnit(TU);
1678 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001679 return 0;
1680}
1681
1682/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001683/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001684/******************************************************************************/
1685
Douglas Gregor9eb77012009-11-07 00:00:49 +00001686/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1687 on failure. If successful, the pointer *filename will contain newly-allocated
1688 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001689int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001690 unsigned *column, unsigned *second_line,
1691 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001692 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001693 const char *last_colon = strrchr(input, ':');
1694 unsigned values[4], i;
1695 unsigned num_values = (second_line && second_column)? 4 : 2;
1696
Douglas Gregor9eb77012009-11-07 00:00:49 +00001697 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001698 if (!last_colon || last_colon == input) {
1699 if (num_values == 4)
1700 fprintf(stderr, "could not parse filename:line:column:line:column in "
1701 "'%s'\n", input);
1702 else
1703 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001704 return 1;
1705 }
1706
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001707 for (i = 0; i != num_values; ++i) {
1708 const char *prev_colon;
1709
1710 /* Parse the next line or column. */
1711 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1712 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001713 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001714 (i % 2 ? "column" : "line"), input);
1715 return 1;
1716 }
Ted Kremenek29004672010-02-17 00:41:32 +00001717
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001718 if (i + 1 == num_values)
1719 break;
1720
1721 /* Find the previous colon. */
1722 prev_colon = last_colon - 1;
1723 while (prev_colon != input && *prev_colon != ':')
1724 --prev_colon;
1725 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001726 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001727 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001728 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001729 }
1730
1731 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001732 }
1733
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001734 *line = values[0];
1735 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001736
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001737 if (second_line && second_column) {
1738 *second_line = values[2];
1739 *second_column = values[3];
1740 }
1741
Douglas Gregorf96ea292009-11-09 18:19:57 +00001742 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001743 *filename = (char*)malloc(last_colon - input + 1);
1744 memcpy(*filename, input, last_colon - input);
1745 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001746 return 0;
1747}
1748
1749const char *
1750clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1751 switch (Kind) {
1752 case CXCompletionChunk_Optional: return "Optional";
1753 case CXCompletionChunk_TypedText: return "TypedText";
1754 case CXCompletionChunk_Text: return "Text";
1755 case CXCompletionChunk_Placeholder: return "Placeholder";
1756 case CXCompletionChunk_Informative: return "Informative";
1757 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1758 case CXCompletionChunk_LeftParen: return "LeftParen";
1759 case CXCompletionChunk_RightParen: return "RightParen";
1760 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1761 case CXCompletionChunk_RightBracket: return "RightBracket";
1762 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1763 case CXCompletionChunk_RightBrace: return "RightBrace";
1764 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1765 case CXCompletionChunk_RightAngle: return "RightAngle";
1766 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001767 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768 case CXCompletionChunk_Colon: return "Colon";
1769 case CXCompletionChunk_SemiColon: return "SemiColon";
1770 case CXCompletionChunk_Equal: return "Equal";
1771 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1772 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001773 }
Ted Kremenek29004672010-02-17 00:41:32 +00001774
Douglas Gregor9eb77012009-11-07 00:00:49 +00001775 return "Unknown";
1776}
1777
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001778static int checkForErrors(CXTranslationUnit TU) {
1779 unsigned Num, i;
1780 CXDiagnostic Diag;
1781 CXString DiagStr;
1782
1783 if (!getenv("CINDEXTEST_FAILONERROR"))
1784 return 0;
1785
1786 Num = clang_getNumDiagnostics(TU);
1787 for (i = 0; i != Num; ++i) {
1788 Diag = clang_getDiagnostic(TU, i);
1789 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1790 DiagStr = clang_formatDiagnostic(Diag,
1791 clang_defaultDiagnosticDisplayOptions());
1792 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1793 clang_disposeString(DiagStr);
1794 clang_disposeDiagnostic(Diag);
1795 return -1;
1796 }
1797 clang_disposeDiagnostic(Diag);
1798 }
1799
1800 return 0;
1801}
1802
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001803void print_completion_string(CXCompletionString completion_string, FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001804 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001805
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001806 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001807 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001808 CXString text;
1809 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001810 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001811 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001812
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001813 if (Kind == CXCompletionChunk_Optional) {
1814 fprintf(file, "{Optional ");
1815 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001816 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001817 file);
1818 fprintf(file, "}");
1819 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001820 }
1821
1822 if (Kind == CXCompletionChunk_VerticalSpace) {
1823 fprintf(file, "{VerticalSpace }");
1824 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001825 }
Ted Kremenek29004672010-02-17 00:41:32 +00001826
Douglas Gregorf81f5282009-11-09 17:05:28 +00001827 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001828 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001829 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001830 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001831 cstr ? cstr : "");
1832 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001833 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001834
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001835}
1836
1837void print_completion_result(CXCompletionResult *completion_result,
1838 CXClientData client_data) {
1839 FILE *file = (FILE *)client_data;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001840 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001841 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001842 enum CXCursorKind ParentKind;
1843 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001844 CXString BriefComment;
1845 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001846
Ted Kremenek29004672010-02-17 00:41:32 +00001847 fprintf(file, "%s:", clang_getCString(ks));
1848 clang_disposeString(ks);
1849
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001850 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001851 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001852 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001853 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1854 case CXAvailability_Available:
1855 break;
1856
1857 case CXAvailability_Deprecated:
1858 fprintf(file, " (deprecated)");
1859 break;
1860
1861 case CXAvailability_NotAvailable:
1862 fprintf(file, " (unavailable)");
1863 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001864
1865 case CXAvailability_NotAccessible:
1866 fprintf(file, " (inaccessible)");
1867 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001868 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001869
1870 annotationCount = clang_getCompletionNumAnnotations(
1871 completion_result->CompletionString);
1872 if (annotationCount) {
1873 unsigned i;
1874 fprintf(file, " (");
1875 for (i = 0; i < annotationCount; ++i) {
1876 if (i != 0)
1877 fprintf(file, ", ");
1878 fprintf(file, "\"%s\"",
1879 clang_getCString(clang_getCompletionAnnotation(
1880 completion_result->CompletionString, i)));
1881 }
1882 fprintf(file, ")");
1883 }
1884
Douglas Gregor78254c82012-03-27 23:34:16 +00001885 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1886 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1887 &ParentKind);
1888 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001889 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00001890 fprintf(file, " (parent: %s '%s')",
1891 clang_getCString(KindSpelling),
1892 clang_getCString(ParentName));
1893 clang_disposeString(KindSpelling);
1894 }
1895 clang_disposeString(ParentName);
1896 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001897
1898 BriefComment = clang_getCompletionBriefComment(
1899 completion_result->CompletionString);
1900 BriefCommentCString = clang_getCString(BriefComment);
1901 if (BriefCommentCString && *BriefCommentCString != '\0') {
1902 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1903 }
1904 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00001905
Douglas Gregorf757a122010-08-23 23:00:57 +00001906 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001907}
1908
Douglas Gregor21325842011-07-07 16:03:39 +00001909void print_completion_contexts(unsigned long long contexts, FILE *file) {
1910 fprintf(file, "Completion contexts:\n");
1911 if (contexts == CXCompletionContext_Unknown) {
1912 fprintf(file, "Unknown\n");
1913 }
1914 if (contexts & CXCompletionContext_AnyType) {
1915 fprintf(file, "Any type\n");
1916 }
1917 if (contexts & CXCompletionContext_AnyValue) {
1918 fprintf(file, "Any value\n");
1919 }
1920 if (contexts & CXCompletionContext_ObjCObjectValue) {
1921 fprintf(file, "Objective-C object value\n");
1922 }
1923 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1924 fprintf(file, "Objective-C selector value\n");
1925 }
1926 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1927 fprintf(file, "C++ class type value\n");
1928 }
1929 if (contexts & CXCompletionContext_DotMemberAccess) {
1930 fprintf(file, "Dot member access\n");
1931 }
1932 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1933 fprintf(file, "Arrow member access\n");
1934 }
1935 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1936 fprintf(file, "Objective-C property access\n");
1937 }
1938 if (contexts & CXCompletionContext_EnumTag) {
1939 fprintf(file, "Enum tag\n");
1940 }
1941 if (contexts & CXCompletionContext_UnionTag) {
1942 fprintf(file, "Union tag\n");
1943 }
1944 if (contexts & CXCompletionContext_StructTag) {
1945 fprintf(file, "Struct tag\n");
1946 }
1947 if (contexts & CXCompletionContext_ClassTag) {
1948 fprintf(file, "Class name\n");
1949 }
1950 if (contexts & CXCompletionContext_Namespace) {
1951 fprintf(file, "Namespace or namespace alias\n");
1952 }
1953 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1954 fprintf(file, "Nested name specifier\n");
1955 }
1956 if (contexts & CXCompletionContext_ObjCInterface) {
1957 fprintf(file, "Objective-C interface\n");
1958 }
1959 if (contexts & CXCompletionContext_ObjCProtocol) {
1960 fprintf(file, "Objective-C protocol\n");
1961 }
1962 if (contexts & CXCompletionContext_ObjCCategory) {
1963 fprintf(file, "Objective-C category\n");
1964 }
1965 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1966 fprintf(file, "Objective-C instance method\n");
1967 }
1968 if (contexts & CXCompletionContext_ObjCClassMessage) {
1969 fprintf(file, "Objective-C class method\n");
1970 }
1971 if (contexts & CXCompletionContext_ObjCSelectorName) {
1972 fprintf(file, "Objective-C selector name\n");
1973 }
1974 if (contexts & CXCompletionContext_MacroName) {
1975 fprintf(file, "Macro name\n");
1976 }
1977 if (contexts & CXCompletionContext_NaturalLanguage) {
1978 fprintf(file, "Natural language\n");
1979 }
1980}
1981
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001982int my_stricmp(const char *s1, const char *s2) {
1983 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00001984 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001985 if (c1 < c2)
1986 return -1;
1987 else if (c1 > c2)
1988 return 1;
1989
1990 ++s1;
1991 ++s2;
1992 }
1993
1994 if (*s1)
1995 return 1;
1996 else if (*s2)
1997 return -1;
1998 return 0;
1999}
2000
Douglas Gregor47815d52010-07-12 18:38:41 +00002001int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002002 const char *input = argv[1];
2003 char *filename = 0;
2004 unsigned line;
2005 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002006 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002007 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002008 struct CXUnsavedFile *unsaved_files = 0;
2009 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002010 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002011 enum CXErrorCode Err;
2012 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002013 unsigned I, Repeats = 1;
2014 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2015
2016 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2017 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002018 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2019 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002020
Douglas Gregor47815d52010-07-12 18:38:41 +00002021 if (timing_only)
2022 input += strlen("-code-completion-timing=");
2023 else
2024 input += strlen("-code-completion-at=");
2025
Ted Kremenek29004672010-02-17 00:41:32 +00002026 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002027 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002028 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002029
Douglas Gregor9485bf92009-12-02 09:21:34 +00002030 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2031 return -1;
2032
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002033 CIdx = clang_createIndex(0, 0);
2034
2035 if (getenv("CINDEXTEST_EDITING"))
2036 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002037
2038 Err = clang_parseTranslationUnit2(CIdx, 0,
2039 argv + num_unsaved_files + 2,
2040 argc - num_unsaved_files - 2,
2041 0, 0, getDefaultParsingOptions(), &TU);
2042 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002043 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002044 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002045 return 1;
2046 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002047
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002048 Err = clang_reparseTranslationUnit(TU, 0, 0,
2049 clang_defaultReparseOptions(TU));
2050
2051 if (Err != CXError_Success) {
Douglas Gregorc6592922010-11-15 23:00:34 +00002052 fprintf(stderr, "Unable to reparse translation init!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002053 describeLibclangFailure(Err);
2054 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002055 return 1;
2056 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002057
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002058 for (I = 0; I != Repeats; ++I) {
2059 results = clang_codeCompleteAt(TU, filename, line, column,
2060 unsaved_files, num_unsaved_files,
2061 completionOptions);
2062 if (!results) {
2063 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002064 return 1;
2065 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002066 if (I != Repeats-1)
2067 clang_disposeCodeCompleteResults(results);
2068 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002069
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002070 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002071 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002072 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002073 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002074 CXString objCSelector;
2075 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002076 if (!timing_only) {
2077 /* Sort the code-completion results based on the typed text. */
2078 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2079
Douglas Gregor47815d52010-07-12 18:38:41 +00002080 for (i = 0; i != n; ++i)
2081 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002082 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002083 n = clang_codeCompleteGetNumDiagnostics(results);
2084 for (i = 0; i != n; ++i) {
2085 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2086 PrintDiagnostic(diag);
2087 clang_disposeDiagnostic(diag);
2088 }
Douglas Gregor21325842011-07-07 16:03:39 +00002089
2090 contexts = clang_codeCompleteGetContexts(results);
2091 print_completion_contexts(contexts, stdout);
2092
Douglas Gregorea777402011-07-26 15:24:30 +00002093 containerKind = clang_codeCompleteGetContainerKind(results,
2094 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002095
2096 if (containerKind != CXCursor_InvalidCode) {
2097 /* We have found a container */
2098 CXString containerUSR, containerKindSpelling;
2099 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2100 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2101 clang_disposeString(containerKindSpelling);
2102
2103 if (containerIsIncomplete) {
2104 printf("Container is incomplete\n");
2105 }
2106 else {
2107 printf("Container is complete\n");
2108 }
2109
2110 containerUSR = clang_codeCompleteGetContainerUSR(results);
2111 printf("Container USR: %s\n", clang_getCString(containerUSR));
2112 clang_disposeString(containerUSR);
2113 }
2114
Douglas Gregorea777402011-07-26 15:24:30 +00002115 objCSelector = clang_codeCompleteGetObjCSelector(results);
2116 selectorString = clang_getCString(objCSelector);
2117 if (selectorString && strlen(selectorString) > 0) {
2118 printf("Objective-C selector: %s\n", selectorString);
2119 }
2120 clang_disposeString(objCSelector);
2121
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002122 clang_disposeCodeCompleteResults(results);
2123 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002124 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002125 clang_disposeIndex(CIdx);
2126 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002127
Douglas Gregor9485bf92009-12-02 09:21:34 +00002128 free_remapped_files(unsaved_files, num_unsaved_files);
2129
Ted Kremenekef3339b2009-11-17 18:09:14 +00002130 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002131}
2132
Douglas Gregor082c3e62010-01-15 19:40:17 +00002133typedef struct {
2134 char *filename;
2135 unsigned line;
2136 unsigned column;
2137} CursorSourceLocation;
2138
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002139static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002140 CXIndex CIdx;
2141 int errorCode;
2142 struct CXUnsavedFile *unsaved_files = 0;
2143 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002144 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002145 CXTranslationUnit TU;
2146 CXCursor Cursor;
2147 CursorSourceLocation *Locations = 0;
2148 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002149 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002150 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002151
Ted Kremenek29004672010-02-17 00:41:32 +00002152 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002153 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2154 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002155
Douglas Gregor082c3e62010-01-15 19:40:17 +00002156 /* Parse the locations. */
2157 assert(NumLocations > 0 && "Unable to count locations?");
2158 Locations = (CursorSourceLocation *)malloc(
2159 NumLocations * sizeof(CursorSourceLocation));
2160 for (Loc = 0; Loc < NumLocations; ++Loc) {
2161 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002162 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2163 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002164 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002165 return errorCode;
2166 }
Ted Kremenek29004672010-02-17 00:41:32 +00002167
2168 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002169 &num_unsaved_files))
2170 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002171
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002172 if (getenv("CINDEXTEST_EDITING"))
2173 Repeats = 5;
2174
2175 /* Parse the translation unit. When we're testing clang_getCursor() after
2176 reparsing, don't remap unsaved files until the second parse. */
2177 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002178 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2179 argv + num_unsaved_files + 1 + NumLocations,
2180 argc - num_unsaved_files - 2 - NumLocations,
2181 unsaved_files,
2182 Repeats > 1? 0 : num_unsaved_files,
2183 getDefaultParsingOptions(), &TU);
2184 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002185 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002186 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002187 return -1;
2188 }
Ted Kremenek29004672010-02-17 00:41:32 +00002189
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002190 if (checkForErrors(TU) != 0)
2191 return -1;
2192
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002193 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002194 if (Repeats > 1) {
2195 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2196 clang_defaultReparseOptions(TU));
2197 if (Err != CXError_Success) {
2198 describeLibclangFailure(Err);
2199 clang_disposeTranslationUnit(TU);
2200 return 1;
2201 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002202 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002203
2204 if (checkForErrors(TU) != 0)
2205 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002206
2207 for (Loc = 0; Loc < NumLocations; ++Loc) {
2208 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2209 if (!file)
2210 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002211
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002212 Cursor = clang_getCursor(TU,
2213 clang_getLocation(TU, file, Locations[Loc].line,
2214 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002215
2216 if (checkForErrors(TU) != 0)
2217 return -1;
2218
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002219 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002220 CXCompletionString completionString = clang_getCursorCompletionString(
2221 Cursor);
2222 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002223 CXString Spelling;
2224 const char *cspell;
2225 unsigned line, column;
2226 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2227 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002228 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002229 PrintCursorExtent(Cursor);
2230 Spelling = clang_getCursorSpelling(Cursor);
2231 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002232 if (cspell && strlen(cspell) != 0) {
2233 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002234 printf(" Spelling=%s (", cspell);
2235 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002236 CXSourceRange range =
2237 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002238 if (clang_Range_isNull(range))
2239 break;
2240 PrintRange(range, 0);
2241 }
2242 printf(")");
2243 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002244 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002245 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2246 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002247 if (clang_Cursor_isDynamicCall(Cursor))
2248 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002249 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002250 CXType T = clang_Cursor_getReceiverType(Cursor);
2251 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002252 printf(" Receiver-type=%s", clang_getCString(S));
2253 clang_disposeString(S);
2254 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002255
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002256 {
2257 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002258 CXFile astFile;
2259 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002260 unsigned i, numHeaders;
2261 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002262 astFile = clang_Module_getASTFile(mod);
2263 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002264 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002265 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002266 printf(" ModuleName=%s (%s) Headers(%d):",
2267 clang_getCString(name), clang_getCString(astFilename),
2268 numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002269 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002270 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002271 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002272 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2273 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002274 printf("\n%s", clang_getCString(filename));
2275 clang_disposeString(filename);
2276 }
2277 }
2278 }
2279
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002280 if (completionString != NULL) {
2281 printf("\nCompletion string: ");
2282 print_completion_string(completionString, stdout);
2283 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002284 printf("\n");
2285 free(Locations[Loc].filename);
2286 }
2287 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002288 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002289
Douglas Gregor33cdd812010-02-18 18:08:43 +00002290 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002291 clang_disposeTranslationUnit(TU);
2292 clang_disposeIndex(CIdx);
2293 free(Locations);
2294 free_remapped_files(unsaved_files, num_unsaved_files);
2295 return 0;
2296}
2297
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002298static enum CXVisitorResult findFileRefsVisit(void *context,
2299 CXCursor cursor, CXSourceRange range) {
2300 if (clang_Range_isNull(range))
2301 return CXVisit_Continue;
2302
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002303 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002304 PrintRange(range, "");
2305 printf("\n");
2306 return CXVisit_Continue;
2307}
2308
2309static int find_file_refs_at(int argc, const char **argv) {
2310 CXIndex CIdx;
2311 int errorCode;
2312 struct CXUnsavedFile *unsaved_files = 0;
2313 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002314 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002315 CXTranslationUnit TU;
2316 CXCursor Cursor;
2317 CursorSourceLocation *Locations = 0;
2318 unsigned NumLocations = 0, Loc;
2319 unsigned Repeats = 1;
2320 unsigned I;
2321
2322 /* Count the number of locations. */
2323 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2324 ++NumLocations;
2325
2326 /* Parse the locations. */
2327 assert(NumLocations > 0 && "Unable to count locations?");
2328 Locations = (CursorSourceLocation *)malloc(
2329 NumLocations * sizeof(CursorSourceLocation));
2330 for (Loc = 0; Loc < NumLocations; ++Loc) {
2331 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2332 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2333 &Locations[Loc].line,
2334 &Locations[Loc].column, 0, 0)))
2335 return errorCode;
2336 }
2337
2338 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2339 &num_unsaved_files))
2340 return -1;
2341
2342 if (getenv("CINDEXTEST_EDITING"))
2343 Repeats = 5;
2344
2345 /* Parse the translation unit. When we're testing clang_getCursor() after
2346 reparsing, don't remap unsaved files until the second parse. */
2347 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002348 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2349 argv + num_unsaved_files + 1 + NumLocations,
2350 argc - num_unsaved_files - 2 - NumLocations,
2351 unsaved_files,
2352 Repeats > 1? 0 : num_unsaved_files,
2353 getDefaultParsingOptions(), &TU);
2354 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002355 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002356 describeLibclangFailure(Err);
2357 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002358 return -1;
2359 }
2360
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002361 if (checkForErrors(TU) != 0)
2362 return -1;
2363
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002364 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002365 if (Repeats > 1) {
2366 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2367 clang_defaultReparseOptions(TU));
2368 if (Err != CXError_Success) {
2369 describeLibclangFailure(Err);
2370 clang_disposeTranslationUnit(TU);
2371 return 1;
2372 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002373 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002374
2375 if (checkForErrors(TU) != 0)
2376 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002377
2378 for (Loc = 0; Loc < NumLocations; ++Loc) {
2379 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2380 if (!file)
2381 continue;
2382
2383 Cursor = clang_getCursor(TU,
2384 clang_getLocation(TU, file, Locations[Loc].line,
2385 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002386
2387 if (checkForErrors(TU) != 0)
2388 return -1;
2389
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002390 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002391 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002392 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002393 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002394 clang_findReferencesInFile(Cursor, file, visitor);
2395 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002396
2397 if (checkForErrors(TU) != 0)
2398 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002399 }
2400 }
2401 }
2402
2403 PrintDiagnostics(TU);
2404 clang_disposeTranslationUnit(TU);
2405 clang_disposeIndex(CIdx);
2406 free(Locations);
2407 free_remapped_files(unsaved_files, num_unsaved_files);
2408 return 0;
2409}
2410
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002411static enum CXVisitorResult findFileIncludesVisit(void *context,
2412 CXCursor cursor, CXSourceRange range) {
2413 PrintCursor(cursor, NULL);
2414 PrintRange(range, "");
2415 printf("\n");
2416 return CXVisit_Continue;
2417}
2418
2419static int find_file_includes_in(int argc, const char **argv) {
2420 CXIndex CIdx;
2421 struct CXUnsavedFile *unsaved_files = 0;
2422 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002423 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002424 CXTranslationUnit TU;
2425 const char **Filenames = 0;
2426 unsigned NumFilenames = 0;
2427 unsigned Repeats = 1;
2428 unsigned I, FI;
2429
2430 /* Count the number of locations. */
2431 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2432 ++NumFilenames;
2433
2434 /* Parse the locations. */
2435 assert(NumFilenames > 0 && "Unable to count filenames?");
2436 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2437 for (I = 0; I < NumFilenames; ++I) {
2438 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2439 /* Copy the file name. */
2440 Filenames[I] = input;
2441 }
2442
2443 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2444 &num_unsaved_files))
2445 return -1;
2446
2447 if (getenv("CINDEXTEST_EDITING"))
2448 Repeats = 2;
2449
2450 /* Parse the translation unit. When we're testing clang_getCursor() after
2451 reparsing, don't remap unsaved files until the second parse. */
2452 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002453 Err = clang_parseTranslationUnit2(
2454 CIdx, argv[argc - 1],
2455 argv + num_unsaved_files + 1 + NumFilenames,
2456 argc - num_unsaved_files - 2 - NumFilenames,
2457 unsaved_files,
2458 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002459
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002460 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002461 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002462 describeLibclangFailure(Err);
2463 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002464 return -1;
2465 }
2466
2467 if (checkForErrors(TU) != 0)
2468 return -1;
2469
2470 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002471 if (Repeats > 1) {
2472 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2473 clang_defaultReparseOptions(TU));
2474 if (Err != CXError_Success) {
2475 describeLibclangFailure(Err);
2476 clang_disposeTranslationUnit(TU);
2477 return 1;
2478 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002479 }
2480
2481 if (checkForErrors(TU) != 0)
2482 return -1;
2483
2484 for (FI = 0; FI < NumFilenames; ++FI) {
2485 CXFile file = clang_getFile(TU, Filenames[FI]);
2486 if (!file)
2487 continue;
2488
2489 if (checkForErrors(TU) != 0)
2490 return -1;
2491
2492 if (I + 1 == Repeats) {
2493 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2494 clang_findIncludesInFile(TU, file, visitor);
2495
2496 if (checkForErrors(TU) != 0)
2497 return -1;
2498 }
2499 }
2500 }
2501
2502 PrintDiagnostics(TU);
2503 clang_disposeTranslationUnit(TU);
2504 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002505 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002506 free_remapped_files(unsaved_files, num_unsaved_files);
2507 return 0;
2508}
2509
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002510#define MAX_IMPORTED_ASTFILES 200
2511
2512typedef struct {
2513 char **filenames;
2514 unsigned num_files;
2515} ImportedASTFilesData;
2516
2517static ImportedASTFilesData *importedASTs_create() {
2518 ImportedASTFilesData *p;
2519 p = malloc(sizeof(ImportedASTFilesData));
2520 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2521 p->num_files = 0;
2522 return p;
2523}
2524
2525static void importedASTs_dispose(ImportedASTFilesData *p) {
2526 unsigned i;
2527 if (!p)
2528 return;
2529
2530 for (i = 0; i < p->num_files; ++i)
2531 free(p->filenames[i]);
2532 free(p->filenames);
2533 free(p);
2534}
2535
2536static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2537 unsigned i;
2538 assert(p && file);
2539 for (i = 0; i < p->num_files; ++i)
2540 if (strcmp(file, p->filenames[i]) == 0)
2541 return;
2542 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2543 p->filenames[p->num_files++] = strdup(file);
2544}
2545
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002546typedef struct {
2547 const char *check_prefix;
2548 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002549 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002550 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002551 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002552 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002553} IndexData;
2554
2555static void printCheck(IndexData *data) {
2556 if (data->check_prefix) {
2557 if (data->first_check_printed) {
2558 printf("// %s-NEXT: ", data->check_prefix);
2559 } else {
2560 printf("// %s : ", data->check_prefix);
2561 data->first_check_printed = 1;
2562 }
2563 }
2564}
2565
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002566static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002567 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002568 printf("%s", clang_getCString(filename));
2569 clang_disposeString(filename);
2570}
2571
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002572static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2573 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002574 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002575 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002576 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002577 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002578 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002579
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002580 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002581 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2582 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002583 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002584 return;
2585 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002586 if (!file) {
2587 printf("<no idxfile>");
2588 return;
2589 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002590 filename = clang_getFileName((CXFile)file);
2591 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002592 if (strcmp(cname, index_data->main_filename) == 0)
2593 isMainFile = 1;
2594 else
2595 isMainFile = 0;
2596 clang_disposeString(filename);
2597
2598 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002599 printCXIndexFile(file);
2600 printf(":");
2601 }
2602 printf("%d:%d", line, column);
2603}
2604
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002605static unsigned digitCount(unsigned val) {
2606 unsigned c = 1;
2607 while (1) {
2608 if (val < 10)
2609 return c;
2610 ++c;
2611 val /= 10;
2612 }
2613}
2614
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002615static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2616 CXIdxLoc loc) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002617 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002618 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002619 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002620 unsigned line, column;
2621
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002622 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002623 if (!name)
2624 name = "<anon-tag>";
2625
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002626 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Argyrios Kyrtzidis90068072011-10-20 17:21:46 +00002627 /* FIXME: free these.*/
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002628 newStr = (char *)malloc(strlen(name) +
2629 digitCount(line) + digitCount(column) + 3);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002630 sprintf(newStr, "%s:%d:%d", name, line, column);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002631 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002632}
2633
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002634static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2635 CXIdxClientContainer container;
2636 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002637 if (!container)
2638 printf("[<<NULL>>]");
2639 else
2640 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002641}
2642
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002643static const char *getEntityKindString(CXIdxEntityKind kind) {
2644 switch (kind) {
2645 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2646 case CXIdxEntity_Typedef: return "typedef";
2647 case CXIdxEntity_Function: return "function";
2648 case CXIdxEntity_Variable: return "variable";
2649 case CXIdxEntity_Field: return "field";
2650 case CXIdxEntity_EnumConstant: return "enumerator";
2651 case CXIdxEntity_ObjCClass: return "objc-class";
2652 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2653 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002654 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2655 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002656 case CXIdxEntity_ObjCProperty: return "objc-property";
2657 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2658 case CXIdxEntity_Enum: return "enum";
2659 case CXIdxEntity_Struct: return "struct";
2660 case CXIdxEntity_Union: return "union";
2661 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002662 case CXIdxEntity_CXXNamespace: return "namespace";
2663 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2664 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2665 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2666 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2667 case CXIdxEntity_CXXConstructor: return "constructor";
2668 case CXIdxEntity_CXXDestructor: return "destructor";
2669 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2670 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002671 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002672 }
2673 assert(0 && "Garbage entity kind");
2674 return 0;
2675}
2676
2677static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2678 switch (kind) {
2679 case CXIdxEntity_NonTemplate: return "";
2680 case CXIdxEntity_Template: return "-template";
2681 case CXIdxEntity_TemplatePartialSpecialization:
2682 return "-template-partial-spec";
2683 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002684 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002685 assert(0 && "Garbage entity kind");
2686 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002687}
2688
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002689static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2690 switch (kind) {
2691 case CXIdxEntityLang_None: return "<none>";
2692 case CXIdxEntityLang_C: return "C";
2693 case CXIdxEntityLang_ObjC: return "ObjC";
2694 case CXIdxEntityLang_CXX: return "C++";
2695 }
2696 assert(0 && "Garbage language kind");
2697 return 0;
2698}
2699
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002700static void printEntityInfo(const char *cb,
2701 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002702 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002703 const char *name;
2704 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002705 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002706 index_data = (IndexData *)client_data;
2707 printCheck(index_data);
2708
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002709 if (!info) {
2710 printf("%s: <<NULL>>", cb);
2711 return;
2712 }
2713
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002714 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002715 if (!name)
2716 name = "<anon-tag>";
2717
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002718 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2719 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002720 printf(" | name: %s", name);
2721 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002722 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002723
2724 for (i = 0; i != info->numAttributes; ++i) {
2725 const CXIdxAttrInfo *Attr = info->attributes[i];
2726 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002727 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002728 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002729}
2730
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002731static void printBaseClassInfo(CXClientData client_data,
2732 const CXIdxBaseClassInfo *info) {
2733 printEntityInfo(" <base>", client_data, info->base);
2734 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002735 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002736 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002737 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002738}
2739
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002740static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2741 CXClientData client_data) {
2742 unsigned i;
2743 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2744 printEntityInfo(" <protocol>", client_data,
2745 ProtoInfo->protocols[i]->protocol);
2746 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002747 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002748 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002749 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002750 printf("\n");
2751 }
2752}
2753
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002754static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002755 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002756 CXString str;
2757 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002758 unsigned numDiags, i;
2759 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002760 IndexData *index_data;
2761 index_data = (IndexData *)client_data;
2762 printCheck(index_data);
2763
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002764 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2765 for (i = 0; i != numDiags; ++i) {
2766 diag = clang_getDiagnosticInSet(diagSet, i);
2767 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2768 cstr = clang_getCString(str);
2769 printf("[diagnostic]: %s\n", cstr);
2770 clang_disposeString(str);
2771
2772 if (getenv("CINDEXTEST_FAILONERROR") &&
2773 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2774 index_data->fail_for_error = 1;
2775 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002776 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002777}
2778
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002779static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2780 CXFile file, void *reserved) {
2781 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002782 CXString filename;
2783
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002784 index_data = (IndexData *)client_data;
2785 printCheck(index_data);
2786
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002787 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002788 index_data->main_filename = clang_getCString(filename);
2789 clang_disposeString(filename);
2790
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002791 printf("[enteredMainFile]: ");
2792 printCXIndexFile((CXIdxClientFile)file);
2793 printf("\n");
2794
2795 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002796}
2797
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002798static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002799 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002800 IndexData *index_data;
2801 index_data = (IndexData *)client_data;
2802 printCheck(index_data);
2803
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002804 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002805 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002806 printf(" | name: \"%s\"", info->filename);
2807 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002808 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002809 printf(" | isImport: %d | isAngled: %d | isModule: %d\n",
2810 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002811
2812 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002813}
2814
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002815static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2816 const CXIdxImportedASTFileInfo *info) {
2817 IndexData *index_data;
2818 index_data = (IndexData *)client_data;
2819 printCheck(index_data);
2820
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002821 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002822 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002823 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2824 clang_disposeString(filename);
2825 }
2826
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002827 printf("[importedASTFile]: ");
2828 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002829 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002830 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002831 printf(" | loc: ");
2832 printCXIndexLoc(info->loc, client_data);
2833 printf(" | name: \"%s\"", clang_getCString(name));
2834 printf(" | isImplicit: %d\n", info->isImplicit);
2835 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002836 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002837 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002838 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002839 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002840
2841 return (CXIdxClientFile)info->file;
2842}
2843
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002844static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002845 void *reserved) {
2846 IndexData *index_data;
2847 index_data = (IndexData *)client_data;
2848 printCheck(index_data);
2849
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002850 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002851 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002852}
2853
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002854static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002855 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002856 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002857 const CXIdxObjCCategoryDeclInfo *CatInfo;
2858 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002859 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002860 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002861 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002862 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002863 index_data = (IndexData *)client_data;
2864
2865 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2866 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002867 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002868 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002869 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00002870 printf(" | semantic-container: ");
2871 printCXIndexContainer(info->semanticContainer);
2872 printf(" | lexical-container: ");
2873 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002874 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002875 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002876 if (info->flags & CXIdxDeclFlag_Skipped) {
2877 assert(!info->isContainer);
2878 printf(" | isContainer: skipped");
2879 } else {
2880 printf(" | isContainer: %d", info->isContainer);
2881 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002882 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002883
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002884 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00002885 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002886 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002887 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002888 printf("\n");
2889 }
2890
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002891 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2892 const char *kindName = 0;
2893 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2894 switch (K) {
2895 case CXIdxObjCContainer_ForwardRef:
2896 kindName = "forward-ref"; break;
2897 case CXIdxObjCContainer_Interface:
2898 kindName = "interface"; break;
2899 case CXIdxObjCContainer_Implementation:
2900 kindName = "implementation"; break;
2901 }
2902 printCheck(index_data);
2903 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2904 }
2905
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002906 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002907 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2908 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00002909 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002910 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00002911 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002912 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002913 printf("\n");
2914 }
2915
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002916 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2917 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002918 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002919 printf("\n");
2920 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002921 }
2922
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002923 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2924 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002925 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002926
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002927 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2928 if (PropInfo->getter) {
2929 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2930 printf("\n");
2931 }
2932 if (PropInfo->setter) {
2933 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2934 printf("\n");
2935 }
2936 }
2937
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002938 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2939 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2940 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2941 printf("\n");
2942 }
2943 }
2944
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002945 if (info->declAsContainer)
2946 clang_index_setClientContainer(info->declAsContainer,
2947 makeClientContainer(info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002948}
2949
2950static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002951 const CXIdxEntityRefInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002952 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002953 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002954 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002955 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002956 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002957 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002958 printf(" | container: ");
2959 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002960 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00002961 switch (info->kind) {
2962 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002963 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00002964 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002965 printf("\n");
2966}
2967
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002968static int index_abortQuery(CXClientData client_data, void *reserved) {
2969 IndexData *index_data;
2970 index_data = (IndexData *)client_data;
2971 return index_data->abort;
2972}
2973
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002974static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002975 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002976 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002977 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002978 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002979 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002980 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002981 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002982 index_indexEntityReference
2983};
2984
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00002985static unsigned getIndexOptions(void) {
2986 unsigned index_opts;
2987 index_opts = 0;
2988 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2989 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2990 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2991 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002992 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
2993 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00002994
2995 return index_opts;
2996}
2997
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00002998static int index_compile_args(int num_args, const char **args,
2999 CXIndexAction idxAction,
3000 ImportedASTFilesData *importedASTs,
3001 const char *check_prefix) {
3002 IndexData index_data;
3003 unsigned index_opts;
3004 int result;
3005
3006 if (num_args == 0) {
3007 fprintf(stderr, "no compiler arguments\n");
3008 return -1;
3009 }
3010
3011 index_data.check_prefix = check_prefix;
3012 index_data.first_check_printed = 0;
3013 index_data.fail_for_error = 0;
3014 index_data.abort = 0;
3015 index_data.main_filename = "";
3016 index_data.importedASTs = importedASTs;
3017
3018 index_opts = getIndexOptions();
3019 result = clang_indexSourceFile(idxAction, &index_data,
3020 &IndexCB,sizeof(IndexCB), index_opts,
3021 0, args, num_args, 0, 0, 0,
3022 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003023 if (result != CXError_Success)
3024 describeLibclangFailure(result);
3025
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003026 if (index_data.fail_for_error)
3027 result = -1;
3028
3029 return result;
3030}
3031
3032static int index_ast_file(const char *ast_file,
3033 CXIndex Idx,
3034 CXIndexAction idxAction,
3035 ImportedASTFilesData *importedASTs,
3036 const char *check_prefix) {
3037 CXTranslationUnit TU;
3038 IndexData index_data;
3039 unsigned index_opts;
3040 int result;
3041
3042 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3043 return -1;
3044
3045 index_data.check_prefix = check_prefix;
3046 index_data.first_check_printed = 0;
3047 index_data.fail_for_error = 0;
3048 index_data.abort = 0;
3049 index_data.main_filename = "";
3050 index_data.importedASTs = importedASTs;
3051
3052 index_opts = getIndexOptions();
3053 result = clang_indexTranslationUnit(idxAction, &index_data,
3054 &IndexCB,sizeof(IndexCB),
3055 index_opts, TU);
3056 if (index_data.fail_for_error)
3057 result = -1;
3058
3059 clang_disposeTranslationUnit(TU);
3060 return result;
3061}
3062
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003063static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003064 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003065 CXIndex Idx;
3066 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003067 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003068 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003069
3070 check_prefix = 0;
3071 if (argc > 0) {
3072 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3073 check_prefix = argv[0] + strlen("-check-prefix=");
3074 ++argv;
3075 --argc;
3076 }
3077 }
3078
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003079 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003080 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003081 fprintf(stderr, "Could not create Index\n");
3082 return 1;
3083 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003084 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003085 importedASTs = 0;
3086 if (full)
3087 importedASTs = importedASTs_create();
3088
3089 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3090 if (result != 0)
3091 goto finished;
3092
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003093 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003094 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003095 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3096 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3097 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003098 }
3099 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003100
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003101finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003102 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003103 clang_IndexAction_dispose(idxAction);
3104 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003105 return result;
3106}
3107
3108static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003109 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003110 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003111 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003112 int result;
3113
3114 check_prefix = 0;
3115 if (argc > 0) {
3116 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3117 check_prefix = argv[0] + strlen("-check-prefix=");
3118 ++argv;
3119 --argc;
3120 }
3121 }
3122
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003123 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003124 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003125 fprintf(stderr, "Could not create Index\n");
3126 return 1;
3127 }
3128 idxAction = clang_IndexAction_create(Idx);
3129
3130 result = index_ast_file(argv[0], Idx, idxAction,
3131 /*importedASTs=*/0, check_prefix);
3132
3133 clang_IndexAction_dispose(idxAction);
3134 clang_disposeIndex(Idx);
3135 return result;
3136}
3137
3138static int index_compile_db(int argc, const char **argv) {
3139 const char *check_prefix;
3140 CXIndex Idx;
3141 CXIndexAction idxAction;
3142 int errorCode = 0;
3143
3144 check_prefix = 0;
3145 if (argc > 0) {
3146 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3147 check_prefix = argv[0] + strlen("-check-prefix=");
3148 ++argv;
3149 --argc;
3150 }
3151 }
3152
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003153 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003154 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003155 return -1;
3156 }
3157
3158 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003159 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003160 fprintf(stderr, "Could not create Index\n");
3161 return 1;
3162 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003163 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003164
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003165 {
3166 const char *database = argv[0];
3167 CXCompilationDatabase db = 0;
3168 CXCompileCommands CCmds = 0;
3169 CXCompileCommand CCmd;
3170 CXCompilationDatabase_Error ec;
3171 CXString wd;
3172#define MAX_COMPILE_ARGS 512
3173 CXString cxargs[MAX_COMPILE_ARGS];
3174 const char *args[MAX_COMPILE_ARGS];
3175 char *tmp;
3176 unsigned len;
3177 char *buildDir;
3178 int i, a, numCmds, numArgs;
3179
3180 len = strlen(database);
3181 tmp = (char *) malloc(len+1);
3182 memcpy(tmp, database, len+1);
3183 buildDir = dirname(tmp);
3184
3185 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3186
3187 if (db) {
3188
3189 if (ec!=CXCompilationDatabase_NoError) {
3190 printf("unexpected error %d code while loading compilation database\n", ec);
3191 errorCode = -1;
3192 goto cdb_end;
3193 }
3194
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003195 if (chdir(buildDir) != 0) {
3196 printf("Could not chdir to %s\n", buildDir);
3197 errorCode = -1;
3198 goto cdb_end;
3199 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003200
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003201 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003202 if (!CCmds) {
3203 printf("compilation db is empty\n");
3204 errorCode = -1;
3205 goto cdb_end;
3206 }
3207
3208 numCmds = clang_CompileCommands_getSize(CCmds);
3209
3210 if (numCmds==0) {
3211 fprintf(stderr, "should not get an empty compileCommand set\n");
3212 errorCode = -1;
3213 goto cdb_end;
3214 }
3215
3216 for (i=0; i<numCmds && errorCode == 0; ++i) {
3217 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3218
3219 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003220 if (chdir(clang_getCString(wd)) != 0) {
3221 printf("Could not chdir to %s\n", clang_getCString(wd));
3222 errorCode = -1;
3223 goto cdb_end;
3224 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003225 clang_disposeString(wd);
3226
3227 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3228 if (numArgs > MAX_COMPILE_ARGS){
3229 fprintf(stderr, "got more compile arguments than maximum\n");
3230 errorCode = -1;
3231 goto cdb_end;
3232 }
3233 for (a=0; a<numArgs; ++a) {
3234 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3235 args[a] = clang_getCString(cxargs[a]);
3236 }
3237
3238 errorCode = index_compile_args(numArgs, args, idxAction,
3239 /*importedASTs=*/0, check_prefix);
3240
3241 for (a=0; a<numArgs; ++a)
3242 clang_disposeString(cxargs[a]);
3243 }
3244 } else {
3245 printf("database loading failed with error code %d.\n", ec);
3246 errorCode = -1;
3247 }
3248
3249 cdb_end:
3250 clang_CompileCommands_dispose(CCmds);
3251 clang_CompilationDatabase_dispose(db);
3252 free(tmp);
3253
3254 }
3255
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003256 clang_IndexAction_dispose(idxAction);
3257 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003258 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003259}
3260
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003261int perform_token_annotation(int argc, const char **argv) {
3262 const char *input = argv[1];
3263 char *filename = 0;
3264 unsigned line, second_line;
3265 unsigned column, second_column;
3266 CXIndex CIdx;
3267 CXTranslationUnit TU = 0;
3268 int errorCode;
3269 struct CXUnsavedFile *unsaved_files = 0;
3270 int num_unsaved_files = 0;
3271 CXToken *tokens;
3272 unsigned num_tokens;
3273 CXSourceRange range;
3274 CXSourceLocation startLoc, endLoc;
3275 CXFile file = 0;
3276 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003277 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003278 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003279 unsigned i;
3280
3281 input += strlen("-test-annotate-tokens=");
3282 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3283 &second_line, &second_column)))
3284 return errorCode;
3285
Richard Smith1ea42eb2012-07-05 08:20:49 +00003286 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3287 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003288 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003289 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003290
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003291 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003292 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3293 argv + num_unsaved_files + 2,
3294 argc - num_unsaved_files - 3,
3295 unsaved_files,
3296 num_unsaved_files,
3297 getDefaultParsingOptions(), &TU);
3298 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003299 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003300 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003301 clang_disposeIndex(CIdx);
3302 free(filename);
3303 free_remapped_files(unsaved_files, num_unsaved_files);
3304 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003305 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003306 errorCode = 0;
3307
Richard Smith1ea42eb2012-07-05 08:20:49 +00003308 if (checkForErrors(TU) != 0) {
3309 errorCode = -1;
3310 goto teardown;
3311 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003312
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003313 if (getenv("CINDEXTEST_EDITING")) {
3314 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003315 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3316 clang_defaultReparseOptions(TU));
3317 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003318 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003319 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003320 errorCode = -1;
3321 goto teardown;
3322 }
3323 }
3324 }
3325
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003326 if (checkForErrors(TU) != 0) {
3327 errorCode = -1;
3328 goto teardown;
3329 }
3330
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003331 file = clang_getFile(TU, filename);
3332 if (!file) {
3333 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3334 errorCode = -1;
3335 goto teardown;
3336 }
3337
3338 startLoc = clang_getLocation(TU, file, line, column);
3339 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003340 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003341 column);
3342 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003343 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003344 }
3345
3346 endLoc = clang_getLocation(TU, file, second_line, second_column);
3347 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003348 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003349 second_line, second_column);
3350 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003351 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003352 }
3353
3354 range = clang_getRange(startLoc, endLoc);
3355 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003356
3357 if (checkForErrors(TU) != 0) {
3358 errorCode = -1;
3359 goto teardown;
3360 }
3361
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003362 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3363 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003364
3365 if (checkForErrors(TU) != 0) {
3366 errorCode = -1;
3367 goto teardown;
3368 }
3369
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003370 skipped_ranges = clang_getSkippedRanges(TU, file);
3371 for (i = 0; i != skipped_ranges->count; ++i) {
3372 unsigned start_line, start_column, end_line, end_column;
3373 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3374 0, &start_line, &start_column, 0);
3375 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3376 0, &end_line, &end_column, 0);
3377 printf("Skipping: ");
3378 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3379 printf("\n");
3380 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003381 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003382
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003383 for (i = 0; i != num_tokens; ++i) {
3384 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003385 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3386 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003387 unsigned start_line, start_column, end_line, end_column;
3388
3389 switch (clang_getTokenKind(tokens[i])) {
3390 case CXToken_Punctuation: kind = "Punctuation"; break;
3391 case CXToken_Keyword: kind = "Keyword"; break;
3392 case CXToken_Identifier: kind = "Identifier"; break;
3393 case CXToken_Literal: kind = "Literal"; break;
3394 case CXToken_Comment: kind = "Comment"; break;
3395 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003396 clang_getSpellingLocation(clang_getRangeStart(extent),
3397 0, &start_line, &start_column, 0);
3398 clang_getSpellingLocation(clang_getRangeEnd(extent),
3399 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003400 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003401 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003402 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003403 if (!clang_isInvalid(cursors[i].kind)) {
3404 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003405 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003406 }
3407 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003408 }
3409 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003410 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003411
3412 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003413 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003414 clang_disposeTranslationUnit(TU);
3415 clang_disposeIndex(CIdx);
3416 free(filename);
3417 free_remapped_files(unsaved_files, num_unsaved_files);
3418 return errorCode;
3419}
3420
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003421static int
3422perform_test_compilation_db(const char *database, int argc, const char **argv) {
3423 CXCompilationDatabase db;
3424 CXCompileCommands CCmds;
3425 CXCompileCommand CCmd;
3426 CXCompilationDatabase_Error ec;
3427 CXString wd;
3428 CXString arg;
3429 int errorCode = 0;
3430 char *tmp;
3431 unsigned len;
3432 char *buildDir;
3433 int i, j, a, numCmds, numArgs;
3434
3435 len = strlen(database);
3436 tmp = (char *) malloc(len+1);
3437 memcpy(tmp, database, len+1);
3438 buildDir = dirname(tmp);
3439
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003440 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003441
3442 if (db) {
3443
3444 if (ec!=CXCompilationDatabase_NoError) {
3445 printf("unexpected error %d code while loading compilation database\n", ec);
3446 errorCode = -1;
3447 goto cdb_end;
3448 }
3449
3450 for (i=0; i<argc && errorCode==0; ) {
3451 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003452 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003453
3454 if (!CCmds) {
3455 printf("file %s not found in compilation db\n", argv[i+1]);
3456 errorCode = -1;
3457 break;
3458 }
3459
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003460 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003461
3462 if (numCmds==0) {
3463 fprintf(stderr, "should not get an empty compileCommand set for file"
3464 " '%s'\n", argv[i+1]);
3465 errorCode = -1;
3466 break;
3467 }
3468
3469 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003470 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003471
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003472 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003473 printf("workdir:'%s'", clang_getCString(wd));
3474 clang_disposeString(wd);
3475
3476 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003477 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003478 for (a=0; a<numArgs; ++a) {
3479 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003480 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003481 printf("%s", clang_getCString(arg));
3482 clang_disposeString(arg);
3483 }
3484 printf("'\n");
3485 }
3486
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003487 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003488
3489 i += 2;
3490 }
3491 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003492 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003493 } else {
3494 printf("database loading failed with error code %d.\n", ec);
3495 errorCode = -1;
3496 }
3497
3498cdb_end:
3499 free(tmp);
3500
3501 return errorCode;
3502}
3503
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003504/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003505/* USR printing. */
3506/******************************************************************************/
3507
3508static int insufficient_usr(const char *kind, const char *usage) {
3509 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3510 return 1;
3511}
3512
3513static unsigned isUSR(const char *s) {
3514 return s[0] == 'c' && s[1] == ':';
3515}
3516
3517static int not_usr(const char *s, const char *arg) {
3518 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3519 return 1;
3520}
3521
3522static void print_usr(CXString usr) {
3523 const char *s = clang_getCString(usr);
3524 printf("%s\n", s);
3525 clang_disposeString(usr);
3526}
3527
3528static void display_usrs() {
3529 fprintf(stderr, "-print-usrs options:\n"
3530 " ObjCCategory <class name> <category name>\n"
3531 " ObjCClass <class name>\n"
3532 " ObjCIvar <ivar name> <class USR>\n"
3533 " ObjCMethod <selector> [0=class method|1=instance method] "
3534 "<class USR>\n"
3535 " ObjCProperty <property name> <class USR>\n"
3536 " ObjCProtocol <protocol name>\n");
3537}
3538
3539int print_usrs(const char **I, const char **E) {
3540 while (I != E) {
3541 const char *kind = *I;
3542 unsigned len = strlen(kind);
3543 switch (len) {
3544 case 8:
3545 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3546 if (I + 2 >= E)
3547 return insufficient_usr(kind, "<ivar name> <class USR>");
3548 if (!isUSR(I[2]))
3549 return not_usr("<class USR>", I[2]);
3550 else {
3551 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003552 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003553 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003554 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3555 }
3556
3557 I += 3;
3558 continue;
3559 }
3560 break;
3561 case 9:
3562 if (memcmp(kind, "ObjCClass", 9) == 0) {
3563 if (I + 1 >= E)
3564 return insufficient_usr(kind, "<class name>");
3565 print_usr(clang_constructUSR_ObjCClass(I[1]));
3566 I += 2;
3567 continue;
3568 }
3569 break;
3570 case 10:
3571 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3572 if (I + 3 >= E)
3573 return insufficient_usr(kind, "<method selector> "
3574 "[0=class method|1=instance method] <class USR>");
3575 if (!isUSR(I[3]))
3576 return not_usr("<class USR>", I[3]);
3577 else {
3578 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003579 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003580 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003581 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3582 }
3583 I += 4;
3584 continue;
3585 }
3586 break;
3587 case 12:
3588 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3589 if (I + 2 >= E)
3590 return insufficient_usr(kind, "<class name> <category name>");
3591 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3592 I += 3;
3593 continue;
3594 }
3595 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3596 if (I + 1 >= E)
3597 return insufficient_usr(kind, "<protocol name>");
3598 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3599 I += 2;
3600 continue;
3601 }
3602 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3603 if (I + 2 >= E)
3604 return insufficient_usr(kind, "<property name> <class USR>");
3605 if (!isUSR(I[2]))
3606 return not_usr("<class USR>", I[2]);
3607 else {
3608 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003609 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003610 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003611 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3612 }
3613 I += 3;
3614 continue;
3615 }
3616 break;
3617 default:
3618 break;
3619 }
3620 break;
3621 }
3622
3623 if (I != E) {
3624 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3625 display_usrs();
3626 return 1;
3627 }
3628 return 0;
3629}
3630
3631int print_usrs_file(const char *file_name) {
3632 char line[2048];
3633 const char *args[128];
3634 unsigned numChars = 0;
3635
3636 FILE *fp = fopen(file_name, "r");
3637 if (!fp) {
3638 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3639 return 1;
3640 }
3641
3642 /* This code is not really all that safe, but it works fine for testing. */
3643 while (!feof(fp)) {
3644 char c = fgetc(fp);
3645 if (c == '\n') {
3646 unsigned i = 0;
3647 const char *s = 0;
3648
3649 if (numChars == 0)
3650 continue;
3651
3652 line[numChars] = '\0';
3653 numChars = 0;
3654
3655 if (line[0] == '/' && line[1] == '/')
3656 continue;
3657
3658 s = strtok(line, " ");
3659 while (s) {
3660 args[i] = s;
3661 ++i;
3662 s = strtok(0, " ");
3663 }
3664 if (print_usrs(&args[0], &args[i]))
3665 return 1;
3666 }
3667 else
3668 line[numChars++] = c;
3669 }
3670
3671 fclose(fp);
3672 return 0;
3673}
3674
3675/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003676/* Command line processing. */
3677/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003678int write_pch_file(const char *filename, int argc, const char *argv[]) {
3679 CXIndex Idx;
3680 CXTranslationUnit TU;
3681 struct CXUnsavedFile *unsaved_files = 0;
3682 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003683 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003684 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003685
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003686 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003687
3688 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3689 clang_disposeIndex(Idx);
3690 return -1;
3691 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003692
3693 Err = clang_parseTranslationUnit2(
3694 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3695 unsaved_files, num_unsaved_files,
3696 CXTranslationUnit_Incomplete |
3697 CXTranslationUnit_DetailedPreprocessingRecord |
3698 CXTranslationUnit_ForSerialization,
3699 &TU);
3700 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003701 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003702 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003703 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003704 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003705 clang_disposeIndex(Idx);
3706 return 1;
3707 }
3708
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003709 switch (clang_saveTranslationUnit(TU, filename,
3710 clang_defaultSaveOptions(TU))) {
3711 case CXSaveError_None:
3712 break;
3713
3714 case CXSaveError_TranslationErrors:
3715 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3716 filename);
3717 result = 2;
3718 break;
3719
3720 case CXSaveError_InvalidTU:
3721 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3722 filename);
3723 result = 3;
3724 break;
3725
3726 case CXSaveError_Unknown:
3727 default:
3728 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3729 result = 1;
3730 break;
3731 }
3732
Douglas Gregore9386682010-08-13 05:36:37 +00003733 clang_disposeTranslationUnit(TU);
3734 free_remapped_files(unsaved_files, num_unsaved_files);
3735 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003736 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003737}
3738
3739/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003740/* Serialized diagnostics. */
3741/******************************************************************************/
3742
3743static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3744 switch (error) {
3745 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3746 case CXLoadDiag_None: break;
3747 case CXLoadDiag_Unknown: return "Unknown";
3748 case CXLoadDiag_InvalidFile: return "Invalid File";
3749 }
3750 return "None";
3751}
3752
3753static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3754 switch (severity) {
3755 case CXDiagnostic_Note: return "note";
3756 case CXDiagnostic_Error: return "error";
3757 case CXDiagnostic_Fatal: return "fatal";
3758 case CXDiagnostic_Ignored: return "ignored";
3759 case CXDiagnostic_Warning: return "warning";
3760 }
3761 return "unknown";
3762}
3763
3764static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003765 if (indent == 0)
3766 return;
3767 fprintf(stderr, "+");
3768 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003769 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003770 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003771 --indent;
3772 }
3773}
3774
3775static void printLocation(CXSourceLocation L) {
3776 CXFile File;
3777 CXString FileName;
3778 unsigned line, column, offset;
3779
3780 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3781 FileName = clang_getFileName(File);
3782
3783 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3784 clang_disposeString(FileName);
3785}
3786
3787static void printRanges(CXDiagnostic D, unsigned indent) {
3788 unsigned i, n = clang_getDiagnosticNumRanges(D);
3789
3790 for (i = 0; i < n; ++i) {
3791 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003792 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003793 Start = clang_getRangeStart(SR);
3794 End = clang_getRangeEnd(SR);
3795
3796 printIndent(indent);
3797 fprintf(stderr, "Range: ");
3798 printLocation(Start);
3799 fprintf(stderr, " ");
3800 printLocation(End);
3801 fprintf(stderr, "\n");
3802 }
3803}
3804
3805static void printFixIts(CXDiagnostic D, unsigned indent) {
3806 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003807 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003808 for (i = 0 ; i < n; ++i) {
3809 CXSourceRange ReplacementRange;
3810 CXString text;
3811 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3812
3813 printIndent(indent);
3814 fprintf(stderr, "FIXIT: (");
3815 printLocation(clang_getRangeStart(ReplacementRange));
3816 fprintf(stderr, " - ");
3817 printLocation(clang_getRangeEnd(ReplacementRange));
3818 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3819 clang_disposeString(text);
3820 }
3821}
3822
3823static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003824 unsigned i, n;
3825
Ted Kremenekd010ba42011-11-10 08:43:12 +00003826 if (!Diags)
3827 return;
3828
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003829 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003830 for (i = 0; i < n; ++i) {
3831 CXSourceLocation DiagLoc;
3832 CXDiagnostic D;
3833 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003834 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003835 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003836 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003837
3838 D = clang_getDiagnosticInSet(Diags, i);
3839 DiagLoc = clang_getDiagnosticLocation(D);
3840 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3841 FileName = clang_getFileName(File);
3842 DiagSpelling = clang_getDiagnosticSpelling(D);
3843
3844 printIndent(indent);
3845
3846 fprintf(stderr, "%s:%d:%d: %s: %s",
3847 clang_getCString(FileName),
3848 line,
3849 column,
3850 getSeverityString(clang_getDiagnosticSeverity(D)),
3851 clang_getCString(DiagSpelling));
3852
3853 DiagOption = clang_getDiagnosticOption(D, 0);
3854 DiagOptionStr = clang_getCString(DiagOption);
3855 if (DiagOptionStr) {
3856 fprintf(stderr, " [%s]", DiagOptionStr);
3857 }
3858
Ted Kremenek26a6d492012-04-12 00:03:31 +00003859 DiagCat = clang_getDiagnosticCategoryText(D);
3860 DiagCatStr = clang_getCString(DiagCat);
3861 if (DiagCatStr) {
3862 fprintf(stderr, " [%s]", DiagCatStr);
3863 }
3864
Ted Kremenekd010ba42011-11-10 08:43:12 +00003865 fprintf(stderr, "\n");
3866
3867 printRanges(D, indent);
3868 printFixIts(D, indent);
3869
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00003870 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00003871 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3872
3873 clang_disposeString(FileName);
3874 clang_disposeString(DiagSpelling);
3875 clang_disposeString(DiagOption);
3876 }
3877}
3878
3879static int read_diagnostics(const char *filename) {
3880 enum CXLoadDiag_Error error;
3881 CXString errorString;
3882 CXDiagnosticSet Diags = 0;
3883
3884 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3885 if (!Diags) {
3886 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3887 getDiagnosticCodeStr(error),
3888 clang_getCString(errorString));
3889 clang_disposeString(errorString);
3890 return 1;
3891 }
3892
3893 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003894 fprintf(stderr, "Number of diagnostics: %d\n",
3895 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00003896 clang_disposeDiagnosticSet(Diags);
3897 return 0;
3898}
3899
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003900static int perform_print_build_session_timestamp(void) {
3901 printf("%lld\n", clang_getBuildSessionTimestamp());
3902 return 0;
3903}
3904
Ted Kremenekd010ba42011-11-10 08:43:12 +00003905/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003906/* Command line processing. */
3907/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00003908
Douglas Gregor720d0052010-01-20 21:32:04 +00003909static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003910 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00003911 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003912 if (strcmp(s, "-usrs") == 0)
3913 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00003914 if (strncmp(s, "-memory-usage", 13) == 0)
3915 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003916 return NULL;
3917}
3918
Ted Kremenekef3339b2009-11-17 18:09:14 +00003919static void print_usage(void) {
3920 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003921 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003922 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00003923 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00003924 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
3925 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00003926 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003927 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003928 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003929 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003930 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00003931 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00003932 "[FileCheck prefix]\n");
3933 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00003934 " c-index-test -test-load-tu <AST file> <symbol filter> "
3935 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003936 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3937 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003938 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00003939 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00003940 " c-index-test -test-load-source-memory-usage "
3941 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00003942 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3943 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003944 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00003945 " c-index-test -test-load-source-usrs-memory-usage "
3946 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00003947 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3948 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00003949 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00003950 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00003951 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00003952 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00003953 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00003954 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00003955 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00003956 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00003957 " c-index-test -write-pch <file> <compiler arguments>\n");
3958 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003959 " c-index-test -compilation-db [lookup <filename>] database\n");
3960 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003961 " c-index-test -print-build-session-timestamp\n");
3962 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00003963 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00003964 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003965 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003966 " all - load all symbols, including those from PCH\n"
3967 " local - load all symbols except those in PCH\n"
3968 " category - only load ObjC categories (non-PCH)\n"
3969 " interface - only load ObjC interfaces (non-PCH)\n"
3970 " protocol - only load ObjC protocols (non-PCH)\n"
3971 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00003972 " typedef - only load typdefs (non-PCH)\n"
3973 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00003974}
3975
Daniel Dunbar08b33d02010-09-30 20:39:47 +00003976/***/
3977
3978int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003979 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00003980 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3981 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00003982 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00003983 return perform_code_completion(argc, argv, 0);
3984 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3985 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00003986 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3987 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00003988 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3989 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00003990 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
3991 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003992 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003993 return index_file(argc - 2, argv + 2, /*full=*/0);
3994 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
3995 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003996 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3997 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003998 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
3999 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004000 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004001 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004002 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004003 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4004 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004005 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004006 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4007 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4008 if (I) {
4009 int trials = atoi(argv[2]);
4010 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4011 NULL);
4012 }
4013 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004014 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004015 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004016
4017 PostVisitTU postVisit = 0;
4018 if (strstr(argv[1], "-memory-usage"))
4019 postVisit = PrintMemoryUsage;
4020
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004021 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004022 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4023 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004024 }
4025 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004026 return perform_file_scan(argv[2], argv[3],
4027 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004028 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4029 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004030 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4031 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4032 PrintInclusionStack);
4033 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4034 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4035 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004036 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4037 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4038 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004039 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004040 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004041 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004042 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4043 return perform_test_load_source(argc - 2, argv + 2, "all",
4044 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004045 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4046 return perform_test_load_source(argc - 2, argv + 2, "all",
4047 PrintBitWidth, 0);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004048 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4049 if (argc > 2)
4050 return print_usrs(argv + 2, argv + argc);
4051 else {
4052 display_usrs();
4053 return 1;
4054 }
4055 }
4056 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4057 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004058 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4059 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004060 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4061 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004062 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4063 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004064
Ted Kremenekef3339b2009-11-17 18:09:14 +00004065 print_usage();
4066 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004067}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004068
4069/***/
4070
4071/* We intentionally run in a separate thread to ensure we at least minimal
4072 * testing of a multithreaded environment (for example, having a reduced stack
4073 * size). */
4074
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004075typedef struct thread_info {
4076 int argc;
4077 const char **argv;
4078 int result;
4079} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004080void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004081 thread_info *client_data = client_data_v;
4082 client_data->result = cindextest_main(client_data->argc, client_data->argv);
NAKAMURA Takumia7d49882012-04-07 06:59:28 +00004083#ifdef __CYGWIN__
4084 fflush(stdout); /* stdout is not flushed on Cygwin. */
4085#endif
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004086}
4087
4088int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004089 thread_info client_data;
4090
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004091#ifdef CLANG_HAVE_LIBXML
4092 LIBXML_TEST_VERSION
4093#endif
4094
Douglas Gregorf428bf82010-10-27 16:00:01 +00004095 if (getenv("CINDEXTEST_NOTHREADS"))
4096 return cindextest_main(argc, argv);
4097
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004098 client_data.argc = argc;
4099 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004100 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004101 return client_data.result;
4102}