blob: 461765c13a8ebe105f0d61acff30dcbc40e84da4 [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 {
1336 const char *FieldName = clang_getCString(clang_getCursorSpelling(cursor));
1337 /* recurse to get the root anonymous record parent */
1338 CXCursor Parent, Root;
1339 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl ) {
1340 const char *RootParentName;
Richard Smith131daca2014-03-06 21:59:38 +00001341 Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001342 do {
1343 Root = Parent;
1344 RootParentName = clang_getCString(clang_getCursorSpelling(Root));
1345 Parent = clang_getCursorSemanticParent(Root);
1346 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1347 !strcmp(RootParentName, "") );
1348 /* if RootParentName is "", record is anonymous. */
1349 {
1350 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
1351 FieldName);
1352 printf(" [offsetof=%lld]", Offset);
1353 }
1354 }
1355 }
1356 /* Print if its a bitfield */
1357 {
1358 int IsBitfield = clang_Cursor_isBitField(cursor);
1359 if (IsBitfield)
1360 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1361 }
1362 printf("\n");
1363 return CXChildVisit_Recurse;
1364}
1365
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001366/******************************************************************************/
1367/* Bitwidth testing. */
1368/******************************************************************************/
1369
1370static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1371 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001372 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001373 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1374 return CXChildVisit_Recurse;
1375
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001376 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001377 if (Bitwidth >= 0) {
1378 PrintCursor(cursor, NULL);
1379 printf(" bitwidth=%d\n", Bitwidth);
1380 }
1381
1382 return CXChildVisit_Recurse;
1383}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001384
1385/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001386/* Loading ASTs/source. */
1387/******************************************************************************/
1388
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001389static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001390 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001391 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001392 PostVisitTU PV,
1393 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001394
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001395 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001396 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001397
1398 if (Visitor) {
1399 enum CXCursorKind K = CXCursor_NotImplemented;
1400 enum CXCursorKind *ck = &K;
1401 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001402
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001403 /* Perform some simple filtering. */
1404 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001405 else if (!strcmp(filter, "all-display") ||
1406 !strcmp(filter, "local-display")) {
1407 ck = NULL;
1408 want_display_name = 1;
1409 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001410 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001411 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1412 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1413 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1414 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1415 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1416 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1417 else {
1418 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1419 return 1;
1420 }
Ted Kremenek29004672010-02-17 00:41:32 +00001421
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001422 Data.TU = TU;
1423 Data.Filter = ck;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001424 Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
1425#ifdef CLANG_HAVE_LIBXML
1426 Data.ValidationData.RNGParser = NULL;
1427 Data.ValidationData.Schema = NULL;
1428#endif
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001429 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001430 }
Ted Kremenek29004672010-02-17 00:41:32 +00001431
Ted Kremenekb478ff42010-01-26 17:59:48 +00001432 if (PV)
1433 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001434
Douglas Gregor33cdd812010-02-18 18:08:43 +00001435 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001436 if (checkForErrors(TU) != 0) {
1437 clang_disposeTranslationUnit(TU);
1438 return -1;
1439 }
1440
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001441 clang_disposeTranslationUnit(TU);
1442 return 0;
1443}
1444
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001445int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001446 const char *prefix, CXCursorVisitor Visitor,
1447 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001448 CXIndex Idx;
1449 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001450 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001451 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001452 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001453 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001454
Ted Kremenek50228be2010-02-11 07:41:25 +00001455 if (!CreateTranslationUnit(Idx, file, &TU)) {
1456 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001457 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001458 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001459
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001460 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001461 clang_disposeIndex(Idx);
1462 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001463}
1464
Ted Kremenekb478ff42010-01-26 17:59:48 +00001465int perform_test_load_source(int argc, const char **argv,
1466 const char *filter, CXCursorVisitor Visitor,
1467 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001468 CXIndex Idx;
1469 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001470 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001471 struct CXUnsavedFile *unsaved_files = 0;
1472 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001473 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001474 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001475
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001476 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001477 (!strcmp(filter, "local") ||
1478 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001479 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001480
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001481 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1482 argc--;
1483 argv++;
1484 }
1485
Ted Kremenek50228be2010-02-11 07:41:25 +00001486 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1487 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001488 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001489 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001490
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001491 Err = clang_parseTranslationUnit2(Idx, 0,
1492 argv + num_unsaved_files,
1493 argc - num_unsaved_files,
1494 unsaved_files, num_unsaved_files,
1495 getDefaultParsingOptions(), &TU);
1496 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001497 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001498 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001499 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001500 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001501 return 1;
1502 }
1503
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001504 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1505 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001506 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001507 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001508 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001509}
1510
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001511int perform_test_reparse_source(int argc, const char **argv, int trials,
1512 const char *filter, CXCursorVisitor Visitor,
1513 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001514 CXIndex Idx;
1515 CXTranslationUnit TU;
1516 struct CXUnsavedFile *unsaved_files = 0;
1517 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001518 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001519 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001520 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001521 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001522 int remap_after_trial = 0;
1523 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001524
1525 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1526 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001527 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001528
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001529 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1530 clang_disposeIndex(Idx);
1531 return -1;
1532 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001533
1534 for (i = 0; i < argc; ++i) {
1535 if (strcmp(argv[i], "--") == 0)
1536 break;
1537 }
1538 if (i < argc)
1539 compiler_arg_idx = i+1;
1540 if (num_unsaved_files > compiler_arg_idx)
1541 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001542
Daniel Dunbarec29d712010-08-18 23:09:16 +00001543 /* Load the initial translation unit -- we do this without honoring remapped
1544 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001545 Err = clang_parseTranslationUnit2(Idx, 0,
1546 argv + compiler_arg_idx,
1547 argc - compiler_arg_idx,
1548 0, 0, getDefaultParsingOptions(), &TU);
1549 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001550 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001551 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001552 free_remapped_files(unsaved_files, num_unsaved_files);
1553 clang_disposeIndex(Idx);
1554 return 1;
1555 }
1556
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001557 if (checkForErrors(TU) != 0)
1558 return -1;
1559
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001560 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1561 remap_after_trial =
1562 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1563 }
1564
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001565 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001566 free_remapped_files(unsaved_files, num_unsaved_files);
1567 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1568 &unsaved_files, &num_unsaved_files)) {
1569 clang_disposeTranslationUnit(TU);
1570 clang_disposeIndex(Idx);
1571 return -1;
1572 }
1573
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001574 Err = clang_reparseTranslationUnit(
1575 TU,
1576 trial >= remap_after_trial ? num_unsaved_files : 0,
1577 trial >= remap_after_trial ? unsaved_files : 0,
1578 clang_defaultReparseOptions(TU));
1579 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001580 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001581 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001582 clang_disposeTranslationUnit(TU);
1583 free_remapped_files(unsaved_files, num_unsaved_files);
1584 clang_disposeIndex(Idx);
1585 return -1;
1586 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001587
1588 if (checkForErrors(TU) != 0)
1589 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001590 }
1591
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001592 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001593
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001594 free_remapped_files(unsaved_files, num_unsaved_files);
1595 clang_disposeIndex(Idx);
1596 return result;
1597}
1598
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001599/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001600/* Logic for testing clang_getCursor(). */
1601/******************************************************************************/
1602
Douglas Gregor37aa4932011-05-04 00:14:37 +00001603static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001604 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001605 unsigned end_line, unsigned end_col,
1606 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001607 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001608 if (prefix)
1609 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001610 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1611 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001612 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001613 printf("\n");
1614}
1615
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001616static int perform_file_scan(const char *ast_file, const char *source_file,
1617 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001618 CXIndex Idx;
1619 CXTranslationUnit TU;
1620 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001621 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001622 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001623 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001624 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001625
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001626 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001627 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001628 fprintf(stderr, "Could not create Index\n");
1629 return 1;
1630 }
Ted Kremenek29004672010-02-17 00:41:32 +00001631
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001632 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1633 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001634
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001635 if ((fp = fopen(source_file, "r")) == NULL) {
1636 fprintf(stderr, "Could not open '%s'\n", source_file);
1637 return 1;
1638 }
Ted Kremenek29004672010-02-17 00:41:32 +00001639
Douglas Gregor816fd362010-01-22 21:44:22 +00001640 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001641 for (;;) {
1642 CXCursor cursor;
1643 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001644
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001645 if (c == '\n') {
1646 ++line;
1647 col = 1;
1648 } else
1649 ++col;
1650
1651 /* Check the cursor at this position, and dump the previous one if we have
1652 * found something new.
1653 */
1654 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1655 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1656 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001657 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001658 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001659 start_line = line;
1660 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001661 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001662 if (c == EOF)
1663 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001664
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001665 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001666 }
Ted Kremenek29004672010-02-17 00:41:32 +00001667
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001668 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001669 clang_disposeTranslationUnit(TU);
1670 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001671 return 0;
1672}
1673
1674/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001675/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001676/******************************************************************************/
1677
Douglas Gregor9eb77012009-11-07 00:00:49 +00001678/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1679 on failure. If successful, the pointer *filename will contain newly-allocated
1680 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001681int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001682 unsigned *column, unsigned *second_line,
1683 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001684 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001685 const char *last_colon = strrchr(input, ':');
1686 unsigned values[4], i;
1687 unsigned num_values = (second_line && second_column)? 4 : 2;
1688
Douglas Gregor9eb77012009-11-07 00:00:49 +00001689 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001690 if (!last_colon || last_colon == input) {
1691 if (num_values == 4)
1692 fprintf(stderr, "could not parse filename:line:column:line:column in "
1693 "'%s'\n", input);
1694 else
1695 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001696 return 1;
1697 }
1698
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001699 for (i = 0; i != num_values; ++i) {
1700 const char *prev_colon;
1701
1702 /* Parse the next line or column. */
1703 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1704 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001705 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001706 (i % 2 ? "column" : "line"), input);
1707 return 1;
1708 }
Ted Kremenek29004672010-02-17 00:41:32 +00001709
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001710 if (i + 1 == num_values)
1711 break;
1712
1713 /* Find the previous colon. */
1714 prev_colon = last_colon - 1;
1715 while (prev_colon != input && *prev_colon != ':')
1716 --prev_colon;
1717 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001718 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001719 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001720 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001721 }
1722
1723 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001724 }
1725
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001726 *line = values[0];
1727 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001728
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001729 if (second_line && second_column) {
1730 *second_line = values[2];
1731 *second_column = values[3];
1732 }
1733
Douglas Gregorf96ea292009-11-09 18:19:57 +00001734 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001735 *filename = (char*)malloc(last_colon - input + 1);
1736 memcpy(*filename, input, last_colon - input);
1737 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001738 return 0;
1739}
1740
1741const char *
1742clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1743 switch (Kind) {
1744 case CXCompletionChunk_Optional: return "Optional";
1745 case CXCompletionChunk_TypedText: return "TypedText";
1746 case CXCompletionChunk_Text: return "Text";
1747 case CXCompletionChunk_Placeholder: return "Placeholder";
1748 case CXCompletionChunk_Informative: return "Informative";
1749 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1750 case CXCompletionChunk_LeftParen: return "LeftParen";
1751 case CXCompletionChunk_RightParen: return "RightParen";
1752 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1753 case CXCompletionChunk_RightBracket: return "RightBracket";
1754 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1755 case CXCompletionChunk_RightBrace: return "RightBrace";
1756 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1757 case CXCompletionChunk_RightAngle: return "RightAngle";
1758 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001759 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001760 case CXCompletionChunk_Colon: return "Colon";
1761 case CXCompletionChunk_SemiColon: return "SemiColon";
1762 case CXCompletionChunk_Equal: return "Equal";
1763 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1764 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001765 }
Ted Kremenek29004672010-02-17 00:41:32 +00001766
Douglas Gregor9eb77012009-11-07 00:00:49 +00001767 return "Unknown";
1768}
1769
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001770static int checkForErrors(CXTranslationUnit TU) {
1771 unsigned Num, i;
1772 CXDiagnostic Diag;
1773 CXString DiagStr;
1774
1775 if (!getenv("CINDEXTEST_FAILONERROR"))
1776 return 0;
1777
1778 Num = clang_getNumDiagnostics(TU);
1779 for (i = 0; i != Num; ++i) {
1780 Diag = clang_getDiagnostic(TU, i);
1781 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1782 DiagStr = clang_formatDiagnostic(Diag,
1783 clang_defaultDiagnosticDisplayOptions());
1784 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1785 clang_disposeString(DiagStr);
1786 clang_disposeDiagnostic(Diag);
1787 return -1;
1788 }
1789 clang_disposeDiagnostic(Diag);
1790 }
1791
1792 return 0;
1793}
1794
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001795void print_completion_string(CXCompletionString completion_string, FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001796 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001797
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001798 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001799 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001800 CXString text;
1801 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001802 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001803 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001804
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001805 if (Kind == CXCompletionChunk_Optional) {
1806 fprintf(file, "{Optional ");
1807 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001808 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001809 file);
1810 fprintf(file, "}");
1811 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001812 }
1813
1814 if (Kind == CXCompletionChunk_VerticalSpace) {
1815 fprintf(file, "{VerticalSpace }");
1816 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001817 }
Ted Kremenek29004672010-02-17 00:41:32 +00001818
Douglas Gregorf81f5282009-11-09 17:05:28 +00001819 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001820 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001821 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001822 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001823 cstr ? cstr : "");
1824 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001825 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001826
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001827}
1828
1829void print_completion_result(CXCompletionResult *completion_result,
1830 CXClientData client_data) {
1831 FILE *file = (FILE *)client_data;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001832 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001833 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001834 enum CXCursorKind ParentKind;
1835 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001836 CXString BriefComment;
1837 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001838
Ted Kremenek29004672010-02-17 00:41:32 +00001839 fprintf(file, "%s:", clang_getCString(ks));
1840 clang_disposeString(ks);
1841
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001842 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001843 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001844 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001845 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1846 case CXAvailability_Available:
1847 break;
1848
1849 case CXAvailability_Deprecated:
1850 fprintf(file, " (deprecated)");
1851 break;
1852
1853 case CXAvailability_NotAvailable:
1854 fprintf(file, " (unavailable)");
1855 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001856
1857 case CXAvailability_NotAccessible:
1858 fprintf(file, " (inaccessible)");
1859 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001860 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001861
1862 annotationCount = clang_getCompletionNumAnnotations(
1863 completion_result->CompletionString);
1864 if (annotationCount) {
1865 unsigned i;
1866 fprintf(file, " (");
1867 for (i = 0; i < annotationCount; ++i) {
1868 if (i != 0)
1869 fprintf(file, ", ");
1870 fprintf(file, "\"%s\"",
1871 clang_getCString(clang_getCompletionAnnotation(
1872 completion_result->CompletionString, i)));
1873 }
1874 fprintf(file, ")");
1875 }
1876
Douglas Gregor78254c82012-03-27 23:34:16 +00001877 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1878 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1879 &ParentKind);
1880 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001881 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00001882 fprintf(file, " (parent: %s '%s')",
1883 clang_getCString(KindSpelling),
1884 clang_getCString(ParentName));
1885 clang_disposeString(KindSpelling);
1886 }
1887 clang_disposeString(ParentName);
1888 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001889
1890 BriefComment = clang_getCompletionBriefComment(
1891 completion_result->CompletionString);
1892 BriefCommentCString = clang_getCString(BriefComment);
1893 if (BriefCommentCString && *BriefCommentCString != '\0') {
1894 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1895 }
1896 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00001897
Douglas Gregorf757a122010-08-23 23:00:57 +00001898 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001899}
1900
Douglas Gregor21325842011-07-07 16:03:39 +00001901void print_completion_contexts(unsigned long long contexts, FILE *file) {
1902 fprintf(file, "Completion contexts:\n");
1903 if (contexts == CXCompletionContext_Unknown) {
1904 fprintf(file, "Unknown\n");
1905 }
1906 if (contexts & CXCompletionContext_AnyType) {
1907 fprintf(file, "Any type\n");
1908 }
1909 if (contexts & CXCompletionContext_AnyValue) {
1910 fprintf(file, "Any value\n");
1911 }
1912 if (contexts & CXCompletionContext_ObjCObjectValue) {
1913 fprintf(file, "Objective-C object value\n");
1914 }
1915 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1916 fprintf(file, "Objective-C selector value\n");
1917 }
1918 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1919 fprintf(file, "C++ class type value\n");
1920 }
1921 if (contexts & CXCompletionContext_DotMemberAccess) {
1922 fprintf(file, "Dot member access\n");
1923 }
1924 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1925 fprintf(file, "Arrow member access\n");
1926 }
1927 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1928 fprintf(file, "Objective-C property access\n");
1929 }
1930 if (contexts & CXCompletionContext_EnumTag) {
1931 fprintf(file, "Enum tag\n");
1932 }
1933 if (contexts & CXCompletionContext_UnionTag) {
1934 fprintf(file, "Union tag\n");
1935 }
1936 if (contexts & CXCompletionContext_StructTag) {
1937 fprintf(file, "Struct tag\n");
1938 }
1939 if (contexts & CXCompletionContext_ClassTag) {
1940 fprintf(file, "Class name\n");
1941 }
1942 if (contexts & CXCompletionContext_Namespace) {
1943 fprintf(file, "Namespace or namespace alias\n");
1944 }
1945 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1946 fprintf(file, "Nested name specifier\n");
1947 }
1948 if (contexts & CXCompletionContext_ObjCInterface) {
1949 fprintf(file, "Objective-C interface\n");
1950 }
1951 if (contexts & CXCompletionContext_ObjCProtocol) {
1952 fprintf(file, "Objective-C protocol\n");
1953 }
1954 if (contexts & CXCompletionContext_ObjCCategory) {
1955 fprintf(file, "Objective-C category\n");
1956 }
1957 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1958 fprintf(file, "Objective-C instance method\n");
1959 }
1960 if (contexts & CXCompletionContext_ObjCClassMessage) {
1961 fprintf(file, "Objective-C class method\n");
1962 }
1963 if (contexts & CXCompletionContext_ObjCSelectorName) {
1964 fprintf(file, "Objective-C selector name\n");
1965 }
1966 if (contexts & CXCompletionContext_MacroName) {
1967 fprintf(file, "Macro name\n");
1968 }
1969 if (contexts & CXCompletionContext_NaturalLanguage) {
1970 fprintf(file, "Natural language\n");
1971 }
1972}
1973
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001974int my_stricmp(const char *s1, const char *s2) {
1975 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00001976 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001977 if (c1 < c2)
1978 return -1;
1979 else if (c1 > c2)
1980 return 1;
1981
1982 ++s1;
1983 ++s2;
1984 }
1985
1986 if (*s1)
1987 return 1;
1988 else if (*s2)
1989 return -1;
1990 return 0;
1991}
1992
Douglas Gregor47815d52010-07-12 18:38:41 +00001993int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001994 const char *input = argv[1];
1995 char *filename = 0;
1996 unsigned line;
1997 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001998 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00001999 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002000 struct CXUnsavedFile *unsaved_files = 0;
2001 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002002 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002003 enum CXErrorCode Err;
2004 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002005 unsigned I, Repeats = 1;
2006 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2007
2008 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2009 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002010 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2011 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002012
Douglas Gregor47815d52010-07-12 18:38:41 +00002013 if (timing_only)
2014 input += strlen("-code-completion-timing=");
2015 else
2016 input += strlen("-code-completion-at=");
2017
Ted Kremenek29004672010-02-17 00:41:32 +00002018 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002019 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002020 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002021
Douglas Gregor9485bf92009-12-02 09:21:34 +00002022 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2023 return -1;
2024
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002025 CIdx = clang_createIndex(0, 0);
2026
2027 if (getenv("CINDEXTEST_EDITING"))
2028 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002029
2030 Err = clang_parseTranslationUnit2(CIdx, 0,
2031 argv + num_unsaved_files + 2,
2032 argc - num_unsaved_files - 2,
2033 0, 0, getDefaultParsingOptions(), &TU);
2034 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002035 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002036 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002037 return 1;
2038 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002039
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002040 Err = clang_reparseTranslationUnit(TU, 0, 0,
2041 clang_defaultReparseOptions(TU));
2042
2043 if (Err != CXError_Success) {
Douglas Gregorc6592922010-11-15 23:00:34 +00002044 fprintf(stderr, "Unable to reparse translation init!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002045 describeLibclangFailure(Err);
2046 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002047 return 1;
2048 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002049
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002050 for (I = 0; I != Repeats; ++I) {
2051 results = clang_codeCompleteAt(TU, filename, line, column,
2052 unsaved_files, num_unsaved_files,
2053 completionOptions);
2054 if (!results) {
2055 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002056 return 1;
2057 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002058 if (I != Repeats-1)
2059 clang_disposeCodeCompleteResults(results);
2060 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002061
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002062 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002063 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002064 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002065 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002066 CXString objCSelector;
2067 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002068 if (!timing_only) {
2069 /* Sort the code-completion results based on the typed text. */
2070 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2071
Douglas Gregor47815d52010-07-12 18:38:41 +00002072 for (i = 0; i != n; ++i)
2073 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002074 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002075 n = clang_codeCompleteGetNumDiagnostics(results);
2076 for (i = 0; i != n; ++i) {
2077 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2078 PrintDiagnostic(diag);
2079 clang_disposeDiagnostic(diag);
2080 }
Douglas Gregor21325842011-07-07 16:03:39 +00002081
2082 contexts = clang_codeCompleteGetContexts(results);
2083 print_completion_contexts(contexts, stdout);
2084
Douglas Gregorea777402011-07-26 15:24:30 +00002085 containerKind = clang_codeCompleteGetContainerKind(results,
2086 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002087
2088 if (containerKind != CXCursor_InvalidCode) {
2089 /* We have found a container */
2090 CXString containerUSR, containerKindSpelling;
2091 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2092 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2093 clang_disposeString(containerKindSpelling);
2094
2095 if (containerIsIncomplete) {
2096 printf("Container is incomplete\n");
2097 }
2098 else {
2099 printf("Container is complete\n");
2100 }
2101
2102 containerUSR = clang_codeCompleteGetContainerUSR(results);
2103 printf("Container USR: %s\n", clang_getCString(containerUSR));
2104 clang_disposeString(containerUSR);
2105 }
2106
Douglas Gregorea777402011-07-26 15:24:30 +00002107 objCSelector = clang_codeCompleteGetObjCSelector(results);
2108 selectorString = clang_getCString(objCSelector);
2109 if (selectorString && strlen(selectorString) > 0) {
2110 printf("Objective-C selector: %s\n", selectorString);
2111 }
2112 clang_disposeString(objCSelector);
2113
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002114 clang_disposeCodeCompleteResults(results);
2115 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002116 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002117 clang_disposeIndex(CIdx);
2118 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002119
Douglas Gregor9485bf92009-12-02 09:21:34 +00002120 free_remapped_files(unsaved_files, num_unsaved_files);
2121
Ted Kremenekef3339b2009-11-17 18:09:14 +00002122 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002123}
2124
Douglas Gregor082c3e62010-01-15 19:40:17 +00002125typedef struct {
2126 char *filename;
2127 unsigned line;
2128 unsigned column;
2129} CursorSourceLocation;
2130
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002131static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002132 CXIndex CIdx;
2133 int errorCode;
2134 struct CXUnsavedFile *unsaved_files = 0;
2135 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002136 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002137 CXTranslationUnit TU;
2138 CXCursor Cursor;
2139 CursorSourceLocation *Locations = 0;
2140 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002141 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002142 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002143
Ted Kremenek29004672010-02-17 00:41:32 +00002144 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002145 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2146 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002147
Douglas Gregor082c3e62010-01-15 19:40:17 +00002148 /* Parse the locations. */
2149 assert(NumLocations > 0 && "Unable to count locations?");
2150 Locations = (CursorSourceLocation *)malloc(
2151 NumLocations * sizeof(CursorSourceLocation));
2152 for (Loc = 0; Loc < NumLocations; ++Loc) {
2153 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002154 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2155 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002156 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002157 return errorCode;
2158 }
Ted Kremenek29004672010-02-17 00:41:32 +00002159
2160 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002161 &num_unsaved_files))
2162 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002163
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002164 if (getenv("CINDEXTEST_EDITING"))
2165 Repeats = 5;
2166
2167 /* Parse the translation unit. When we're testing clang_getCursor() after
2168 reparsing, don't remap unsaved files until the second parse. */
2169 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002170 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2171 argv + num_unsaved_files + 1 + NumLocations,
2172 argc - num_unsaved_files - 2 - NumLocations,
2173 unsaved_files,
2174 Repeats > 1? 0 : num_unsaved_files,
2175 getDefaultParsingOptions(), &TU);
2176 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002177 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002178 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002179 return -1;
2180 }
Ted Kremenek29004672010-02-17 00:41:32 +00002181
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002182 if (checkForErrors(TU) != 0)
2183 return -1;
2184
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002185 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002186 if (Repeats > 1) {
2187 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2188 clang_defaultReparseOptions(TU));
2189 if (Err != CXError_Success) {
2190 describeLibclangFailure(Err);
2191 clang_disposeTranslationUnit(TU);
2192 return 1;
2193 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002194 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002195
2196 if (checkForErrors(TU) != 0)
2197 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002198
2199 for (Loc = 0; Loc < NumLocations; ++Loc) {
2200 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2201 if (!file)
2202 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002203
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002204 Cursor = clang_getCursor(TU,
2205 clang_getLocation(TU, file, Locations[Loc].line,
2206 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002207
2208 if (checkForErrors(TU) != 0)
2209 return -1;
2210
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002211 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002212 CXCompletionString completionString = clang_getCursorCompletionString(
2213 Cursor);
2214 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002215 CXString Spelling;
2216 const char *cspell;
2217 unsigned line, column;
2218 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2219 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002220 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002221 PrintCursorExtent(Cursor);
2222 Spelling = clang_getCursorSpelling(Cursor);
2223 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002224 if (cspell && strlen(cspell) != 0) {
2225 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002226 printf(" Spelling=%s (", cspell);
2227 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002228 CXSourceRange range =
2229 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002230 if (clang_Range_isNull(range))
2231 break;
2232 PrintRange(range, 0);
2233 }
2234 printf(")");
2235 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002236 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002237 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2238 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002239 if (clang_Cursor_isDynamicCall(Cursor))
2240 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002241 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002242 CXType T = clang_Cursor_getReceiverType(Cursor);
2243 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002244 printf(" Receiver-type=%s", clang_getCString(S));
2245 clang_disposeString(S);
2246 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002247
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002248 {
2249 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002250 CXFile astFile;
2251 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002252 unsigned i, numHeaders;
2253 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002254 astFile = clang_Module_getASTFile(mod);
2255 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002256 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002257 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002258 printf(" ModuleName=%s (%s) Headers(%d):",
2259 clang_getCString(name), clang_getCString(astFilename),
2260 numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002261 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002262 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002263 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002264 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2265 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002266 printf("\n%s", clang_getCString(filename));
2267 clang_disposeString(filename);
2268 }
2269 }
2270 }
2271
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002272 if (completionString != NULL) {
2273 printf("\nCompletion string: ");
2274 print_completion_string(completionString, stdout);
2275 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002276 printf("\n");
2277 free(Locations[Loc].filename);
2278 }
2279 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002280 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002281
Douglas Gregor33cdd812010-02-18 18:08:43 +00002282 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002283 clang_disposeTranslationUnit(TU);
2284 clang_disposeIndex(CIdx);
2285 free(Locations);
2286 free_remapped_files(unsaved_files, num_unsaved_files);
2287 return 0;
2288}
2289
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002290static enum CXVisitorResult findFileRefsVisit(void *context,
2291 CXCursor cursor, CXSourceRange range) {
2292 if (clang_Range_isNull(range))
2293 return CXVisit_Continue;
2294
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002295 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002296 PrintRange(range, "");
2297 printf("\n");
2298 return CXVisit_Continue;
2299}
2300
2301static int find_file_refs_at(int argc, const char **argv) {
2302 CXIndex CIdx;
2303 int errorCode;
2304 struct CXUnsavedFile *unsaved_files = 0;
2305 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002306 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002307 CXTranslationUnit TU;
2308 CXCursor Cursor;
2309 CursorSourceLocation *Locations = 0;
2310 unsigned NumLocations = 0, Loc;
2311 unsigned Repeats = 1;
2312 unsigned I;
2313
2314 /* Count the number of locations. */
2315 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2316 ++NumLocations;
2317
2318 /* Parse the locations. */
2319 assert(NumLocations > 0 && "Unable to count locations?");
2320 Locations = (CursorSourceLocation *)malloc(
2321 NumLocations * sizeof(CursorSourceLocation));
2322 for (Loc = 0; Loc < NumLocations; ++Loc) {
2323 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2324 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2325 &Locations[Loc].line,
2326 &Locations[Loc].column, 0, 0)))
2327 return errorCode;
2328 }
2329
2330 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2331 &num_unsaved_files))
2332 return -1;
2333
2334 if (getenv("CINDEXTEST_EDITING"))
2335 Repeats = 5;
2336
2337 /* Parse the translation unit. When we're testing clang_getCursor() after
2338 reparsing, don't remap unsaved files until the second parse. */
2339 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002340 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2341 argv + num_unsaved_files + 1 + NumLocations,
2342 argc - num_unsaved_files - 2 - NumLocations,
2343 unsaved_files,
2344 Repeats > 1? 0 : num_unsaved_files,
2345 getDefaultParsingOptions(), &TU);
2346 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002347 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002348 describeLibclangFailure(Err);
2349 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002350 return -1;
2351 }
2352
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002353 if (checkForErrors(TU) != 0)
2354 return -1;
2355
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002356 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002357 if (Repeats > 1) {
2358 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2359 clang_defaultReparseOptions(TU));
2360 if (Err != CXError_Success) {
2361 describeLibclangFailure(Err);
2362 clang_disposeTranslationUnit(TU);
2363 return 1;
2364 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002365 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002366
2367 if (checkForErrors(TU) != 0)
2368 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002369
2370 for (Loc = 0; Loc < NumLocations; ++Loc) {
2371 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2372 if (!file)
2373 continue;
2374
2375 Cursor = clang_getCursor(TU,
2376 clang_getLocation(TU, file, Locations[Loc].line,
2377 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002378
2379 if (checkForErrors(TU) != 0)
2380 return -1;
2381
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002382 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002383 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002384 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002385 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002386 clang_findReferencesInFile(Cursor, file, visitor);
2387 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002388
2389 if (checkForErrors(TU) != 0)
2390 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002391 }
2392 }
2393 }
2394
2395 PrintDiagnostics(TU);
2396 clang_disposeTranslationUnit(TU);
2397 clang_disposeIndex(CIdx);
2398 free(Locations);
2399 free_remapped_files(unsaved_files, num_unsaved_files);
2400 return 0;
2401}
2402
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002403static enum CXVisitorResult findFileIncludesVisit(void *context,
2404 CXCursor cursor, CXSourceRange range) {
2405 PrintCursor(cursor, NULL);
2406 PrintRange(range, "");
2407 printf("\n");
2408 return CXVisit_Continue;
2409}
2410
2411static int find_file_includes_in(int argc, const char **argv) {
2412 CXIndex CIdx;
2413 struct CXUnsavedFile *unsaved_files = 0;
2414 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002415 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002416 CXTranslationUnit TU;
2417 const char **Filenames = 0;
2418 unsigned NumFilenames = 0;
2419 unsigned Repeats = 1;
2420 unsigned I, FI;
2421
2422 /* Count the number of locations. */
2423 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2424 ++NumFilenames;
2425
2426 /* Parse the locations. */
2427 assert(NumFilenames > 0 && "Unable to count filenames?");
2428 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2429 for (I = 0; I < NumFilenames; ++I) {
2430 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2431 /* Copy the file name. */
2432 Filenames[I] = input;
2433 }
2434
2435 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2436 &num_unsaved_files))
2437 return -1;
2438
2439 if (getenv("CINDEXTEST_EDITING"))
2440 Repeats = 2;
2441
2442 /* Parse the translation unit. When we're testing clang_getCursor() after
2443 reparsing, don't remap unsaved files until the second parse. */
2444 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002445 Err = clang_parseTranslationUnit2(
2446 CIdx, argv[argc - 1],
2447 argv + num_unsaved_files + 1 + NumFilenames,
2448 argc - num_unsaved_files - 2 - NumFilenames,
2449 unsaved_files,
2450 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002451
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002452 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002453 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002454 describeLibclangFailure(Err);
2455 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002456 return -1;
2457 }
2458
2459 if (checkForErrors(TU) != 0)
2460 return -1;
2461
2462 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002463 if (Repeats > 1) {
2464 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2465 clang_defaultReparseOptions(TU));
2466 if (Err != CXError_Success) {
2467 describeLibclangFailure(Err);
2468 clang_disposeTranslationUnit(TU);
2469 return 1;
2470 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002471 }
2472
2473 if (checkForErrors(TU) != 0)
2474 return -1;
2475
2476 for (FI = 0; FI < NumFilenames; ++FI) {
2477 CXFile file = clang_getFile(TU, Filenames[FI]);
2478 if (!file)
2479 continue;
2480
2481 if (checkForErrors(TU) != 0)
2482 return -1;
2483
2484 if (I + 1 == Repeats) {
2485 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2486 clang_findIncludesInFile(TU, file, visitor);
2487
2488 if (checkForErrors(TU) != 0)
2489 return -1;
2490 }
2491 }
2492 }
2493
2494 PrintDiagnostics(TU);
2495 clang_disposeTranslationUnit(TU);
2496 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002497 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002498 free_remapped_files(unsaved_files, num_unsaved_files);
2499 return 0;
2500}
2501
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002502#define MAX_IMPORTED_ASTFILES 200
2503
2504typedef struct {
2505 char **filenames;
2506 unsigned num_files;
2507} ImportedASTFilesData;
2508
2509static ImportedASTFilesData *importedASTs_create() {
2510 ImportedASTFilesData *p;
2511 p = malloc(sizeof(ImportedASTFilesData));
2512 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2513 p->num_files = 0;
2514 return p;
2515}
2516
2517static void importedASTs_dispose(ImportedASTFilesData *p) {
2518 unsigned i;
2519 if (!p)
2520 return;
2521
2522 for (i = 0; i < p->num_files; ++i)
2523 free(p->filenames[i]);
2524 free(p->filenames);
2525 free(p);
2526}
2527
2528static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2529 unsigned i;
2530 assert(p && file);
2531 for (i = 0; i < p->num_files; ++i)
2532 if (strcmp(file, p->filenames[i]) == 0)
2533 return;
2534 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2535 p->filenames[p->num_files++] = strdup(file);
2536}
2537
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002538typedef struct {
2539 const char *check_prefix;
2540 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002541 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002542 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002543 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002544 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002545} IndexData;
2546
2547static void printCheck(IndexData *data) {
2548 if (data->check_prefix) {
2549 if (data->first_check_printed) {
2550 printf("// %s-NEXT: ", data->check_prefix);
2551 } else {
2552 printf("// %s : ", data->check_prefix);
2553 data->first_check_printed = 1;
2554 }
2555 }
2556}
2557
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002558static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002559 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002560 printf("%s", clang_getCString(filename));
2561 clang_disposeString(filename);
2562}
2563
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002564static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2565 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002566 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002567 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002568 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002569 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002570 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002571
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002572 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002573 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2574 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002575 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002576 return;
2577 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002578 if (!file) {
2579 printf("<no idxfile>");
2580 return;
2581 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002582 filename = clang_getFileName((CXFile)file);
2583 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002584 if (strcmp(cname, index_data->main_filename) == 0)
2585 isMainFile = 1;
2586 else
2587 isMainFile = 0;
2588 clang_disposeString(filename);
2589
2590 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002591 printCXIndexFile(file);
2592 printf(":");
2593 }
2594 printf("%d:%d", line, column);
2595}
2596
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002597static unsigned digitCount(unsigned val) {
2598 unsigned c = 1;
2599 while (1) {
2600 if (val < 10)
2601 return c;
2602 ++c;
2603 val /= 10;
2604 }
2605}
2606
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002607static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2608 CXIdxLoc loc) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002609 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002610 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002611 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002612 unsigned line, column;
2613
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002614 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002615 if (!name)
2616 name = "<anon-tag>";
2617
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002618 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Argyrios Kyrtzidis90068072011-10-20 17:21:46 +00002619 /* FIXME: free these.*/
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002620 newStr = (char *)malloc(strlen(name) +
2621 digitCount(line) + digitCount(column) + 3);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002622 sprintf(newStr, "%s:%d:%d", name, line, column);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002623 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002624}
2625
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002626static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2627 CXIdxClientContainer container;
2628 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002629 if (!container)
2630 printf("[<<NULL>>]");
2631 else
2632 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002633}
2634
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002635static const char *getEntityKindString(CXIdxEntityKind kind) {
2636 switch (kind) {
2637 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2638 case CXIdxEntity_Typedef: return "typedef";
2639 case CXIdxEntity_Function: return "function";
2640 case CXIdxEntity_Variable: return "variable";
2641 case CXIdxEntity_Field: return "field";
2642 case CXIdxEntity_EnumConstant: return "enumerator";
2643 case CXIdxEntity_ObjCClass: return "objc-class";
2644 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2645 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002646 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2647 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002648 case CXIdxEntity_ObjCProperty: return "objc-property";
2649 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2650 case CXIdxEntity_Enum: return "enum";
2651 case CXIdxEntity_Struct: return "struct";
2652 case CXIdxEntity_Union: return "union";
2653 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002654 case CXIdxEntity_CXXNamespace: return "namespace";
2655 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2656 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2657 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2658 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2659 case CXIdxEntity_CXXConstructor: return "constructor";
2660 case CXIdxEntity_CXXDestructor: return "destructor";
2661 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2662 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002663 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002664 }
2665 assert(0 && "Garbage entity kind");
2666 return 0;
2667}
2668
2669static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2670 switch (kind) {
2671 case CXIdxEntity_NonTemplate: return "";
2672 case CXIdxEntity_Template: return "-template";
2673 case CXIdxEntity_TemplatePartialSpecialization:
2674 return "-template-partial-spec";
2675 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002676 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002677 assert(0 && "Garbage entity kind");
2678 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002679}
2680
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002681static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2682 switch (kind) {
2683 case CXIdxEntityLang_None: return "<none>";
2684 case CXIdxEntityLang_C: return "C";
2685 case CXIdxEntityLang_ObjC: return "ObjC";
2686 case CXIdxEntityLang_CXX: return "C++";
2687 }
2688 assert(0 && "Garbage language kind");
2689 return 0;
2690}
2691
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002692static void printEntityInfo(const char *cb,
2693 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002694 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002695 const char *name;
2696 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002697 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002698 index_data = (IndexData *)client_data;
2699 printCheck(index_data);
2700
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002701 if (!info) {
2702 printf("%s: <<NULL>>", cb);
2703 return;
2704 }
2705
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002706 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002707 if (!name)
2708 name = "<anon-tag>";
2709
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002710 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2711 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002712 printf(" | name: %s", name);
2713 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002714 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002715
2716 for (i = 0; i != info->numAttributes; ++i) {
2717 const CXIdxAttrInfo *Attr = info->attributes[i];
2718 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002719 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002720 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002721}
2722
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002723static void printBaseClassInfo(CXClientData client_data,
2724 const CXIdxBaseClassInfo *info) {
2725 printEntityInfo(" <base>", client_data, info->base);
2726 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002727 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002728 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002729 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002730}
2731
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002732static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2733 CXClientData client_data) {
2734 unsigned i;
2735 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2736 printEntityInfo(" <protocol>", client_data,
2737 ProtoInfo->protocols[i]->protocol);
2738 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002739 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002740 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002741 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002742 printf("\n");
2743 }
2744}
2745
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002746static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002747 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002748 CXString str;
2749 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002750 unsigned numDiags, i;
2751 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002752 IndexData *index_data;
2753 index_data = (IndexData *)client_data;
2754 printCheck(index_data);
2755
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002756 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2757 for (i = 0; i != numDiags; ++i) {
2758 diag = clang_getDiagnosticInSet(diagSet, i);
2759 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2760 cstr = clang_getCString(str);
2761 printf("[diagnostic]: %s\n", cstr);
2762 clang_disposeString(str);
2763
2764 if (getenv("CINDEXTEST_FAILONERROR") &&
2765 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2766 index_data->fail_for_error = 1;
2767 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002768 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002769}
2770
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002771static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2772 CXFile file, void *reserved) {
2773 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002774 CXString filename;
2775
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002776 index_data = (IndexData *)client_data;
2777 printCheck(index_data);
2778
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002779 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002780 index_data->main_filename = clang_getCString(filename);
2781 clang_disposeString(filename);
2782
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002783 printf("[enteredMainFile]: ");
2784 printCXIndexFile((CXIdxClientFile)file);
2785 printf("\n");
2786
2787 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002788}
2789
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002790static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002791 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002792 IndexData *index_data;
2793 index_data = (IndexData *)client_data;
2794 printCheck(index_data);
2795
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002796 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002797 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002798 printf(" | name: \"%s\"", info->filename);
2799 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002800 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002801 printf(" | isImport: %d | isAngled: %d | isModule: %d\n",
2802 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002803
2804 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002805}
2806
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002807static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2808 const CXIdxImportedASTFileInfo *info) {
2809 IndexData *index_data;
2810 index_data = (IndexData *)client_data;
2811 printCheck(index_data);
2812
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002813 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002814 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002815 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2816 clang_disposeString(filename);
2817 }
2818
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002819 printf("[importedASTFile]: ");
2820 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002821 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002822 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002823 printf(" | loc: ");
2824 printCXIndexLoc(info->loc, client_data);
2825 printf(" | name: \"%s\"", clang_getCString(name));
2826 printf(" | isImplicit: %d\n", info->isImplicit);
2827 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002828 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002829 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002830 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002831 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002832
2833 return (CXIdxClientFile)info->file;
2834}
2835
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002836static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002837 void *reserved) {
2838 IndexData *index_data;
2839 index_data = (IndexData *)client_data;
2840 printCheck(index_data);
2841
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002842 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002843 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002844}
2845
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002846static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002847 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002848 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002849 const CXIdxObjCCategoryDeclInfo *CatInfo;
2850 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002851 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002852 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002853 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002854 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002855 index_data = (IndexData *)client_data;
2856
2857 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2858 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002859 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002860 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002861 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00002862 printf(" | semantic-container: ");
2863 printCXIndexContainer(info->semanticContainer);
2864 printf(" | lexical-container: ");
2865 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002866 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002867 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002868 if (info->flags & CXIdxDeclFlag_Skipped) {
2869 assert(!info->isContainer);
2870 printf(" | isContainer: skipped");
2871 } else {
2872 printf(" | isContainer: %d", info->isContainer);
2873 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002874 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002875
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002876 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00002877 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002878 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002879 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002880 printf("\n");
2881 }
2882
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002883 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2884 const char *kindName = 0;
2885 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2886 switch (K) {
2887 case CXIdxObjCContainer_ForwardRef:
2888 kindName = "forward-ref"; break;
2889 case CXIdxObjCContainer_Interface:
2890 kindName = "interface"; break;
2891 case CXIdxObjCContainer_Implementation:
2892 kindName = "implementation"; break;
2893 }
2894 printCheck(index_data);
2895 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2896 }
2897
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002898 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002899 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2900 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00002901 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002902 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00002903 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002904 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002905 printf("\n");
2906 }
2907
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002908 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2909 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002910 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002911 printf("\n");
2912 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002913 }
2914
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002915 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2916 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002917 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002918
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002919 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2920 if (PropInfo->getter) {
2921 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2922 printf("\n");
2923 }
2924 if (PropInfo->setter) {
2925 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2926 printf("\n");
2927 }
2928 }
2929
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002930 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2931 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2932 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2933 printf("\n");
2934 }
2935 }
2936
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002937 if (info->declAsContainer)
2938 clang_index_setClientContainer(info->declAsContainer,
2939 makeClientContainer(info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002940}
2941
2942static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002943 const CXIdxEntityRefInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002944 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002945 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002946 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002947 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002948 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002949 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002950 printf(" | container: ");
2951 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002952 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00002953 switch (info->kind) {
2954 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002955 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00002956 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002957 printf("\n");
2958}
2959
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002960static int index_abortQuery(CXClientData client_data, void *reserved) {
2961 IndexData *index_data;
2962 index_data = (IndexData *)client_data;
2963 return index_data->abort;
2964}
2965
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002966static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002967 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002968 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002969 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002970 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002971 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002972 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002973 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002974 index_indexEntityReference
2975};
2976
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00002977static unsigned getIndexOptions(void) {
2978 unsigned index_opts;
2979 index_opts = 0;
2980 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2981 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2982 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2983 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002984 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
2985 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00002986
2987 return index_opts;
2988}
2989
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00002990static int index_compile_args(int num_args, const char **args,
2991 CXIndexAction idxAction,
2992 ImportedASTFilesData *importedASTs,
2993 const char *check_prefix) {
2994 IndexData index_data;
2995 unsigned index_opts;
2996 int result;
2997
2998 if (num_args == 0) {
2999 fprintf(stderr, "no compiler arguments\n");
3000 return -1;
3001 }
3002
3003 index_data.check_prefix = check_prefix;
3004 index_data.first_check_printed = 0;
3005 index_data.fail_for_error = 0;
3006 index_data.abort = 0;
3007 index_data.main_filename = "";
3008 index_data.importedASTs = importedASTs;
3009
3010 index_opts = getIndexOptions();
3011 result = clang_indexSourceFile(idxAction, &index_data,
3012 &IndexCB,sizeof(IndexCB), index_opts,
3013 0, args, num_args, 0, 0, 0,
3014 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003015 if (result != CXError_Success)
3016 describeLibclangFailure(result);
3017
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003018 if (index_data.fail_for_error)
3019 result = -1;
3020
3021 return result;
3022}
3023
3024static int index_ast_file(const char *ast_file,
3025 CXIndex Idx,
3026 CXIndexAction idxAction,
3027 ImportedASTFilesData *importedASTs,
3028 const char *check_prefix) {
3029 CXTranslationUnit TU;
3030 IndexData index_data;
3031 unsigned index_opts;
3032 int result;
3033
3034 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3035 return -1;
3036
3037 index_data.check_prefix = check_prefix;
3038 index_data.first_check_printed = 0;
3039 index_data.fail_for_error = 0;
3040 index_data.abort = 0;
3041 index_data.main_filename = "";
3042 index_data.importedASTs = importedASTs;
3043
3044 index_opts = getIndexOptions();
3045 result = clang_indexTranslationUnit(idxAction, &index_data,
3046 &IndexCB,sizeof(IndexCB),
3047 index_opts, TU);
3048 if (index_data.fail_for_error)
3049 result = -1;
3050
3051 clang_disposeTranslationUnit(TU);
3052 return result;
3053}
3054
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003055static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003056 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003057 CXIndex Idx;
3058 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003059 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003060 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003061
3062 check_prefix = 0;
3063 if (argc > 0) {
3064 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3065 check_prefix = argv[0] + strlen("-check-prefix=");
3066 ++argv;
3067 --argc;
3068 }
3069 }
3070
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003071 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003072 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003073 fprintf(stderr, "Could not create Index\n");
3074 return 1;
3075 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003076 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003077 importedASTs = 0;
3078 if (full)
3079 importedASTs = importedASTs_create();
3080
3081 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3082 if (result != 0)
3083 goto finished;
3084
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003085 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003086 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003087 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3088 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3089 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003090 }
3091 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003092
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003093finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003094 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003095 clang_IndexAction_dispose(idxAction);
3096 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003097 return result;
3098}
3099
3100static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003101 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003102 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003103 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003104 int result;
3105
3106 check_prefix = 0;
3107 if (argc > 0) {
3108 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3109 check_prefix = argv[0] + strlen("-check-prefix=");
3110 ++argv;
3111 --argc;
3112 }
3113 }
3114
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003115 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003116 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003117 fprintf(stderr, "Could not create Index\n");
3118 return 1;
3119 }
3120 idxAction = clang_IndexAction_create(Idx);
3121
3122 result = index_ast_file(argv[0], Idx, idxAction,
3123 /*importedASTs=*/0, check_prefix);
3124
3125 clang_IndexAction_dispose(idxAction);
3126 clang_disposeIndex(Idx);
3127 return result;
3128}
3129
3130static int index_compile_db(int argc, const char **argv) {
3131 const char *check_prefix;
3132 CXIndex Idx;
3133 CXIndexAction idxAction;
3134 int errorCode = 0;
3135
3136 check_prefix = 0;
3137 if (argc > 0) {
3138 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3139 check_prefix = argv[0] + strlen("-check-prefix=");
3140 ++argv;
3141 --argc;
3142 }
3143 }
3144
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003145 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003146 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003147 return -1;
3148 }
3149
3150 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003151 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003152 fprintf(stderr, "Could not create Index\n");
3153 return 1;
3154 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003155 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003156
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003157 {
3158 const char *database = argv[0];
3159 CXCompilationDatabase db = 0;
3160 CXCompileCommands CCmds = 0;
3161 CXCompileCommand CCmd;
3162 CXCompilationDatabase_Error ec;
3163 CXString wd;
3164#define MAX_COMPILE_ARGS 512
3165 CXString cxargs[MAX_COMPILE_ARGS];
3166 const char *args[MAX_COMPILE_ARGS];
3167 char *tmp;
3168 unsigned len;
3169 char *buildDir;
3170 int i, a, numCmds, numArgs;
3171
3172 len = strlen(database);
3173 tmp = (char *) malloc(len+1);
3174 memcpy(tmp, database, len+1);
3175 buildDir = dirname(tmp);
3176
3177 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3178
3179 if (db) {
3180
3181 if (ec!=CXCompilationDatabase_NoError) {
3182 printf("unexpected error %d code while loading compilation database\n", ec);
3183 errorCode = -1;
3184 goto cdb_end;
3185 }
3186
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003187 if (chdir(buildDir) != 0) {
3188 printf("Could not chdir to %s\n", buildDir);
3189 errorCode = -1;
3190 goto cdb_end;
3191 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003192
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003193 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003194 if (!CCmds) {
3195 printf("compilation db is empty\n");
3196 errorCode = -1;
3197 goto cdb_end;
3198 }
3199
3200 numCmds = clang_CompileCommands_getSize(CCmds);
3201
3202 if (numCmds==0) {
3203 fprintf(stderr, "should not get an empty compileCommand set\n");
3204 errorCode = -1;
3205 goto cdb_end;
3206 }
3207
3208 for (i=0; i<numCmds && errorCode == 0; ++i) {
3209 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3210
3211 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003212 if (chdir(clang_getCString(wd)) != 0) {
3213 printf("Could not chdir to %s\n", clang_getCString(wd));
3214 errorCode = -1;
3215 goto cdb_end;
3216 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003217 clang_disposeString(wd);
3218
3219 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3220 if (numArgs > MAX_COMPILE_ARGS){
3221 fprintf(stderr, "got more compile arguments than maximum\n");
3222 errorCode = -1;
3223 goto cdb_end;
3224 }
3225 for (a=0; a<numArgs; ++a) {
3226 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3227 args[a] = clang_getCString(cxargs[a]);
3228 }
3229
3230 errorCode = index_compile_args(numArgs, args, idxAction,
3231 /*importedASTs=*/0, check_prefix);
3232
3233 for (a=0; a<numArgs; ++a)
3234 clang_disposeString(cxargs[a]);
3235 }
3236 } else {
3237 printf("database loading failed with error code %d.\n", ec);
3238 errorCode = -1;
3239 }
3240
3241 cdb_end:
3242 clang_CompileCommands_dispose(CCmds);
3243 clang_CompilationDatabase_dispose(db);
3244 free(tmp);
3245
3246 }
3247
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003248 clang_IndexAction_dispose(idxAction);
3249 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003250 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003251}
3252
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003253int perform_token_annotation(int argc, const char **argv) {
3254 const char *input = argv[1];
3255 char *filename = 0;
3256 unsigned line, second_line;
3257 unsigned column, second_column;
3258 CXIndex CIdx;
3259 CXTranslationUnit TU = 0;
3260 int errorCode;
3261 struct CXUnsavedFile *unsaved_files = 0;
3262 int num_unsaved_files = 0;
3263 CXToken *tokens;
3264 unsigned num_tokens;
3265 CXSourceRange range;
3266 CXSourceLocation startLoc, endLoc;
3267 CXFile file = 0;
3268 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003269 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003270 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003271 unsigned i;
3272
3273 input += strlen("-test-annotate-tokens=");
3274 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3275 &second_line, &second_column)))
3276 return errorCode;
3277
Richard Smith1ea42eb2012-07-05 08:20:49 +00003278 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3279 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003280 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003281 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003282
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003283 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003284 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3285 argv + num_unsaved_files + 2,
3286 argc - num_unsaved_files - 3,
3287 unsaved_files,
3288 num_unsaved_files,
3289 getDefaultParsingOptions(), &TU);
3290 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003291 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003292 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003293 clang_disposeIndex(CIdx);
3294 free(filename);
3295 free_remapped_files(unsaved_files, num_unsaved_files);
3296 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003297 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003298 errorCode = 0;
3299
Richard Smith1ea42eb2012-07-05 08:20:49 +00003300 if (checkForErrors(TU) != 0) {
3301 errorCode = -1;
3302 goto teardown;
3303 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003304
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003305 if (getenv("CINDEXTEST_EDITING")) {
3306 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003307 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3308 clang_defaultReparseOptions(TU));
3309 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003310 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003311 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003312 errorCode = -1;
3313 goto teardown;
3314 }
3315 }
3316 }
3317
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003318 if (checkForErrors(TU) != 0) {
3319 errorCode = -1;
3320 goto teardown;
3321 }
3322
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003323 file = clang_getFile(TU, filename);
3324 if (!file) {
3325 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3326 errorCode = -1;
3327 goto teardown;
3328 }
3329
3330 startLoc = clang_getLocation(TU, file, line, column);
3331 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003332 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003333 column);
3334 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003335 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003336 }
3337
3338 endLoc = clang_getLocation(TU, file, second_line, second_column);
3339 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003340 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003341 second_line, second_column);
3342 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003343 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003344 }
3345
3346 range = clang_getRange(startLoc, endLoc);
3347 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003348
3349 if (checkForErrors(TU) != 0) {
3350 errorCode = -1;
3351 goto teardown;
3352 }
3353
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003354 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3355 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003356
3357 if (checkForErrors(TU) != 0) {
3358 errorCode = -1;
3359 goto teardown;
3360 }
3361
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003362 skipped_ranges = clang_getSkippedRanges(TU, file);
3363 for (i = 0; i != skipped_ranges->count; ++i) {
3364 unsigned start_line, start_column, end_line, end_column;
3365 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3366 0, &start_line, &start_column, 0);
3367 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3368 0, &end_line, &end_column, 0);
3369 printf("Skipping: ");
3370 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3371 printf("\n");
3372 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003373 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003374
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003375 for (i = 0; i != num_tokens; ++i) {
3376 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003377 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3378 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003379 unsigned start_line, start_column, end_line, end_column;
3380
3381 switch (clang_getTokenKind(tokens[i])) {
3382 case CXToken_Punctuation: kind = "Punctuation"; break;
3383 case CXToken_Keyword: kind = "Keyword"; break;
3384 case CXToken_Identifier: kind = "Identifier"; break;
3385 case CXToken_Literal: kind = "Literal"; break;
3386 case CXToken_Comment: kind = "Comment"; break;
3387 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003388 clang_getSpellingLocation(clang_getRangeStart(extent),
3389 0, &start_line, &start_column, 0);
3390 clang_getSpellingLocation(clang_getRangeEnd(extent),
3391 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003392 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003393 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003394 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003395 if (!clang_isInvalid(cursors[i].kind)) {
3396 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003397 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003398 }
3399 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003400 }
3401 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003402 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003403
3404 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003405 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003406 clang_disposeTranslationUnit(TU);
3407 clang_disposeIndex(CIdx);
3408 free(filename);
3409 free_remapped_files(unsaved_files, num_unsaved_files);
3410 return errorCode;
3411}
3412
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003413static int
3414perform_test_compilation_db(const char *database, int argc, const char **argv) {
3415 CXCompilationDatabase db;
3416 CXCompileCommands CCmds;
3417 CXCompileCommand CCmd;
3418 CXCompilationDatabase_Error ec;
3419 CXString wd;
3420 CXString arg;
3421 int errorCode = 0;
3422 char *tmp;
3423 unsigned len;
3424 char *buildDir;
3425 int i, j, a, numCmds, numArgs;
3426
3427 len = strlen(database);
3428 tmp = (char *) malloc(len+1);
3429 memcpy(tmp, database, len+1);
3430 buildDir = dirname(tmp);
3431
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003432 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003433
3434 if (db) {
3435
3436 if (ec!=CXCompilationDatabase_NoError) {
3437 printf("unexpected error %d code while loading compilation database\n", ec);
3438 errorCode = -1;
3439 goto cdb_end;
3440 }
3441
3442 for (i=0; i<argc && errorCode==0; ) {
3443 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003444 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003445
3446 if (!CCmds) {
3447 printf("file %s not found in compilation db\n", argv[i+1]);
3448 errorCode = -1;
3449 break;
3450 }
3451
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003452 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003453
3454 if (numCmds==0) {
3455 fprintf(stderr, "should not get an empty compileCommand set for file"
3456 " '%s'\n", argv[i+1]);
3457 errorCode = -1;
3458 break;
3459 }
3460
3461 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003462 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003463
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003464 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003465 printf("workdir:'%s'", clang_getCString(wd));
3466 clang_disposeString(wd);
3467
3468 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003469 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003470 for (a=0; a<numArgs; ++a) {
3471 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003472 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003473 printf("%s", clang_getCString(arg));
3474 clang_disposeString(arg);
3475 }
3476 printf("'\n");
3477 }
3478
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003479 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003480
3481 i += 2;
3482 }
3483 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003484 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003485 } else {
3486 printf("database loading failed with error code %d.\n", ec);
3487 errorCode = -1;
3488 }
3489
3490cdb_end:
3491 free(tmp);
3492
3493 return errorCode;
3494}
3495
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003496/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003497/* USR printing. */
3498/******************************************************************************/
3499
3500static int insufficient_usr(const char *kind, const char *usage) {
3501 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3502 return 1;
3503}
3504
3505static unsigned isUSR(const char *s) {
3506 return s[0] == 'c' && s[1] == ':';
3507}
3508
3509static int not_usr(const char *s, const char *arg) {
3510 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3511 return 1;
3512}
3513
3514static void print_usr(CXString usr) {
3515 const char *s = clang_getCString(usr);
3516 printf("%s\n", s);
3517 clang_disposeString(usr);
3518}
3519
3520static void display_usrs() {
3521 fprintf(stderr, "-print-usrs options:\n"
3522 " ObjCCategory <class name> <category name>\n"
3523 " ObjCClass <class name>\n"
3524 " ObjCIvar <ivar name> <class USR>\n"
3525 " ObjCMethod <selector> [0=class method|1=instance method] "
3526 "<class USR>\n"
3527 " ObjCProperty <property name> <class USR>\n"
3528 " ObjCProtocol <protocol name>\n");
3529}
3530
3531int print_usrs(const char **I, const char **E) {
3532 while (I != E) {
3533 const char *kind = *I;
3534 unsigned len = strlen(kind);
3535 switch (len) {
3536 case 8:
3537 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3538 if (I + 2 >= E)
3539 return insufficient_usr(kind, "<ivar name> <class USR>");
3540 if (!isUSR(I[2]))
3541 return not_usr("<class USR>", I[2]);
3542 else {
3543 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003544 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003545 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003546 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3547 }
3548
3549 I += 3;
3550 continue;
3551 }
3552 break;
3553 case 9:
3554 if (memcmp(kind, "ObjCClass", 9) == 0) {
3555 if (I + 1 >= E)
3556 return insufficient_usr(kind, "<class name>");
3557 print_usr(clang_constructUSR_ObjCClass(I[1]));
3558 I += 2;
3559 continue;
3560 }
3561 break;
3562 case 10:
3563 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3564 if (I + 3 >= E)
3565 return insufficient_usr(kind, "<method selector> "
3566 "[0=class method|1=instance method] <class USR>");
3567 if (!isUSR(I[3]))
3568 return not_usr("<class USR>", I[3]);
3569 else {
3570 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003571 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003572 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003573 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3574 }
3575 I += 4;
3576 continue;
3577 }
3578 break;
3579 case 12:
3580 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3581 if (I + 2 >= E)
3582 return insufficient_usr(kind, "<class name> <category name>");
3583 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3584 I += 3;
3585 continue;
3586 }
3587 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3588 if (I + 1 >= E)
3589 return insufficient_usr(kind, "<protocol name>");
3590 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3591 I += 2;
3592 continue;
3593 }
3594 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3595 if (I + 2 >= E)
3596 return insufficient_usr(kind, "<property name> <class USR>");
3597 if (!isUSR(I[2]))
3598 return not_usr("<class USR>", I[2]);
3599 else {
3600 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003601 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003602 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003603 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3604 }
3605 I += 3;
3606 continue;
3607 }
3608 break;
3609 default:
3610 break;
3611 }
3612 break;
3613 }
3614
3615 if (I != E) {
3616 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3617 display_usrs();
3618 return 1;
3619 }
3620 return 0;
3621}
3622
3623int print_usrs_file(const char *file_name) {
3624 char line[2048];
3625 const char *args[128];
3626 unsigned numChars = 0;
3627
3628 FILE *fp = fopen(file_name, "r");
3629 if (!fp) {
3630 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3631 return 1;
3632 }
3633
3634 /* This code is not really all that safe, but it works fine for testing. */
3635 while (!feof(fp)) {
3636 char c = fgetc(fp);
3637 if (c == '\n') {
3638 unsigned i = 0;
3639 const char *s = 0;
3640
3641 if (numChars == 0)
3642 continue;
3643
3644 line[numChars] = '\0';
3645 numChars = 0;
3646
3647 if (line[0] == '/' && line[1] == '/')
3648 continue;
3649
3650 s = strtok(line, " ");
3651 while (s) {
3652 args[i] = s;
3653 ++i;
3654 s = strtok(0, " ");
3655 }
3656 if (print_usrs(&args[0], &args[i]))
3657 return 1;
3658 }
3659 else
3660 line[numChars++] = c;
3661 }
3662
3663 fclose(fp);
3664 return 0;
3665}
3666
3667/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003668/* Command line processing. */
3669/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003670int write_pch_file(const char *filename, int argc, const char *argv[]) {
3671 CXIndex Idx;
3672 CXTranslationUnit TU;
3673 struct CXUnsavedFile *unsaved_files = 0;
3674 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003675 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003676 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003677
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003678 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003679
3680 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3681 clang_disposeIndex(Idx);
3682 return -1;
3683 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003684
3685 Err = clang_parseTranslationUnit2(
3686 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3687 unsaved_files, num_unsaved_files,
3688 CXTranslationUnit_Incomplete |
3689 CXTranslationUnit_DetailedPreprocessingRecord |
3690 CXTranslationUnit_ForSerialization,
3691 &TU);
3692 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003693 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003694 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003695 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003696 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003697 clang_disposeIndex(Idx);
3698 return 1;
3699 }
3700
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003701 switch (clang_saveTranslationUnit(TU, filename,
3702 clang_defaultSaveOptions(TU))) {
3703 case CXSaveError_None:
3704 break;
3705
3706 case CXSaveError_TranslationErrors:
3707 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3708 filename);
3709 result = 2;
3710 break;
3711
3712 case CXSaveError_InvalidTU:
3713 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3714 filename);
3715 result = 3;
3716 break;
3717
3718 case CXSaveError_Unknown:
3719 default:
3720 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3721 result = 1;
3722 break;
3723 }
3724
Douglas Gregore9386682010-08-13 05:36:37 +00003725 clang_disposeTranslationUnit(TU);
3726 free_remapped_files(unsaved_files, num_unsaved_files);
3727 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003728 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003729}
3730
3731/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003732/* Serialized diagnostics. */
3733/******************************************************************************/
3734
3735static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3736 switch (error) {
3737 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3738 case CXLoadDiag_None: break;
3739 case CXLoadDiag_Unknown: return "Unknown";
3740 case CXLoadDiag_InvalidFile: return "Invalid File";
3741 }
3742 return "None";
3743}
3744
3745static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3746 switch (severity) {
3747 case CXDiagnostic_Note: return "note";
Tobias Grosser74160242014-02-28 09:11:08 +00003748 case CXDiagnostic_Remark: return "remark";
Ted Kremenekd010ba42011-11-10 08:43:12 +00003749 case CXDiagnostic_Error: return "error";
3750 case CXDiagnostic_Fatal: return "fatal";
3751 case CXDiagnostic_Ignored: return "ignored";
3752 case CXDiagnostic_Warning: return "warning";
3753 }
3754 return "unknown";
3755}
3756
3757static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003758 if (indent == 0)
3759 return;
3760 fprintf(stderr, "+");
3761 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003762 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003763 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003764 --indent;
3765 }
3766}
3767
3768static void printLocation(CXSourceLocation L) {
3769 CXFile File;
3770 CXString FileName;
3771 unsigned line, column, offset;
3772
3773 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3774 FileName = clang_getFileName(File);
3775
3776 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3777 clang_disposeString(FileName);
3778}
3779
3780static void printRanges(CXDiagnostic D, unsigned indent) {
3781 unsigned i, n = clang_getDiagnosticNumRanges(D);
3782
3783 for (i = 0; i < n; ++i) {
3784 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003785 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003786 Start = clang_getRangeStart(SR);
3787 End = clang_getRangeEnd(SR);
3788
3789 printIndent(indent);
3790 fprintf(stderr, "Range: ");
3791 printLocation(Start);
3792 fprintf(stderr, " ");
3793 printLocation(End);
3794 fprintf(stderr, "\n");
3795 }
3796}
3797
3798static void printFixIts(CXDiagnostic D, unsigned indent) {
3799 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003800 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003801 for (i = 0 ; i < n; ++i) {
3802 CXSourceRange ReplacementRange;
3803 CXString text;
3804 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3805
3806 printIndent(indent);
3807 fprintf(stderr, "FIXIT: (");
3808 printLocation(clang_getRangeStart(ReplacementRange));
3809 fprintf(stderr, " - ");
3810 printLocation(clang_getRangeEnd(ReplacementRange));
3811 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3812 clang_disposeString(text);
3813 }
3814}
3815
3816static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003817 unsigned i, n;
3818
Ted Kremenekd010ba42011-11-10 08:43:12 +00003819 if (!Diags)
3820 return;
3821
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003822 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003823 for (i = 0; i < n; ++i) {
3824 CXSourceLocation DiagLoc;
3825 CXDiagnostic D;
3826 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003827 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003828 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003829 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003830
3831 D = clang_getDiagnosticInSet(Diags, i);
3832 DiagLoc = clang_getDiagnosticLocation(D);
3833 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3834 FileName = clang_getFileName(File);
3835 DiagSpelling = clang_getDiagnosticSpelling(D);
3836
3837 printIndent(indent);
3838
3839 fprintf(stderr, "%s:%d:%d: %s: %s",
3840 clang_getCString(FileName),
3841 line,
3842 column,
3843 getSeverityString(clang_getDiagnosticSeverity(D)),
3844 clang_getCString(DiagSpelling));
3845
3846 DiagOption = clang_getDiagnosticOption(D, 0);
3847 DiagOptionStr = clang_getCString(DiagOption);
3848 if (DiagOptionStr) {
3849 fprintf(stderr, " [%s]", DiagOptionStr);
3850 }
3851
Ted Kremenek26a6d492012-04-12 00:03:31 +00003852 DiagCat = clang_getDiagnosticCategoryText(D);
3853 DiagCatStr = clang_getCString(DiagCat);
3854 if (DiagCatStr) {
3855 fprintf(stderr, " [%s]", DiagCatStr);
3856 }
3857
Ted Kremenekd010ba42011-11-10 08:43:12 +00003858 fprintf(stderr, "\n");
3859
3860 printRanges(D, indent);
3861 printFixIts(D, indent);
3862
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00003863 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00003864 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3865
3866 clang_disposeString(FileName);
3867 clang_disposeString(DiagSpelling);
3868 clang_disposeString(DiagOption);
3869 }
3870}
3871
3872static int read_diagnostics(const char *filename) {
3873 enum CXLoadDiag_Error error;
3874 CXString errorString;
3875 CXDiagnosticSet Diags = 0;
3876
3877 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3878 if (!Diags) {
3879 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3880 getDiagnosticCodeStr(error),
3881 clang_getCString(errorString));
3882 clang_disposeString(errorString);
3883 return 1;
3884 }
3885
3886 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003887 fprintf(stderr, "Number of diagnostics: %d\n",
3888 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00003889 clang_disposeDiagnosticSet(Diags);
3890 return 0;
3891}
3892
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003893static int perform_print_build_session_timestamp(void) {
3894 printf("%lld\n", clang_getBuildSessionTimestamp());
3895 return 0;
3896}
3897
Ted Kremenekd010ba42011-11-10 08:43:12 +00003898/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003899/* Command line processing. */
3900/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00003901
Douglas Gregor720d0052010-01-20 21:32:04 +00003902static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003903 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00003904 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003905 if (strcmp(s, "-usrs") == 0)
3906 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00003907 if (strncmp(s, "-memory-usage", 13) == 0)
3908 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003909 return NULL;
3910}
3911
Ted Kremenekef3339b2009-11-17 18:09:14 +00003912static void print_usage(void) {
3913 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003914 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003915 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00003916 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00003917 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
3918 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00003919 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003920 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003921 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003922 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003923 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00003924 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00003925 "[FileCheck prefix]\n");
3926 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00003927 " c-index-test -test-load-tu <AST file> <symbol filter> "
3928 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003929 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3930 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003931 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00003932 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00003933 " c-index-test -test-load-source-memory-usage "
3934 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00003935 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3936 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00003937 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00003938 " c-index-test -test-load-source-usrs-memory-usage "
3939 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00003940 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3941 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00003942 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00003943 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00003944 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00003945 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00003946 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00003947 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00003948 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00003949 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00003950 " c-index-test -write-pch <file> <compiler arguments>\n");
3951 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003952 " c-index-test -compilation-db [lookup <filename>] database\n");
3953 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003954 " c-index-test -print-build-session-timestamp\n");
3955 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00003956 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00003957 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003958 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003959 " all - load all symbols, including those from PCH\n"
3960 " local - load all symbols except those in PCH\n"
3961 " category - only load ObjC categories (non-PCH)\n"
3962 " interface - only load ObjC interfaces (non-PCH)\n"
3963 " protocol - only load ObjC protocols (non-PCH)\n"
3964 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00003965 " typedef - only load typdefs (non-PCH)\n"
3966 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00003967}
3968
Daniel Dunbar08b33d02010-09-30 20:39:47 +00003969/***/
3970
3971int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003972 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00003973 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3974 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00003975 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00003976 return perform_code_completion(argc, argv, 0);
3977 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3978 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00003979 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3980 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00003981 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3982 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00003983 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
3984 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003985 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003986 return index_file(argc - 2, argv + 2, /*full=*/0);
3987 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
3988 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003989 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3990 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003991 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
3992 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003993 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00003994 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003995 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00003996 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3997 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00003998 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00003999 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4000 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4001 if (I) {
4002 int trials = atoi(argv[2]);
4003 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4004 NULL);
4005 }
4006 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004007 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004008 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004009
4010 PostVisitTU postVisit = 0;
4011 if (strstr(argv[1], "-memory-usage"))
4012 postVisit = PrintMemoryUsage;
4013
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004014 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004015 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4016 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004017 }
4018 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004019 return perform_file_scan(argv[2], argv[3],
4020 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004021 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4022 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004023 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4024 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4025 PrintInclusionStack);
4026 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4027 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4028 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004029 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4030 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4031 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004032 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004033 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004034 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004035 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4036 return perform_test_load_source(argc - 2, argv + 2, "all",
4037 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004038 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4039 return perform_test_load_source(argc - 2, argv + 2, "all",
4040 PrintBitWidth, 0);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004041 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4042 if (argc > 2)
4043 return print_usrs(argv + 2, argv + argc);
4044 else {
4045 display_usrs();
4046 return 1;
4047 }
4048 }
4049 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4050 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004051 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4052 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004053 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4054 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004055 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4056 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004057
Ted Kremenekef3339b2009-11-17 18:09:14 +00004058 print_usage();
4059 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004060}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004061
4062/***/
4063
4064/* We intentionally run in a separate thread to ensure we at least minimal
4065 * testing of a multithreaded environment (for example, having a reduced stack
4066 * size). */
4067
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004068typedef struct thread_info {
4069 int argc;
4070 const char **argv;
4071 int result;
4072} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004073void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004074 thread_info *client_data = client_data_v;
4075 client_data->result = cindextest_main(client_data->argc, client_data->argv);
NAKAMURA Takumia7d49882012-04-07 06:59:28 +00004076#ifdef __CYGWIN__
4077 fflush(stdout); /* stdout is not flushed on Cygwin. */
4078#endif
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004079}
4080
4081int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004082 thread_info client_data;
4083
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004084#ifdef CLANG_HAVE_LIBXML
4085 LIBXML_TEST_VERSION
4086#endif
4087
Douglas Gregorf428bf82010-10-27 16:00:01 +00004088 if (getenv("CINDEXTEST_NOTHREADS"))
4089 return cindextest_main(argc, argv);
4090
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004091 client_data.argc = argc;
4092 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004093 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004094 return client_data.result;
4095}