1/* c-index-test.c */
2
3#include "clang-c/BuildSystem.h"
4#include "clang-c/CXCompilationDatabase.h"
5#include "clang-c/CXErrorCode.h"
6#include "clang-c/CXSourceLocation.h"
7#include "clang-c/CXString.h"
8#include "clang-c/Documentation.h"
9#include "clang-c/Index.h"
10#include "clang/Config/config.h"
11#include "llvm/Support/AutoConvert.h"
12#include <assert.h>
13#include <ctype.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17
18#ifdef CLANG_HAVE_LIBXML
19#include <libxml/parser.h>
20#include <libxml/relaxng.h>
21#include <libxml/xmlerror.h>
22#endif
23
24#ifdef _WIN32
25# include <direct.h>
26#else
27# include <unistd.h>
28#endif
29
30extern int indextest_core_main(int argc, const char **argv);
31extern int indextest_perform_shell_execution(const char *command_line);
32
33/******************************************************************************/
34/* Utility functions. */
35/******************************************************************************/
36
37#ifdef _MSC_VER
38char *basename(const char* path)
39{
40 char* base1 = (char*)strrchr(path, '/');
41 char* base2 = (char*)strrchr(path, '\\');
42 if (base1 && base2)
43 return((base1 > base2) ? base1 + 1 : base2 + 1);
44 else if (base1)
45 return(base1 + 1);
46 else if (base2)
47 return(base2 + 1);
48
49#ifdef __clang__
50#pragma clang diagnostic push
51#pragma clang diagnostic ignored "-Wcast-qual"
52#endif
53 return ((char *)path);
54#ifdef __clang__
55#pragma clang diagnostic pop
56#endif
57}
58char *dirname(char* path)
59{
60 char* base1 = (char*)strrchr(path, '/');
61 char* base2 = (char*)strrchr(path, '\\');
62 if (base1 && base2)
63 if (base1 > base2)
64 *base1 = 0;
65 else
66 *base2 = 0;
67 else if (base1)
68 *base1 = 0;
69 else if (base2)
70 *base2 = 0;
71
72 return path;
73}
74#else
75extern char *basename(const char *);
76extern char *dirname(char *);
77#endif
78
79CXIndex createIndexWithInvocationEmissionPath(int ExcludeDeclarationsFromPCH,
80 int DisplayDiagnostics) {
81 CXIndex Idx;
82
83 CXIndexOptions Opts;
84 memset(s: &Opts, c: 0, n: sizeof(Opts));
85 Opts.Size = sizeof(CXIndexOptions);
86 Opts.ExcludeDeclarationsFromPCH = ExcludeDeclarationsFromPCH;
87 Opts.DisplayDiagnostics = DisplayDiagnostics;
88 Opts.InvocationEmissionPath = getenv(name: "CINDEXTEST_INVOCATION_EMISSION_PATH");
89
90 Idx = clang_createIndexWithOptions(options: &Opts);
91 if (!Idx) {
92 fprintf(stderr,
93 format: "clang_createIndexWithOptions() failed. "
94 "CINDEX_VERSION_MINOR = %d, sizeof(CXIndexOptions) = %u\n",
95 CINDEX_VERSION_MINOR, Opts.Size);
96 }
97 return Idx;
98}
99
100/** Return the default parsing options. */
101static unsigned getDefaultParsingOptions(void) {
102 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
103
104 if (getenv(name: "CINDEXTEST_EDITING"))
105 options |= clang_defaultEditingTranslationUnitOptions();
106 if (getenv(name: "CINDEXTEST_COMPLETION_CACHING"))
107 options |= CXTranslationUnit_CacheCompletionResults;
108 if (getenv(name: "CINDEXTEST_COMPLETION_NO_CACHING"))
109 options &= ~CXTranslationUnit_CacheCompletionResults;
110 if (getenv(name: "CINDEXTEST_SKIP_FUNCTION_BODIES"))
111 options |= CXTranslationUnit_SkipFunctionBodies;
112 if (getenv(name: "CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
113 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
114 if (getenv(name: "CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
115 options |= CXTranslationUnit_CreatePreambleOnFirstParse;
116 if (getenv(name: "CINDEXTEST_KEEP_GOING"))
117 options |= CXTranslationUnit_KeepGoing;
118 if (getenv(name: "CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
119 options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
120 if (getenv(name: "CINDEXTEST_INCLUDE_ATTRIBUTED_TYPES"))
121 options |= CXTranslationUnit_IncludeAttributedTypes;
122 if (getenv(name: "CINDEXTEST_VISIT_IMPLICIT_ATTRIBUTES"))
123 options |= CXTranslationUnit_VisitImplicitAttributes;
124 if (getenv(name: "CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES"))
125 options |= CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles;
126
127 return options;
128}
129
130static void ModifyPrintingPolicyAccordingToEnv(CXPrintingPolicy Policy) {
131 struct Mapping {
132 const char *name;
133 enum CXPrintingPolicyProperty property;
134 };
135 struct Mapping mappings[] = {
136 {"CINDEXTEST_PRINTINGPOLICY_INDENTATION", CXPrintingPolicy_Indentation},
137 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSPECIFIERS",
138 CXPrintingPolicy_SuppressSpecifiers},
139 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTAGKEYWORD",
140 CXPrintingPolicy_SuppressTagKeyword},
141 {"CINDEXTEST_PRINTINGPOLICY_INCLUDETAGDEFINITION",
142 CXPrintingPolicy_IncludeTagDefinition},
143 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSCOPE",
144 CXPrintingPolicy_SuppressScope},
145 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSUNWRITTENSCOPE",
146 CXPrintingPolicy_SuppressUnwrittenScope},
147 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSINITIALIZERS",
148 CXPrintingPolicy_SuppressInitializers},
149 {"CINDEXTEST_PRINTINGPOLICY_CONSTANTARRAYSIZEASWRITTEN",
150 CXPrintingPolicy_ConstantArraySizeAsWritten},
151 {"CINDEXTEST_PRINTINGPOLICY_ANONYMOUSTAGLOCATIONS",
152 CXPrintingPolicy_AnonymousTagLocations},
153 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSTRONGLIFETIME",
154 CXPrintingPolicy_SuppressStrongLifetime},
155 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSLIFETIMEQUALIFIERS",
156 CXPrintingPolicy_SuppressLifetimeQualifiers},
157 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTEMPLATEARGSINCXXCONSTRUCTORS",
158 CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors},
159 {"CINDEXTEST_PRINTINGPOLICY_BOOL", CXPrintingPolicy_Bool},
160 {"CINDEXTEST_PRINTINGPOLICY_RESTRICT", CXPrintingPolicy_Restrict},
161 {"CINDEXTEST_PRINTINGPOLICY_ALIGNOF", CXPrintingPolicy_Alignof},
162 {"CINDEXTEST_PRINTINGPOLICY_UNDERSCOREALIGNOF",
163 CXPrintingPolicy_UnderscoreAlignof},
164 {"CINDEXTEST_PRINTINGPOLICY_USEVOIDFORZEROPARAMS",
165 CXPrintingPolicy_UseVoidForZeroParams},
166 {"CINDEXTEST_PRINTINGPOLICY_TERSEOUTPUT", CXPrintingPolicy_TerseOutput},
167 {"CINDEXTEST_PRINTINGPOLICY_POLISHFORDECLARATION",
168 CXPrintingPolicy_PolishForDeclaration},
169 {"CINDEXTEST_PRINTINGPOLICY_HALF", CXPrintingPolicy_Half},
170 {"CINDEXTEST_PRINTINGPOLICY_MSWCHAR", CXPrintingPolicy_MSWChar},
171 {"CINDEXTEST_PRINTINGPOLICY_INCLUDENEWLINES",
172 CXPrintingPolicy_IncludeNewlines},
173 {"CINDEXTEST_PRINTINGPOLICY_MSVCFORMATTING",
174 CXPrintingPolicy_MSVCFormatting},
175 {"CINDEXTEST_PRINTINGPOLICY_CONSTANTSASWRITTEN",
176 CXPrintingPolicy_ConstantsAsWritten},
177 {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSIMPLICITBASE",
178 CXPrintingPolicy_SuppressImplicitBase},
179 {"CINDEXTEST_PRINTINGPOLICY_FULLYQUALIFIEDNAME",
180 CXPrintingPolicy_FullyQualifiedName},
181 };
182
183 unsigned i;
184 for (i = 0; i < sizeof(mappings) / sizeof(struct Mapping); i++) {
185 char *value = getenv(name: mappings[i].name);
186 if (value) {
187 clang_PrintingPolicy_setProperty(Policy, Property: mappings[i].property,
188 Value: (unsigned)strtoul(nptr: value, endptr: 0L, base: 10));
189 }
190 }
191}
192
193/** Returns 0 in case of success, non-zero in case of a failure. */
194static int checkForErrors(CXTranslationUnit TU);
195
196static void describeLibclangFailure(enum CXErrorCode Err) {
197 switch (Err) {
198 case CXError_Success:
199 fprintf(stderr, format: "Success\n");
200 return;
201
202 case CXError_Failure:
203 fprintf(stderr, format: "Failure (no details available)\n");
204 return;
205
206 case CXError_Crashed:
207 fprintf(stderr, format: "Failure: libclang crashed\n");
208 return;
209
210 case CXError_InvalidArguments:
211 fprintf(stderr, format: "Failure: invalid arguments passed to a libclang routine\n");
212 return;
213
214 case CXError_ASTReadError:
215 fprintf(stderr, format: "Failure: AST deserialization error occurred\n");
216 return;
217 }
218}
219
220static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
221 unsigned end_line, unsigned end_column) {
222 fprintf(stream: out, format: "[%d:%d - %d:%d]", begin_line, begin_column,
223 end_line, end_column);
224}
225
226static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
227 CXTranslationUnit *TU) {
228 enum CXErrorCode Err = clang_createTranslationUnit2(CIdx: Idx, ast_filename: file, out_TU: TU);
229 if (Err != CXError_Success) {
230 fprintf(stderr, format: "Unable to load translation unit from '%s'!\n", file);
231 describeLibclangFailure(Err);
232 *TU = 0;
233 return 0;
234 }
235 return 1;
236}
237
238void free_remapped_files(struct CXUnsavedFile *unsaved_files,
239 int num_unsaved_files) {
240 int i;
241 for (i = 0; i != num_unsaved_files; ++i) {
242#ifdef __GNUC__
243#pragma GCC diagnostic push
244#pragma GCC diagnostic ignored "-Wcast-qual"
245#elif defined(__clang__)
246#pragma clang diagnostic push
247#pragma clang diagnostic ignored "-Wcast-qual"
248#endif
249 free(ptr: (char *)unsaved_files[i].Filename);
250 free(ptr: (char *)unsaved_files[i].Contents);
251#ifdef __GNUC__
252#pragma GCC diagnostic pop
253#elif defined(__clang__)
254#pragma clang diagnostic pop
255#endif
256 }
257 free(ptr: unsaved_files);
258}
259
260static int parse_remapped_files_with_opt(const char *opt_name,
261 int argc, const char **argv,
262 int start_arg,
263 struct CXUnsavedFile **unsaved_files,
264 int *num_unsaved_files) {
265 int i;
266 int arg;
267 int prefix_len = strlen(s: opt_name);
268 int arg_indices[20];
269 *unsaved_files = 0;
270 *num_unsaved_files = 0;
271
272 /* Count the number of remapped files. */
273 for (arg = start_arg; arg < argc; ++arg) {
274 if (strncmp(s1: argv[arg], s2: opt_name, n: prefix_len))
275 continue;
276
277 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
278 arg_indices[*num_unsaved_files] = arg;
279 ++*num_unsaved_files;
280 }
281
282 if (*num_unsaved_files == 0)
283 return 0;
284
285 *unsaved_files
286 = (struct CXUnsavedFile *)malloc(size: sizeof(struct CXUnsavedFile) *
287 *num_unsaved_files);
288 assert(*unsaved_files);
289 for (i = 0; i != *num_unsaved_files; ++i) {
290 struct CXUnsavedFile *unsaved = *unsaved_files + i;
291 const char *arg_string = argv[arg_indices[i]] + prefix_len;
292 int filename_len;
293 char *filename;
294 char *contents;
295 FILE *to_file;
296 const char *sep = strchr(s: arg_string, c: ',');
297 if (!sep) {
298 fprintf(stderr,
299 format: "error: %sfrom:to argument is missing comma\n", opt_name);
300 free_remapped_files(unsaved_files: *unsaved_files, num_unsaved_files: i);
301 *unsaved_files = 0;
302 *num_unsaved_files = 0;
303 return -1;
304 }
305
306 /* Open the file that we're remapping to. */
307 to_file = fopen(filename: sep + 1, modes: "rb");
308 if (!to_file) {
309 fprintf(stderr, format: "error: cannot open file %s that we are remapping to\n",
310 sep + 1);
311 free_remapped_files(unsaved_files: *unsaved_files, num_unsaved_files: i);
312 *unsaved_files = 0;
313 *num_unsaved_files = 0;
314 return -1;
315 }
316
317 /* Determine the length of the file we're remapping to. */
318 fseek(stream: to_file, off: 0, SEEK_END);
319 unsaved->Length = ftell(stream: to_file);
320 fseek(stream: to_file, off: 0, SEEK_SET);
321
322 /* Read the contents of the file we're remapping to. */
323 contents = (char *)malloc(size: unsaved->Length + 1);
324 assert(contents);
325 if (fread(ptr: contents, size: 1, n: unsaved->Length, stream: to_file) != unsaved->Length) {
326 fprintf(stderr, format: "error: unexpected %s reading 'to' file %s\n",
327 (feof(stream: to_file) ? "EOF" : "error"), sep + 1);
328 fclose(stream: to_file);
329 free_remapped_files(unsaved_files: *unsaved_files, num_unsaved_files: i);
330 free(ptr: contents);
331 *unsaved_files = 0;
332 *num_unsaved_files = 0;
333 return -1;
334 }
335 contents[unsaved->Length] = 0;
336 unsaved->Contents = contents;
337
338 /* Close the file. */
339 fclose(stream: to_file);
340
341 /* Copy the file name that we're remapping from. */
342 filename_len = sep - arg_string;
343 filename = (char *)malloc(size: filename_len + 1);
344 assert(filename);
345 memcpy(dest: filename, src: arg_string, n: filename_len);
346 filename[filename_len] = 0;
347 unsaved->Filename = filename;
348 }
349
350 return 0;
351}
352
353static int parse_remapped_files(int argc, const char **argv, int start_arg,
354 struct CXUnsavedFile **unsaved_files,
355 int *num_unsaved_files) {
356 return parse_remapped_files_with_opt(opt_name: "-remap-file=", argc, argv, start_arg,
357 unsaved_files, num_unsaved_files);
358}
359
360static int parse_remapped_files_with_try(int try_idx,
361 int argc, const char **argv,
362 int start_arg,
363 struct CXUnsavedFile **unsaved_files,
364 int *num_unsaved_files) {
365 struct CXUnsavedFile *unsaved_files_no_try_idx;
366 int num_unsaved_files_no_try_idx;
367 struct CXUnsavedFile *unsaved_files_try_idx;
368 int num_unsaved_files_try_idx;
369 int ret;
370 char opt_name[32];
371
372 ret = parse_remapped_files(argc, argv, start_arg,
373 unsaved_files: &unsaved_files_no_try_idx, num_unsaved_files: &num_unsaved_files_no_try_idx);
374 if (ret)
375 return ret;
376
377 sprintf(s: opt_name, format: "-remap-file-%d=", try_idx);
378 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
379 unsaved_files: &unsaved_files_try_idx, num_unsaved_files: &num_unsaved_files_try_idx);
380 if (ret)
381 return ret;
382
383 if (num_unsaved_files_no_try_idx == 0) {
384 *unsaved_files = unsaved_files_try_idx;
385 *num_unsaved_files = num_unsaved_files_try_idx;
386 return 0;
387 }
388 if (num_unsaved_files_try_idx == 0) {
389 *unsaved_files = unsaved_files_no_try_idx;
390 *num_unsaved_files = num_unsaved_files_no_try_idx;
391 return 0;
392 }
393
394 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
395 *unsaved_files
396 = (struct CXUnsavedFile *)realloc(ptr: unsaved_files_no_try_idx,
397 size: sizeof(struct CXUnsavedFile) *
398 *num_unsaved_files);
399 assert(*unsaved_files);
400 memcpy(dest: *unsaved_files + num_unsaved_files_no_try_idx,
401 src: unsaved_files_try_idx, n: sizeof(struct CXUnsavedFile) *
402 num_unsaved_files_try_idx);
403 free(ptr: unsaved_files_try_idx);
404 return 0;
405}
406
407static const char *parse_comments_schema(int argc, const char **argv) {
408 const char *CommentsSchemaArg = "-comments-xml-schema=";
409 const char *CommentSchemaFile = NULL;
410
411 if (argc == 0)
412 return CommentSchemaFile;
413
414 if (!strncmp(s1: argv[0], s2: CommentsSchemaArg, n: strlen(s: CommentsSchemaArg)))
415 CommentSchemaFile = argv[0] + strlen(s: CommentsSchemaArg);
416
417 return CommentSchemaFile;
418}
419
420/******************************************************************************/
421/* Pretty-printing. */
422/******************************************************************************/
423
424static const char *FileCheckPrefix = "CHECK";
425
426static void PrintCString(const char *CStr) {
427 if (CStr != NULL && CStr[0] != '\0') {
428 for ( ; *CStr; ++CStr) {
429 const char C = *CStr;
430 switch (C) {
431 case '\n': printf(format: "\\n"); break;
432 case '\r': printf(format: "\\r"); break;
433 case '\t': printf(format: "\\t"); break;
434 case '\v': printf(format: "\\v"); break;
435 case '\f': printf(format: "\\f"); break;
436 default: putchar(c: C); break;
437 }
438 }
439 }
440}
441
442static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
443 printf(format: " %s=[", Prefix);
444 PrintCString(CStr);
445 printf(format: "]");
446}
447
448static void PrintCXStringAndDispose(CXString Str) {
449 PrintCString(CStr: clang_getCString(string: Str));
450 clang_disposeString(string: Str);
451}
452
453static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
454 PrintCStringWithPrefix(Prefix, CStr: clang_getCString(string: Str));
455}
456
457static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
458 CXString Str) {
459 PrintCStringWithPrefix(Prefix, CStr: clang_getCString(string: Str));
460 clang_disposeString(string: Str);
461}
462
463static void PrintRange(CXSourceRange R, const char *str) {
464 CXFile begin_file, end_file;
465 unsigned begin_line, begin_column, end_line, end_column;
466
467 clang_getSpellingLocation(location: clang_getRangeStart(range: R),
468 file: &begin_file, line: &begin_line, column: &begin_column, offset: 0);
469 clang_getSpellingLocation(location: clang_getRangeEnd(range: R),
470 file: &end_file, line: &end_line, column: &end_column, offset: 0);
471 if (!begin_file || !end_file)
472 return;
473
474 if (str)
475 printf(format: " %s=", str);
476 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
477}
478
479static enum DisplayType {
480 DisplayType_Spelling,
481 DisplayType_DisplayName,
482 DisplayType_Pretty
483} wanted_display_type = DisplayType_Spelling;
484
485static void printVersion(const char *Prefix, CXVersion Version) {
486 if (Version.Major < 0)
487 return;
488 printf(format: "%s%d", Prefix, Version.Major);
489
490 if (Version.Minor < 0)
491 return;
492 printf(format: ".%d", Version.Minor);
493
494 if (Version.Subminor < 0)
495 return;
496 printf(format: ".%d", Version.Subminor);
497}
498
499struct CommentASTDumpingContext {
500 int IndentLevel;
501};
502
503static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
504 CXComment Comment) {
505 unsigned i;
506 unsigned e;
507 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
508
509 Ctx->IndentLevel++;
510 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
511 printf(format: " ");
512
513 printf(format: "(");
514 switch (Kind) {
515 case CXComment_Null:
516 printf(format: "CXComment_Null");
517 break;
518 case CXComment_Text:
519 printf(format: "CXComment_Text");
520 PrintCXStringWithPrefixAndDispose(Prefix: "Text",
521 Str: clang_TextComment_getText(Comment));
522 if (clang_Comment_isWhitespace(Comment))
523 printf(format: " IsWhitespace");
524 if (clang_InlineContentComment_hasTrailingNewline(Comment))
525 printf(format: " HasTrailingNewline");
526 break;
527 case CXComment_InlineCommand:
528 printf(format: "CXComment_InlineCommand");
529 PrintCXStringWithPrefixAndDispose(
530 Prefix: "CommandName",
531 Str: clang_InlineCommandComment_getCommandName(Comment));
532 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
533 case CXCommentInlineCommandRenderKind_Normal:
534 printf(format: " RenderNormal");
535 break;
536 case CXCommentInlineCommandRenderKind_Bold:
537 printf(format: " RenderBold");
538 break;
539 case CXCommentInlineCommandRenderKind_Monospaced:
540 printf(format: " RenderMonospaced");
541 break;
542 case CXCommentInlineCommandRenderKind_Emphasized:
543 printf(format: " RenderEmphasized");
544 break;
545 case CXCommentInlineCommandRenderKind_Anchor:
546 printf(format: " RenderAnchor");
547 break;
548 }
549 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
550 i != e; ++i) {
551 printf(format: " Arg[%u]=", i);
552 PrintCXStringAndDispose(
553 Str: clang_InlineCommandComment_getArgText(Comment, ArgIdx: i));
554 }
555 if (clang_InlineContentComment_hasTrailingNewline(Comment))
556 printf(format: " HasTrailingNewline");
557 break;
558 case CXComment_HTMLStartTag: {
559 unsigned NumAttrs;
560 printf(format: "CXComment_HTMLStartTag");
561 PrintCXStringWithPrefixAndDispose(
562 Prefix: "Name",
563 Str: clang_HTMLTagComment_getTagName(Comment));
564 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
565 if (NumAttrs != 0) {
566 printf(format: " Attrs:");
567 for (i = 0; i != NumAttrs; ++i) {
568 printf(format: " ");
569 PrintCXStringAndDispose(Str: clang_HTMLStartTag_getAttrName(Comment, AttrIdx: i));
570 printf(format: "=");
571 PrintCXStringAndDispose(Str: clang_HTMLStartTag_getAttrValue(Comment, AttrIdx: i));
572 }
573 }
574 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
575 printf(format: " SelfClosing");
576 if (clang_InlineContentComment_hasTrailingNewline(Comment))
577 printf(format: " HasTrailingNewline");
578 break;
579 }
580 case CXComment_HTMLEndTag:
581 printf(format: "CXComment_HTMLEndTag");
582 PrintCXStringWithPrefixAndDispose(
583 Prefix: "Name",
584 Str: clang_HTMLTagComment_getTagName(Comment));
585 if (clang_InlineContentComment_hasTrailingNewline(Comment))
586 printf(format: " HasTrailingNewline");
587 break;
588 case CXComment_Paragraph:
589 printf(format: "CXComment_Paragraph");
590 if (clang_Comment_isWhitespace(Comment))
591 printf(format: " IsWhitespace");
592 break;
593 case CXComment_BlockCommand:
594 printf(format: "CXComment_BlockCommand");
595 PrintCXStringWithPrefixAndDispose(
596 Prefix: "CommandName",
597 Str: clang_BlockCommandComment_getCommandName(Comment));
598 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
599 i != e; ++i) {
600 printf(format: " Arg[%u]=", i);
601 PrintCXStringAndDispose(
602 Str: clang_BlockCommandComment_getArgText(Comment, ArgIdx: i));
603 }
604 break;
605 case CXComment_ParamCommand:
606 printf(format: "CXComment_ParamCommand");
607 switch (clang_ParamCommandComment_getDirection(Comment)) {
608 case CXCommentParamPassDirection_In:
609 printf(format: " in");
610 break;
611 case CXCommentParamPassDirection_Out:
612 printf(format: " out");
613 break;
614 case CXCommentParamPassDirection_InOut:
615 printf(format: " in,out");
616 break;
617 }
618 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
619 printf(format: " explicitly");
620 else
621 printf(format: " implicitly");
622 PrintCXStringWithPrefixAndDispose(
623 Prefix: "ParamName",
624 Str: clang_ParamCommandComment_getParamName(Comment));
625 if (clang_ParamCommandComment_isParamIndexValid(Comment))
626 printf(format: " ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
627 else
628 printf(format: " ParamIndex=Invalid");
629 break;
630 case CXComment_TParamCommand:
631 printf(format: "CXComment_TParamCommand");
632 PrintCXStringWithPrefixAndDispose(
633 Prefix: "ParamName",
634 Str: clang_TParamCommandComment_getParamName(Comment));
635 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
636 printf(format: " ParamPosition={");
637 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
638 i != e; ++i) {
639 printf(format: "%u", clang_TParamCommandComment_getIndex(Comment, Depth: i));
640 if (i != e - 1)
641 printf(format: ", ");
642 }
643 printf(format: "}");
644 } else
645 printf(format: " ParamPosition=Invalid");
646 break;
647 case CXComment_VerbatimBlockCommand:
648 printf(format: "CXComment_VerbatimBlockCommand");
649 PrintCXStringWithPrefixAndDispose(
650 Prefix: "CommandName",
651 Str: clang_BlockCommandComment_getCommandName(Comment));
652 break;
653 case CXComment_VerbatimBlockLine:
654 printf(format: "CXComment_VerbatimBlockLine");
655 PrintCXStringWithPrefixAndDispose(
656 Prefix: "Text",
657 Str: clang_VerbatimBlockLineComment_getText(Comment));
658 break;
659 case CXComment_VerbatimLine:
660 printf(format: "CXComment_VerbatimLine");
661 PrintCXStringWithPrefixAndDispose(
662 Prefix: "Text",
663 Str: clang_VerbatimLineComment_getText(Comment));
664 break;
665 case CXComment_FullComment:
666 printf(format: "CXComment_FullComment");
667 break;
668 }
669 if (Kind != CXComment_Null) {
670 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
671 unsigned i;
672 for (i = 0; i != NumChildren; ++i) {
673 printf(format: "\n// %s: ", FileCheckPrefix);
674 DumpCXCommentInternal(Ctx, Comment: clang_Comment_getChild(Comment, ChildIdx: i));
675 }
676 }
677 printf(format: ")");
678 Ctx->IndentLevel--;
679}
680
681static void DumpCXComment(CXComment Comment) {
682 struct CommentASTDumpingContext Ctx;
683 Ctx.IndentLevel = 1;
684 printf(format: "\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
685 DumpCXCommentInternal(Ctx: &Ctx, Comment);
686 printf(format: "]");
687}
688
689static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
690#ifdef CLANG_HAVE_LIBXML
691 xmlRelaxNGParserCtxtPtr RNGParser;
692 xmlRelaxNGPtr Schema;
693 xmlDocPtr Doc;
694 xmlRelaxNGValidCtxtPtr ValidationCtxt;
695 int status;
696
697 if (!CommentSchemaFile)
698 return;
699
700 RNGParser = xmlRelaxNGNewParserCtxt(URL: CommentSchemaFile);
701 if (!RNGParser) {
702 printf(format: " libXMLError");
703 return;
704 }
705 Schema = xmlRelaxNGParse(ctxt: RNGParser);
706
707 Doc = xmlParseDoc(cur: (const xmlChar *) Str);
708
709 if (!Doc) {
710 const xmlError *Error = xmlGetLastError();
711 printf(format: " CommentXMLInvalid [not well-formed XML: %s]", Error->message);
712 return;
713 }
714
715 ValidationCtxt = xmlRelaxNGNewValidCtxt(schema: Schema);
716 status = xmlRelaxNGValidateDoc(ctxt: ValidationCtxt, doc: Doc);
717 if (!status)
718 printf(format: " CommentXMLValid");
719 else if (status > 0) {
720 const xmlError *Error = xmlGetLastError();
721 printf(format: " CommentXMLInvalid [not valid XML: %s]", Error->message);
722 } else
723 printf(format: " libXMLError");
724
725 xmlRelaxNGFreeValidCtxt(ctxt: ValidationCtxt);
726 xmlFreeDoc(cur: Doc);
727 xmlRelaxNGFree(schema: Schema);
728 xmlRelaxNGFreeParserCtxt(ctxt: RNGParser);
729#endif
730}
731
732static void PrintCursorComments(CXCursor Cursor,
733 const char *CommentSchemaFile) {
734 {
735 CXString RawComment;
736 const char *RawCommentCString;
737 CXString BriefComment;
738 const char *BriefCommentCString;
739
740 RawComment = clang_Cursor_getRawCommentText(C: Cursor);
741 RawCommentCString = clang_getCString(string: RawComment);
742 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
743 PrintCStringWithPrefix(Prefix: "RawComment", CStr: RawCommentCString);
744 PrintRange(R: clang_Cursor_getCommentRange(C: Cursor), str: "RawCommentRange");
745
746 BriefComment = clang_Cursor_getBriefCommentText(C: Cursor);
747 BriefCommentCString = clang_getCString(string: BriefComment);
748 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
749 PrintCStringWithPrefix(Prefix: "BriefComment", CStr: BriefCommentCString);
750 clang_disposeString(string: BriefComment);
751 }
752 clang_disposeString(string: RawComment);
753 }
754
755 {
756 CXComment Comment = clang_Cursor_getParsedComment(C: Cursor);
757 if (clang_Comment_getKind(Comment) != CXComment_Null) {
758 PrintCXStringWithPrefixAndDispose(Prefix: "FullCommentAsHTML",
759 Str: clang_FullComment_getAsHTML(Comment));
760 {
761 CXString XML;
762 XML = clang_FullComment_getAsXML(Comment);
763 PrintCXStringWithPrefix(Prefix: "FullCommentAsXML", Str: XML);
764 ValidateCommentXML(Str: clang_getCString(string: XML), CommentSchemaFile);
765 clang_disposeString(string: XML);
766 }
767
768 DumpCXComment(Comment);
769 }
770 }
771}
772
773typedef struct {
774 unsigned line;
775 unsigned col;
776} LineCol;
777
778static int lineCol_cmp(const void *p1, const void *p2) {
779 const LineCol *lhs = p1;
780 const LineCol *rhs = p2;
781 if (lhs->line != rhs->line)
782 return (int)lhs->line - (int)rhs->line;
783 return (int)lhs->col - (int)rhs->col;
784}
785
786static CXString CursorToText(CXCursor Cursor) {
787 CXString text;
788 switch (wanted_display_type) {
789 case DisplayType_Spelling:
790 return clang_getCursorSpelling(Cursor);
791 case DisplayType_DisplayName:
792 return clang_getCursorDisplayName(Cursor);
793 case DisplayType_Pretty: {
794 CXPrintingPolicy Policy = clang_getCursorPrintingPolicy(Cursor);
795 ModifyPrintingPolicyAccordingToEnv(Policy);
796 text = clang_getCursorPrettyPrinted(Cursor, Policy);
797 clang_PrintingPolicy_dispose(Policy);
798 return text;
799 }
800 }
801 assert(0 && "unknown display type"); /* no llvm_unreachable in C. */
802 /* Set to NULL to prevent uninitialized variable warnings. */
803 text.data = NULL;
804 text.private_flags = 0;
805 return text;
806}
807
808static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
809 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
810 if (clang_isInvalid(Cursor.kind)) {
811 CXString ks = clang_getCursorKindSpelling(Kind: Cursor.kind);
812 printf(format: "Invalid Cursor => %s", clang_getCString(string: ks));
813 clang_disposeString(string: ks);
814 }
815 else {
816 CXString string, ks;
817 CXCursor Referenced;
818 unsigned line, column;
819 CXCursor SpecializationOf;
820 CXCursor *overridden;
821 unsigned num_overridden;
822 unsigned RefNameRangeNr;
823 CXSourceRange CursorExtent;
824 CXSourceRange RefNameRange;
825 int AlwaysUnavailable;
826 int AlwaysDeprecated;
827 CXString UnavailableMessage;
828 CXString DeprecatedMessage;
829 CXPlatformAvailability PlatformAvailability[2];
830 int NumPlatformAvailability;
831 int I;
832
833 ks = clang_getCursorKindSpelling(Kind: Cursor.kind);
834 string = CursorToText(Cursor);
835 printf(format: "%s=%s", clang_getCString(string: ks),
836 clang_getCString(string));
837 clang_disposeString(string: ks);
838 clang_disposeString(string);
839
840 Referenced = clang_getCursorReferenced(Cursor);
841 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
842 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
843 unsigned I, N = clang_getNumOverloadedDecls(cursor: Referenced);
844 printf(format: "[");
845 for (I = 0; I != N; ++I) {
846 CXCursor Ovl = clang_getOverloadedDecl(cursor: Referenced, index: I);
847 CXSourceLocation Loc;
848 if (I)
849 printf(format: ", ");
850
851 Loc = clang_getCursorLocation(Ovl);
852 clang_getSpellingLocation(location: Loc, file: 0, line: &line, column: &column, offset: 0);
853 printf(format: "%d:%d", line, column);
854 }
855 printf(format: "]");
856 } else {
857 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
858 clang_getSpellingLocation(location: Loc, file: 0, line: &line, column: &column, offset: 0);
859 printf(format: ":%d:%d", line, column);
860 }
861
862 if (clang_getCursorKind(Referenced) == CXCursor_TypedefDecl) {
863 CXType T = clang_getCursorType(C: Referenced);
864 if (clang_Type_isTransparentTagTypedef(T)) {
865 CXType Underlying = clang_getTypedefDeclUnderlyingType(C: Referenced);
866 CXString S = clang_getTypeSpelling(CT: Underlying);
867 printf(format: " (Transparent: %s)", clang_getCString(string: S));
868 clang_disposeString(string: S);
869 }
870 }
871 }
872
873 if (clang_isCursorDefinition(Cursor))
874 printf(format: " (Definition)");
875
876 switch (clang_getCursorAvailability(cursor: Cursor)) {
877 case CXAvailability_Available:
878 break;
879
880 case CXAvailability_Deprecated:
881 printf(format: " (deprecated)");
882 break;
883
884 case CXAvailability_NotAvailable:
885 printf(format: " (unavailable)");
886 break;
887
888 case CXAvailability_NotAccessible:
889 printf(format: " (inaccessible)");
890 break;
891 }
892
893 NumPlatformAvailability
894 = clang_getCursorPlatformAvailability(cursor: Cursor,
895 always_deprecated: &AlwaysDeprecated,
896 deprecated_message: &DeprecatedMessage,
897 always_unavailable: &AlwaysUnavailable,
898 unavailable_message: &UnavailableMessage,
899 availability: PlatformAvailability, availability_size: 2);
900 if (AlwaysUnavailable) {
901 printf(format: " (always unavailable: \"%s\")",
902 clang_getCString(string: UnavailableMessage));
903 } else if (AlwaysDeprecated) {
904 printf(format: " (always deprecated: \"%s\")",
905 clang_getCString(string: DeprecatedMessage));
906 } else {
907 for (I = 0; I != NumPlatformAvailability; ++I) {
908 if (I >= 2)
909 break;
910
911 printf(format: " (%s", clang_getCString(string: PlatformAvailability[I].Platform));
912 if (PlatformAvailability[I].Unavailable)
913 printf(format: ", unavailable");
914 else {
915 printVersion(Prefix: ", introduced=", Version: PlatformAvailability[I].Introduced);
916 printVersion(Prefix: ", deprecated=", Version: PlatformAvailability[I].Deprecated);
917 printVersion(Prefix: ", obsoleted=", Version: PlatformAvailability[I].Obsoleted);
918 }
919 if (clang_getCString(string: PlatformAvailability[I].Message)[0])
920 printf(format: ", message=\"%s\"",
921 clang_getCString(string: PlatformAvailability[I].Message));
922 printf(format: ")");
923 }
924 }
925 for (I = 0; I != NumPlatformAvailability; ++I) {
926 if (I >= 2)
927 break;
928 clang_disposeCXPlatformAvailability(availability: PlatformAvailability + I);
929 }
930
931 clang_disposeString(string: DeprecatedMessage);
932 clang_disposeString(string: UnavailableMessage);
933
934 if (clang_CXXConstructor_isDefaultConstructor(C: Cursor))
935 printf(format: " (default constructor)");
936
937 if (clang_CXXConstructor_isMoveConstructor(C: Cursor))
938 printf(format: " (move constructor)");
939 if (clang_CXXConstructor_isCopyConstructor(C: Cursor))
940 printf(format: " (copy constructor)");
941 if (clang_CXXConstructor_isConvertingConstructor(C: Cursor))
942 printf(format: " (converting constructor)");
943 if (clang_CXXField_isMutable(C: Cursor))
944 printf(format: " (mutable)");
945 if (clang_CXXMethod_isDefaulted(C: Cursor))
946 printf(format: " (defaulted)");
947 if (clang_CXXMethod_isDeleted(C: Cursor))
948 printf(format: " (deleted)");
949 if (clang_CXXMethod_isStatic(C: Cursor))
950 printf(format: " (static)");
951 if (clang_CXXMethod_isVirtual(C: Cursor))
952 printf(format: " (virtual)");
953 if (clang_CXXMethod_isConst(C: Cursor))
954 printf(format: " (const)");
955 if (clang_CXXMethod_isPureVirtual(C: Cursor))
956 printf(format: " (pure)");
957 if (clang_CXXMethod_isCopyAssignmentOperator(C: Cursor))
958 printf(format: " (copy-assignment operator)");
959 if (clang_CXXMethod_isMoveAssignmentOperator(C: Cursor))
960 printf(format: " (move-assignment operator)");
961 if (clang_CXXMethod_isExplicit(C: Cursor))
962 printf(format: " (explicit)");
963 if (clang_CXXRecord_isAbstract(C: Cursor))
964 printf(format: " (abstract)");
965 if (clang_EnumDecl_isScoped(C: Cursor))
966 printf(format: " (scoped)");
967 if (clang_Cursor_isVariadic(C: Cursor))
968 printf(format: " (variadic)");
969 if (clang_Cursor_isObjCOptional(C: Cursor))
970 printf(format: " (@optional)");
971 if (clang_isInvalidDeclaration(Cursor))
972 printf(format: " (invalid)");
973
974 switch (clang_getCursorExceptionSpecificationType(C: Cursor))
975 {
976 case CXCursor_ExceptionSpecificationKind_None:
977 break;
978
979 case CXCursor_ExceptionSpecificationKind_DynamicNone:
980 printf(format: " (noexcept dynamic none)");
981 break;
982
983 case CXCursor_ExceptionSpecificationKind_Dynamic:
984 printf(format: " (noexcept dynamic)");
985 break;
986
987 case CXCursor_ExceptionSpecificationKind_MSAny:
988 printf(format: " (noexcept dynamic any)");
989 break;
990
991 case CXCursor_ExceptionSpecificationKind_BasicNoexcept:
992 printf(format: " (noexcept)");
993 break;
994
995 case CXCursor_ExceptionSpecificationKind_ComputedNoexcept:
996 printf(format: " (computed-noexcept)");
997 break;
998
999 case CXCursor_ExceptionSpecificationKind_Unevaluated:
1000 case CXCursor_ExceptionSpecificationKind_Uninstantiated:
1001 case CXCursor_ExceptionSpecificationKind_Unparsed:
1002 break;
1003 }
1004
1005 {
1006 CXString language;
1007 CXString definedIn;
1008 unsigned generated;
1009 if (clang_Cursor_isExternalSymbol(C: Cursor, language: &language, definedIn: &definedIn,
1010 isGenerated: &generated)) {
1011 printf(format: " (external lang: %s, defined: %s, gen: %d)",
1012 clang_getCString(string: language), clang_getCString(string: definedIn), generated);
1013 clang_disposeString(string: language);
1014 clang_disposeString(string: definedIn);
1015 }
1016 }
1017
1018 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
1019 CXType T =
1020 clang_getCanonicalType(T: clang_getIBOutletCollectionType(Cursor));
1021 CXString S = clang_getTypeKindSpelling(K: T.kind);
1022 printf(format: " [IBOutletCollection=%s]", clang_getCString(string: S));
1023 clang_disposeString(string: S);
1024 }
1025
1026 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
1027 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1028 unsigned isVirtual = clang_isVirtualBase(Cursor);
1029 const char *accessStr = 0;
1030
1031 switch (access) {
1032 case CX_CXXInvalidAccessSpecifier:
1033 accessStr = "invalid"; break;
1034 case CX_CXXPublic:
1035 accessStr = "public"; break;
1036 case CX_CXXProtected:
1037 accessStr = "protected"; break;
1038 case CX_CXXPrivate:
1039 accessStr = "private"; break;
1040 }
1041
1042 printf(format: " [access=%s isVirtual=%s]", accessStr,
1043 isVirtual ? "true" : "false");
1044 }
1045
1046 SpecializationOf = clang_getSpecializedCursorTemplate(C: Cursor);
1047 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
1048 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
1049 CXString Name = clang_getCursorSpelling(SpecializationOf);
1050 clang_getSpellingLocation(location: Loc, file: 0, line: &line, column: &column, offset: 0);
1051 printf(format: " [Specialization of %s:%d:%d]",
1052 clang_getCString(string: Name), line, column);
1053 clang_disposeString(string: Name);
1054
1055 if (Cursor.kind == CXCursor_FunctionDecl
1056 || Cursor.kind == CXCursor_StructDecl
1057 || Cursor.kind == CXCursor_ClassDecl
1058 || Cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
1059 /* Collect the template parameter kinds from the base template. */
1060 int NumTemplateArgs = clang_Cursor_getNumTemplateArguments(C: Cursor);
1061 int I;
1062 if (NumTemplateArgs < 0) {
1063 printf(format: " [no template arg info]");
1064 }
1065 for (I = 0; I < NumTemplateArgs; I++) {
1066 enum CXTemplateArgumentKind TAK =
1067 clang_Cursor_getTemplateArgumentKind(C: Cursor, I);
1068 switch(TAK) {
1069 case CXTemplateArgumentKind_Type:
1070 {
1071 CXType T = clang_Cursor_getTemplateArgumentType(C: Cursor, I);
1072 CXString S = clang_getTypeSpelling(CT: T);
1073 printf(format: " [Template arg %d: kind: %d, type: %s]",
1074 I, TAK, clang_getCString(string: S));
1075 clang_disposeString(string: S);
1076 }
1077 break;
1078 case CXTemplateArgumentKind_Integral:
1079 printf(format: " [Template arg %d: kind: %d, intval: %lld]",
1080 I, TAK, clang_Cursor_getTemplateArgumentValue(C: Cursor, I));
1081 break;
1082 default:
1083 printf(format: " [Template arg %d: kind: %d]\n", I, TAK);
1084 }
1085 }
1086 }
1087 }
1088
1089 clang_getOverriddenCursors(cursor: Cursor, overridden: &overridden, num_overridden: &num_overridden);
1090 if (num_overridden) {
1091 unsigned I;
1092 LineCol lineCols[50];
1093 assert(num_overridden <= 50);
1094 printf(format: " [Overrides ");
1095 for (I = 0; I != num_overridden; ++I) {
1096 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
1097 clang_getSpellingLocation(location: Loc, file: 0, line: &line, column: &column, offset: 0);
1098 lineCols[I].line = line;
1099 lineCols[I].col = column;
1100 }
1101 /* Make the order of the override list deterministic. */
1102 qsort(base: lineCols, nmemb: num_overridden, size: sizeof(LineCol), compar: lineCol_cmp);
1103 for (I = 0; I != num_overridden; ++I) {
1104 if (I)
1105 printf(format: ", ");
1106 printf(format: "@%d:%d", lineCols[I].line, lineCols[I].col);
1107 }
1108 printf(format: "]");
1109 clang_disposeOverriddenCursors(overridden);
1110 }
1111
1112 if (Cursor.kind == CXCursor_InclusionDirective) {
1113 CXFile File = clang_getIncludedFile(cursor: Cursor);
1114 CXString Included = clang_getFileName(SFile: File);
1115 const char *IncludedString = clang_getCString(string: Included);
1116 printf(format: " (%s)", IncludedString ? IncludedString : "(null)");
1117 clang_disposeString(string: Included);
1118
1119 if (clang_isFileMultipleIncludeGuarded(tu: TU, file: File))
1120 printf(format: " [multi-include guarded]");
1121 }
1122
1123 CursorExtent = clang_getCursorExtent(Cursor);
1124 RefNameRange = clang_getCursorReferenceNameRange(C: Cursor,
1125 NameFlags: CXNameRange_WantQualifier
1126 | CXNameRange_WantSinglePiece
1127 | CXNameRange_WantTemplateArgs,
1128 PieceIndex: 0);
1129 if (!clang_equalRanges(range1: CursorExtent, range2: RefNameRange))
1130 PrintRange(R: RefNameRange, str: "SingleRefName");
1131
1132 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
1133 RefNameRange = clang_getCursorReferenceNameRange(C: Cursor,
1134 NameFlags: CXNameRange_WantQualifier
1135 | CXNameRange_WantTemplateArgs,
1136 PieceIndex: RefNameRangeNr);
1137 if (clang_equalRanges(range1: clang_getNullRange(), range2: RefNameRange))
1138 break;
1139 if (!clang_equalRanges(range1: CursorExtent, range2: RefNameRange))
1140 PrintRange(R: RefNameRange, str: "RefName");
1141 }
1142
1143 PrintCursorComments(Cursor, CommentSchemaFile);
1144
1145 {
1146 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(C: Cursor, reserved: 0);
1147 if (PropAttrs != CXObjCPropertyAttr_noattr) {
1148 printf(format: " [");
1149 #define PRINT_PROP_ATTR(A) \
1150 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
1151 PRINT_PROP_ATTR(readonly);
1152 PRINT_PROP_ATTR(getter);
1153 PRINT_PROP_ATTR(assign);
1154 PRINT_PROP_ATTR(readwrite);
1155 PRINT_PROP_ATTR(retain);
1156 PRINT_PROP_ATTR(copy);
1157 PRINT_PROP_ATTR(nonatomic);
1158 PRINT_PROP_ATTR(setter);
1159 PRINT_PROP_ATTR(atomic);
1160 PRINT_PROP_ATTR(weak);
1161 PRINT_PROP_ATTR(strong);
1162 PRINT_PROP_ATTR(unsafe_unretained);
1163 PRINT_PROP_ATTR(class);
1164 printf(format: "]");
1165 }
1166 }
1167
1168 if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
1169 CXString Name = clang_Cursor_getObjCPropertyGetterName(C: Cursor);
1170 CXString Spelling = clang_getCursorSpelling(Cursor);
1171 const char *CName = clang_getCString(string: Name);
1172 const char *CSpelling = clang_getCString(string: Spelling);
1173 if (CName && strcmp(s1: CName, s2: CSpelling)) {
1174 printf(format: " (getter=%s)", CName);
1175 }
1176 clang_disposeString(string: Spelling);
1177 clang_disposeString(string: Name);
1178 }
1179
1180 if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
1181 CXString Name = clang_Cursor_getObjCPropertySetterName(C: Cursor);
1182 CXString Spelling = clang_getCursorSpelling(Cursor);
1183 const char *CName = clang_getCString(string: Name);
1184 const char *CSpelling = clang_getCString(string: Spelling);
1185 char *DefaultSetter = malloc(size: strlen(s: CSpelling) + 5);
1186 sprintf(s: DefaultSetter, format: "set%s:", CSpelling);
1187 DefaultSetter[3] &= ~(1 << 5); /* Make uppercase */
1188 if (CName && strcmp(s1: CName, s2: DefaultSetter)) {
1189 printf(format: " (setter=%s)", CName);
1190 }
1191 free(ptr: DefaultSetter);
1192 clang_disposeString(string: Spelling);
1193 clang_disposeString(string: Name);
1194 }
1195
1196 {
1197 unsigned QT = clang_Cursor_getObjCDeclQualifiers(C: Cursor);
1198 if (QT != CXObjCDeclQualifier_None) {
1199 printf(format: " [");
1200 #define PRINT_OBJC_QUAL(A) \
1201 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
1202 PRINT_OBJC_QUAL(In);
1203 PRINT_OBJC_QUAL(Inout);
1204 PRINT_OBJC_QUAL(Out);
1205 PRINT_OBJC_QUAL(Bycopy);
1206 PRINT_OBJC_QUAL(Byref);
1207 PRINT_OBJC_QUAL(Oneway);
1208 printf(format: "]");
1209 }
1210 }
1211 }
1212}
1213
1214static const char* GetCursorSource(CXCursor Cursor) {
1215 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
1216 CXString source;
1217 CXFile file;
1218 clang_getExpansionLocation(location: Loc, file: &file, line: 0, column: 0, offset: 0);
1219 source = clang_getFileName(SFile: file);
1220 if (!clang_getCString(string: source)) {
1221 clang_disposeString(string: source);
1222 return "<invalid loc>";
1223 }
1224 else {
1225 const char *b = basename(clang_getCString(string: source));
1226 clang_disposeString(string: source);
1227 return b;
1228 }
1229}
1230
1231static CXString createCXString(const char *CS) {
1232 CXString Str;
1233 Str.data = (const void *) CS;
1234 Str.private_flags = 0;
1235 return Str;
1236}
1237
1238/******************************************************************************/
1239/* Callbacks. */
1240/******************************************************************************/
1241
1242typedef void (*PostVisitTU)(CXTranslationUnit);
1243
1244void PrintDiagnostic(CXDiagnostic Diagnostic) {
1245 FILE *out = stderr;
1246 CXFile file;
1247 CXString Msg;
1248 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
1249 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
1250 | CXDiagnostic_DisplayOption;
1251 unsigned i, num_fixits;
1252
1253 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
1254 return;
1255
1256 Msg = clang_formatDiagnostic(Diagnostic, Options: display_opts);
1257 fprintf(stderr, format: "%s\n", clang_getCString(string: Msg));
1258 clang_disposeString(string: Msg);
1259
1260 clang_getSpellingLocation(location: clang_getDiagnosticLocation(Diagnostic),
1261 file: &file, line: 0, column: 0, offset: 0);
1262 if (!file)
1263 return;
1264
1265 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
1266 fprintf(stderr, format: "Number FIX-ITs = %d\n", num_fixits);
1267 for (i = 0; i != num_fixits; ++i) {
1268 CXSourceRange range;
1269 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, FixIt: i, ReplacementRange: &range);
1270 CXSourceLocation start = clang_getRangeStart(range);
1271 CXSourceLocation end = clang_getRangeEnd(range);
1272 unsigned start_line, start_column, end_line, end_column;
1273 CXFile start_file, end_file;
1274 clang_getSpellingLocation(location: start, file: &start_file, line: &start_line,
1275 column: &start_column, offset: 0);
1276 clang_getSpellingLocation(location: end, file: &end_file, line: &end_line, column: &end_column, offset: 0);
1277 if (clang_equalLocations(loc1: start, loc2: end)) {
1278 /* Insertion. */
1279 if (start_file == file)
1280 fprintf(stream: out, format: "FIX-IT: Insert \"%s\" at %d:%d\n",
1281 clang_getCString(string: insertion_text), start_line, start_column);
1282 } else if (strcmp(s1: clang_getCString(string: insertion_text), s2: "") == 0) {
1283 /* Removal. */
1284 if (start_file == file && end_file == file) {
1285 fprintf(stream: out, format: "FIX-IT: Remove ");
1286 PrintExtent(out, begin_line: start_line, begin_column: start_column, end_line, end_column);
1287 fprintf(stream: out, format: "\n");
1288 }
1289 } else {
1290 /* Replacement. */
1291 if (start_file == end_file) {
1292 fprintf(stream: out, format: "FIX-IT: Replace ");
1293 PrintExtent(out, begin_line: start_line, begin_column: start_column, end_line, end_column);
1294 fprintf(stream: out, format: " with \"%s\"\n", clang_getCString(string: insertion_text));
1295 }
1296 }
1297 clang_disposeString(string: insertion_text);
1298 }
1299}
1300
1301void PrintDiagnosticSet(CXDiagnosticSet Set) {
1302 int i = 0, n = clang_getNumDiagnosticsInSet(Diags: Set);
1303 for ( ; i != n ; ++i) {
1304 CXDiagnostic Diag = clang_getDiagnosticInSet(Diags: Set, Index: i);
1305 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(D: Diag);
1306 PrintDiagnostic(Diagnostic: Diag);
1307 if (ChildDiags)
1308 PrintDiagnosticSet(Set: ChildDiags);
1309 }
1310}
1311
1312void PrintDiagnostics(CXTranslationUnit TU) {
1313 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(Unit: TU);
1314 PrintDiagnosticSet(Set: TUSet);
1315 clang_disposeDiagnosticSet(Diags: TUSet);
1316}
1317
1318void PrintMemoryUsage(CXTranslationUnit TU) {
1319 unsigned long total = 0;
1320 unsigned i = 0;
1321 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
1322 fprintf(stderr, format: "Memory usage:\n");
1323 for (i = 0 ; i != usage.numEntries; ++i) {
1324 const char *name = clang_getTUResourceUsageName(kind: usage.entries[i].kind);
1325 unsigned long amount = usage.entries[i].amount;
1326 total += amount;
1327 fprintf(stderr, format: " %s : %ld bytes (%f MBytes)\n", name, amount,
1328 ((double) amount)/(1024*1024));
1329 }
1330 fprintf(stderr, format: " TOTAL = %ld bytes (%f MBytes)\n", total,
1331 ((double) total)/(1024*1024));
1332 clang_disposeCXTUResourceUsage(usage);
1333}
1334
1335/******************************************************************************/
1336/* Logic for testing traversal. */
1337/******************************************************************************/
1338
1339static void PrintCursorExtent(CXCursor C) {
1340 CXSourceRange extent = clang_getCursorExtent(C);
1341 PrintRange(R: extent, str: "Extent");
1342}
1343
1344/* Data used by the visitors. */
1345typedef struct {
1346 CXTranslationUnit TU;
1347 enum CXCursorKind *Filter;
1348 const char *CommentSchemaFile;
1349} VisitorData;
1350
1351
1352enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
1353 CXCursor Parent,
1354 CXClientData ClientData) {
1355 VisitorData *Data = (VisitorData *)ClientData;
1356 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
1357 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
1358 unsigned line, column;
1359 clang_getSpellingLocation(location: Loc, file: 0, line: &line, column: &column, offset: 0);
1360 printf(format: "// %s: %s:%d:%d: ", FileCheckPrefix,
1361 GetCursorSource(Cursor), line, column);
1362 PrintCursor(Cursor, CommentSchemaFile: Data->CommentSchemaFile);
1363 PrintCursorExtent(C: Cursor);
1364 if (clang_isDeclaration(Cursor.kind)) {
1365 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1366 const char *accessStr = 0;
1367
1368 switch (access) {
1369 case CX_CXXInvalidAccessSpecifier: break;
1370 case CX_CXXPublic:
1371 accessStr = "public"; break;
1372 case CX_CXXProtected:
1373 accessStr = "protected"; break;
1374 case CX_CXXPrivate:
1375 accessStr = "private"; break;
1376 }
1377
1378 if (accessStr)
1379 printf(format: " [access=%s]", accessStr);
1380 }
1381 printf(format: "\n");
1382 return CXChildVisit_Recurse;
1383 }
1384
1385 return CXChildVisit_Continue;
1386}
1387
1388static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
1389 CXCursor Parent,
1390 CXClientData ClientData) {
1391 const char *startBuf, *endBuf;
1392 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1393 CXCursor Ref;
1394 VisitorData *Data = (VisitorData *)ClientData;
1395
1396 if (Cursor.kind != CXCursor_FunctionDecl ||
1397 !clang_isCursorDefinition(Cursor))
1398 return CXChildVisit_Continue;
1399
1400 clang_getDefinitionSpellingAndExtent(Cursor, startBuf: &startBuf, endBuf: &endBuf,
1401 startLine: &startLine, startColumn: &startColumn,
1402 endLine: &endLine, endColumn: &endColumn);
1403 /* Probe the entire body, looking for both decls and refs. */
1404 curLine = startLine;
1405 curColumn = startColumn;
1406
1407 while (startBuf < endBuf) {
1408 CXSourceLocation Loc;
1409 CXFile file;
1410 CXString source;
1411
1412 if (*startBuf == '\n') {
1413 startBuf++;
1414 curLine++;
1415 curColumn = 1;
1416 } else if (*startBuf != '\t')
1417 curColumn++;
1418
1419 Loc = clang_getCursorLocation(Cursor);
1420 clang_getSpellingLocation(location: Loc, file: &file, line: 0, column: 0, offset: 0);
1421
1422 source = clang_getFileName(SFile: file);
1423 if (clang_getCString(string: source)) {
1424 CXSourceLocation RefLoc
1425 = clang_getLocation(tu: Data->TU, file, line: curLine, column: curColumn);
1426 Ref = clang_getCursor(Data->TU, RefLoc);
1427 if (Ref.kind == CXCursor_NoDeclFound) {
1428 /* Nothing found here; that's fine. */
1429 } else if (Ref.kind != CXCursor_FunctionDecl) {
1430 printf(format: "// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Cursor: Ref),
1431 curLine, curColumn);
1432 PrintCursor(Cursor: Ref, CommentSchemaFile: Data->CommentSchemaFile);
1433 printf(format: "\n");
1434 }
1435 }
1436 clang_disposeString(string: source);
1437 startBuf++;
1438 }
1439
1440 return CXChildVisit_Continue;
1441}
1442
1443/******************************************************************************/
1444/* USR testing. */
1445/******************************************************************************/
1446
1447enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1448 CXClientData ClientData) {
1449 VisitorData *Data = (VisitorData *)ClientData;
1450 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
1451 CXString USR = clang_getCursorUSR(C);
1452 const char *cstr = clang_getCString(string: USR);
1453 if (!cstr || cstr[0] == '\0') {
1454 clang_disposeString(string: USR);
1455 return CXChildVisit_Recurse;
1456 }
1457 printf(format: "// %s: %s %s", FileCheckPrefix, GetCursorSource(Cursor: C), cstr);
1458
1459 PrintCursorExtent(C);
1460 printf(format: "\n");
1461 clang_disposeString(string: USR);
1462
1463 return CXChildVisit_Recurse;
1464 }
1465
1466 return CXChildVisit_Continue;
1467}
1468
1469/******************************************************************************/
1470/* Inclusion stack testing. */
1471/******************************************************************************/
1472
1473void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1474 unsigned includeStackLen, CXClientData data) {
1475
1476 unsigned i;
1477 CXString fname;
1478
1479 fname = clang_getFileName(SFile: includedFile);
1480 printf(format: "file: %s\nincluded by:\n", clang_getCString(string: fname));
1481 clang_disposeString(string: fname);
1482
1483 for (i = 0; i < includeStackLen; ++i) {
1484 CXFile includingFile;
1485 unsigned line, column;
1486 clang_getSpellingLocation(location: includeStack[i], file: &includingFile, line: &line,
1487 column: &column, offset: 0);
1488 fname = clang_getFileName(SFile: includingFile);
1489 printf(format: " %s:%d:%d\n", clang_getCString(string: fname), line, column);
1490 clang_disposeString(string: fname);
1491 }
1492 printf(format: "\n");
1493}
1494
1495void PrintInclusionStack(CXTranslationUnit TU) {
1496 clang_getInclusions(tu: TU, visitor: InclusionVisitor, NULL);
1497}
1498
1499/******************************************************************************/
1500/* Linkage testing. */
1501/******************************************************************************/
1502
1503static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1504 CXClientData d) {
1505 const char *linkage = 0;
1506
1507 if (clang_isInvalid(clang_getCursorKind(cursor)))
1508 return CXChildVisit_Recurse;
1509
1510 switch (clang_getCursorLinkage(cursor)) {
1511 case CXLinkage_Invalid: break;
1512 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1513 case CXLinkage_Internal: linkage = "Internal"; break;
1514 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1515 case CXLinkage_External: linkage = "External"; break;
1516 }
1517
1518 if (linkage) {
1519 PrintCursor(Cursor: cursor, NULL);
1520 printf(format: "linkage=%s\n", linkage);
1521 }
1522
1523 return CXChildVisit_Recurse;
1524}
1525
1526/******************************************************************************/
1527/* Visibility testing. */
1528/******************************************************************************/
1529
1530static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1531 CXClientData d) {
1532 const char *visibility = 0;
1533
1534 if (clang_isInvalid(clang_getCursorKind(cursor)))
1535 return CXChildVisit_Recurse;
1536
1537 switch (clang_getCursorVisibility(cursor)) {
1538 case CXVisibility_Invalid: break;
1539 case CXVisibility_Hidden: visibility = "Hidden"; break;
1540 case CXVisibility_Protected: visibility = "Protected"; break;
1541 case CXVisibility_Default: visibility = "Default"; break;
1542 }
1543
1544 if (visibility) {
1545 PrintCursor(Cursor: cursor, NULL);
1546 printf(format: "visibility=%s\n", visibility);
1547 }
1548
1549 return CXChildVisit_Recurse;
1550}
1551
1552/******************************************************************************/
1553/* Typekind testing. */
1554/******************************************************************************/
1555
1556static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1557 CXString TypeSpelling, TypeKindSpelling;
1558
1559 TypeSpelling = clang_getTypeSpelling(CT: T);
1560 TypeKindSpelling = clang_getTypeKindSpelling(K: T.kind);
1561 printf(format: Format,
1562 clang_getCString(string: TypeSpelling),
1563 clang_getCString(string: TypeKindSpelling));
1564 clang_disposeString(string: TypeSpelling);
1565 clang_disposeString(string: TypeKindSpelling);
1566}
1567
1568static enum CXVisitorResult FieldVisitor(CXCursor C,
1569 CXClientData client_data) {
1570 (*(int *) client_data)+=1;
1571 return CXVisit_Continue;
1572}
1573
1574static void PrintTypeTemplateArgs(CXType T, const char *Format) {
1575 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1576 if (NumTArgs != -1 && NumTArgs != 0) {
1577 int i;
1578 CXType TArg;
1579 printf(format: Format, NumTArgs);
1580 for (i = 0; i < NumTArgs; ++i) {
1581 TArg = clang_Type_getTemplateArgumentAsType(T, i);
1582 if (TArg.kind != CXType_Invalid) {
1583 PrintTypeAndTypeKind(T: TArg, Format: " [type=%s] [typekind=%s]");
1584 }
1585 }
1586 /* Ensure that the returned type is invalid when indexing off-by-one. */
1587 TArg = clang_Type_getTemplateArgumentAsType(T, i);
1588 assert(TArg.kind == CXType_Invalid);
1589 printf(format: "]");
1590 }
1591}
1592
1593static void PrintNullabilityKind(CXType T, const char *Format) {
1594 enum CXTypeNullabilityKind N = clang_Type_getNullability(T);
1595
1596 const char *nullability = 0;
1597 switch (N) {
1598 case CXTypeNullability_NonNull:
1599 nullability = "nonnull";
1600 break;
1601 case CXTypeNullability_Nullable:
1602 nullability = "nullable";
1603 break;
1604 case CXTypeNullability_NullableResult:
1605 nullability = "nullable_result";
1606 break;
1607 case CXTypeNullability_Unspecified:
1608 nullability = "unspecified";
1609 break;
1610 case CXTypeNullability_Invalid:
1611 break;
1612 }
1613
1614 if (nullability) {
1615 printf(format: Format, nullability);
1616 }
1617}
1618
1619static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1620 CXClientData d) {
1621 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
1622 CXType T = clang_getCursorType(C: cursor);
1623 CXType PT = clang_getPointeeType(T);
1624 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
1625 PrintCursor(Cursor: cursor, NULL);
1626 PrintTypeAndTypeKind(T, Format: " [type=%s] [typekind=%s]");
1627 PrintNullabilityKind(T, Format: " [nullability=%s]");
1628 if (clang_isConstQualifiedType(T))
1629 printf(format: " const");
1630 if (clang_isVolatileQualifiedType(T))
1631 printf(format: " volatile");
1632 if (clang_isRestrictQualifiedType(T))
1633 printf(format: " restrict");
1634 if (RQ == CXRefQualifier_LValue)
1635 printf(format: " lvalue-ref-qualifier");
1636 if (RQ == CXRefQualifier_RValue)
1637 printf(format: " rvalue-ref-qualifier");
1638 /* Print the template argument types if they exist. */
1639 PrintTypeTemplateArgs(T, Format: " [templateargs/%d=");
1640 /* Print the canonical type if it is different. */
1641 {
1642 CXType CT = clang_getCanonicalType(T);
1643 if (!clang_equalTypes(A: T, B: CT)) {
1644 PrintTypeAndTypeKind(T: CT, Format: " [canonicaltype=%s] [canonicaltypekind=%s]");
1645 PrintTypeTemplateArgs(T: CT, Format: " [canonicaltemplateargs/%d=");
1646 }
1647 }
1648 /* Print the value type if it exists. */
1649 {
1650 CXType VT = clang_Type_getValueType(CT: T);
1651 if (VT.kind != CXType_Invalid)
1652 PrintTypeAndTypeKind(T: VT, Format: " [valuetype=%s] [valuetypekind=%s]");
1653 }
1654 /* Print the modified type if it exists. */
1655 {
1656 CXType MT = clang_Type_getModifiedType(T);
1657 if (MT.kind != CXType_Invalid) {
1658 PrintTypeAndTypeKind(T: MT, Format: " [modifiedtype=%s] [modifiedtypekind=%s]");
1659 }
1660 }
1661 /* Print the return type if it exists. */
1662 {
1663 CXType RT = clang_getCursorResultType(C: cursor);
1664 if (RT.kind != CXType_Invalid) {
1665 PrintTypeAndTypeKind(T: RT, Format: " [resulttype=%s] [resulttypekind=%s]");
1666 }
1667 PrintNullabilityKind(T: RT, Format: " [resultnullability=%s]");
1668 }
1669 /* Print the argument types if they exist. */
1670 {
1671 int NumArgs = clang_Cursor_getNumArguments(C: cursor);
1672 if (NumArgs != -1 && NumArgs != 0) {
1673 int i;
1674 printf(format: " [args=");
1675 for (i = 0; i < NumArgs; ++i) {
1676 CXType T = clang_getCursorType(C: clang_Cursor_getArgument(C: cursor, i));
1677 if (T.kind != CXType_Invalid) {
1678 PrintTypeAndTypeKind(T, Format: " [%s] [%s]");
1679 PrintNullabilityKind(T, Format: " [%s]");
1680 }
1681 }
1682 printf(format: "]");
1683 }
1684 }
1685 /* Print ObjC base types, type arguments, and protocol list if available. */
1686 {
1687 CXType BT = clang_Type_getObjCObjectBaseType(T: PT);
1688 if (BT.kind != CXType_Invalid) {
1689 PrintTypeAndTypeKind(T: BT, Format: " [basetype=%s] [basekind=%s]");
1690 }
1691 }
1692 {
1693 unsigned NumTypeArgs = clang_Type_getNumObjCTypeArgs(T: PT);
1694 if (NumTypeArgs > 0) {
1695 unsigned i;
1696 printf(format: " [typeargs=");
1697 for (i = 0; i < NumTypeArgs; ++i) {
1698 CXType TA = clang_Type_getObjCTypeArg(T: PT, i);
1699 if (TA.kind != CXType_Invalid) {
1700 PrintTypeAndTypeKind(T: TA, Format: " [%s] [%s]");
1701 }
1702 }
1703 printf(format: "]");
1704 }
1705 }
1706 {
1707 unsigned NumProtocols = clang_Type_getNumObjCProtocolRefs(T: PT);
1708 if (NumProtocols > 0) {
1709 unsigned i;
1710 printf(format: " [protocols=");
1711 for (i = 0; i < NumProtocols; ++i) {
1712 CXCursor P = clang_Type_getObjCProtocolDecl(T: PT, i);
1713 if (!clang_isInvalid(clang_getCursorKind(P))) {
1714 PrintCursor(Cursor: P, NULL);
1715 }
1716 }
1717 printf(format: "]");
1718 }
1719 }
1720 /* Print if this is a non-POD type. */
1721 printf(format: " [isPOD=%d]", clang_isPODType(T));
1722 /* Print the pointee type. */
1723 {
1724 if (PT.kind != CXType_Invalid) {
1725 PrintTypeAndTypeKind(T: PT, Format: " [pointeetype=%s] [pointeekind=%s]");
1726 }
1727 }
1728 /* Print the number of fields if they exist. */
1729 {
1730 int numFields = 0;
1731 if (clang_Type_visitFields(T, visitor: FieldVisitor, client_data: &numFields)){
1732 if (numFields != 0) {
1733 printf(format: " [nbFields=%d]", numFields);
1734 }
1735 }
1736 }
1737
1738 /* Print if it is an anonymous record or namespace. */
1739 {
1740 unsigned isAnon = clang_Cursor_isAnonymous(C: cursor);
1741 if (isAnon != 0) {
1742 printf(format: " [isAnon=%d]", isAnon);
1743 }
1744 }
1745
1746 /* Print if it is an anonymous record decl */
1747 {
1748 unsigned isAnonRecDecl = clang_Cursor_isAnonymousRecordDecl(C: cursor);
1749 printf(format: " [isAnonRecDecl=%d]", isAnonRecDecl);
1750 }
1751
1752 /* Print if it is an inline namespace decl */
1753 {
1754 unsigned isInlineNamespace = clang_Cursor_isInlineNamespace(C: cursor);
1755 if (isInlineNamespace != 0)
1756 printf(format: " [isInlineNamespace=%d]", isInlineNamespace);
1757 }
1758
1759 printf(format: "\n");
1760 }
1761 return CXChildVisit_Recurse;
1762}
1763
1764static void PrintSingleTypeSize(CXType T, const char *TypeKindFormat,
1765 const char *SizeFormat,
1766 const char *AlignFormat) {
1767 PrintTypeAndTypeKind(T, Format: TypeKindFormat);
1768 /* Print the type sizeof if applicable. */
1769 {
1770 long long Size = clang_Type_getSizeOf(T);
1771 if (Size >= 0 || Size < -1 ) {
1772 printf(format: SizeFormat, Size);
1773 }
1774 }
1775 /* Print the type alignof if applicable. */
1776 {
1777 long long Align = clang_Type_getAlignOf(T);
1778 if (Align >= 0 || Align < -1) {
1779 printf(format: AlignFormat, Align);
1780 }
1781 }
1782
1783 /* Print the return type if it exists. */
1784 {
1785 CXType RT = clang_getResultType(T);
1786 if (RT.kind != CXType_Invalid)
1787 PrintSingleTypeSize(T: RT, TypeKindFormat: " [resulttype=%s] [resulttypekind=%s]",
1788 SizeFormat: " [resultsizeof=%lld]", AlignFormat: " [resultalignof=%lld]");
1789 }
1790}
1791
1792static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1793 CXClientData d) {
1794 CXType T;
1795 enum CXCursorKind K = clang_getCursorKind(cursor);
1796 if (clang_isInvalid(K))
1797 return CXChildVisit_Recurse;
1798 T = clang_getCursorType(C: cursor);
1799 PrintCursor(Cursor: cursor, NULL);
1800 PrintSingleTypeSize(T, TypeKindFormat: " [type=%s] [typekind=%s]", SizeFormat: " [sizeof=%lld]",
1801 AlignFormat: " [alignof=%lld]");
1802 /* Print the record field offset if applicable. */
1803 {
1804 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1805 const char *FieldName = clang_getCString(string: FieldSpelling);
1806 /* recurse to get the first parent record that is not anonymous. */
1807 unsigned RecordIsAnonymous = 0;
1808 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
1809 CXCursor Record;
1810 CXCursor Parent = p;
1811 do {
1812 Record = Parent;
1813 Parent = clang_getCursorSemanticParent(cursor: Record);
1814 RecordIsAnonymous = clang_Cursor_isAnonymous(C: Record);
1815 /* Recurse as long as the parent is a CXType_Record and the Record
1816 is anonymous */
1817 } while ( clang_getCursorType(C: Parent).kind == CXType_Record &&
1818 RecordIsAnonymous > 0);
1819 {
1820 long long Offset = clang_Type_getOffsetOf(T: clang_getCursorType(C: Record),
1821 S: FieldName);
1822 long long Offset2 = clang_Cursor_getOffsetOfField(C: cursor);
1823 if (Offset == Offset2){
1824 printf(format: " [offsetof=%lld]", Offset);
1825 } else {
1826 /* Offsets will be different in anonymous records. */
1827 printf(format: " [offsetof=%lld/%lld]", Offset, Offset2);
1828 }
1829 }
1830 }
1831 clang_disposeString(string: FieldSpelling);
1832 }
1833 /* Print if its a bitfield */
1834 {
1835 int IsBitfield = clang_Cursor_isBitField(C: cursor);
1836 if (IsBitfield)
1837 printf(format: " [BitFieldSize=%d]", clang_getFieldDeclBitWidth(C: cursor));
1838 }
1839
1840 printf(format: "\n");
1841
1842 return CXChildVisit_Recurse;
1843}
1844
1845/******************************************************************************/
1846/* Mangling testing. */
1847/******************************************************************************/
1848
1849static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1850 CXClientData d) {
1851 CXString MangledName;
1852 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1853 return CXChildVisit_Recurse;
1854 if (clang_getCursorKind(cursor) == CXCursor_LinkageSpec)
1855 return CXChildVisit_Recurse;
1856 PrintCursor(Cursor: cursor, NULL);
1857 MangledName = clang_Cursor_getMangling(cursor);
1858 printf(format: " [mangled=%s]\n", clang_getCString(string: MangledName));
1859 clang_disposeString(string: MangledName);
1860 return CXChildVisit_Continue;
1861}
1862
1863static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1864 CXClientData d) {
1865 unsigned I, E;
1866 CXStringSet *Manglings = NULL;
1867 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1868 return CXChildVisit_Recurse;
1869 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1870 return CXChildVisit_Recurse;
1871 if (clang_getCursorKind(cursor) == CXCursor_LinkageSpec)
1872 return CXChildVisit_Recurse;
1873 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1874 return CXChildVisit_Continue;
1875 PrintCursor(Cursor: cursor, NULL);
1876 Manglings = clang_Cursor_getCXXManglings(cursor);
1877 if (Manglings) {
1878 for (I = 0, E = Manglings->Count; I < E; ++I)
1879 printf(format: " [mangled=%s]", clang_getCString(string: Manglings->Strings[I]));
1880 clang_disposeStringSet(set: Manglings);
1881 printf(format: "\n");
1882 }
1883 Manglings = clang_Cursor_getObjCManglings(cursor);
1884 if (Manglings) {
1885 for (I = 0, E = Manglings->Count; I < E; ++I)
1886 printf(format: " [mangled=%s]", clang_getCString(string: Manglings->Strings[I]));
1887 clang_disposeStringSet(set: Manglings);
1888 printf(format: "\n");
1889 }
1890 return CXChildVisit_Recurse;
1891}
1892
1893static enum CXChildVisitResult
1894PrintSingleSymbolSGFs(CXCursor cursor, CXCursor parent, CXClientData data) {
1895 CXString SGFData = clang_getSymbolGraphForCursor(cursor);
1896 const char *SGF = clang_getCString(string: SGFData);
1897 if (SGF)
1898 printf(format: "%s\n", SGF);
1899
1900 clang_disposeString(string: SGFData);
1901
1902 return CXChildVisit_Recurse;
1903}
1904
1905/******************************************************************************/
1906/* Bitwidth testing. */
1907/******************************************************************************/
1908
1909static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1910 CXClientData d) {
1911 int Bitwidth;
1912 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1913 return CXChildVisit_Recurse;
1914
1915 Bitwidth = clang_getFieldDeclBitWidth(C: cursor);
1916 if (Bitwidth >= 0) {
1917 PrintCursor(Cursor: cursor, NULL);
1918 printf(format: " bitwidth=%d\n", Bitwidth);
1919 }
1920
1921 return CXChildVisit_Recurse;
1922}
1923
1924/******************************************************************************/
1925/* Type declaration testing */
1926/******************************************************************************/
1927
1928static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1929 CXClientData d) {
1930 CXCursor typeDeclaration = clang_getTypeDeclaration(T: clang_getCursorType(C: cursor));
1931
1932 if (clang_isDeclaration(typeDeclaration.kind)) {
1933 PrintCursor(Cursor: cursor, NULL);
1934 PrintTypeAndTypeKind(T: clang_getCursorType(C: typeDeclaration), Format: " [typedeclaration=%s] [typekind=%s]\n");
1935 }
1936
1937 return CXChildVisit_Recurse;
1938}
1939
1940/******************************************************************************/
1941/* Declaration attributes testing */
1942/******************************************************************************/
1943
1944static enum CXChildVisitResult PrintDeclAttributes(CXCursor cursor, CXCursor p,
1945 CXClientData d) {
1946 if (clang_isDeclaration(cursor.kind)) {
1947 printf(format: "\n");
1948 PrintCursor(Cursor: cursor, NULL);
1949 return CXChildVisit_Recurse;
1950 } else if (clang_isAttribute(cursor.kind)) {
1951 printf(format: " ");
1952 PrintCursor(Cursor: cursor, NULL);
1953 }
1954 return CXChildVisit_Continue;
1955}
1956
1957/******************************************************************************/
1958/* Target information testing. */
1959/******************************************************************************/
1960
1961static int print_target_info(int argc, const char **argv) {
1962 CXIndex Idx;
1963 CXTranslationUnit TU;
1964 CXTargetInfo TargetInfo;
1965 CXString Triple;
1966 const char *FileName;
1967 enum CXErrorCode Err;
1968 int PointerWidth;
1969
1970 if (argc == 0) {
1971 fprintf(stderr, format: "No filename specified\n");
1972 return 1;
1973 }
1974
1975 FileName = argv[1];
1976
1977 Idx = clang_createIndex(excludeDeclarationsFromPCH: 0, displayDiagnostics: 1);
1978 Err = clang_parseTranslationUnit2(CIdx: Idx, source_filename: FileName, command_line_args: argv, num_command_line_args: argc, NULL, num_unsaved_files: 0,
1979 options: getDefaultParsingOptions(), out_TU: &TU);
1980 if (Err != CXError_Success) {
1981 fprintf(stderr, format: "Couldn't parse translation unit!\n");
1982 describeLibclangFailure(Err);
1983 clang_disposeIndex(index: Idx);
1984 return 1;
1985 }
1986
1987 TargetInfo = clang_getTranslationUnitTargetInfo(CTUnit: TU);
1988
1989 Triple = clang_TargetInfo_getTriple(Info: TargetInfo);
1990 printf(format: "TargetTriple: %s\n", clang_getCString(string: Triple));
1991 clang_disposeString(string: Triple);
1992
1993 PointerWidth = clang_TargetInfo_getPointerWidth(Info: TargetInfo);
1994 printf(format: "PointerWidth: %d\n", PointerWidth);
1995
1996 clang_TargetInfo_dispose(Info: TargetInfo);
1997 clang_disposeTranslationUnit(TU);
1998 clang_disposeIndex(index: Idx);
1999 return 0;
2000}
2001
2002/******************************************************************************/
2003/* Loading ASTs/source. */
2004/******************************************************************************/
2005
2006static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
2007 const char *filter, const char *prefix,
2008 CXCursorVisitor Visitor,
2009 PostVisitTU PV,
2010 const char *CommentSchemaFile) {
2011
2012 if (prefix)
2013 FileCheckPrefix = prefix;
2014
2015 if (Visitor) {
2016 enum CXCursorKind K = CXCursor_NotImplemented;
2017 enum CXCursorKind *ck = &K;
2018 VisitorData Data;
2019
2020 /* Perform some simple filtering. */
2021 if (!strcmp(s1: filter, s2: "all") || !strcmp(s1: filter, s2: "local")) ck = NULL;
2022 else if (!strcmp(s1: filter, s2: "all-display") ||
2023 !strcmp(s1: filter, s2: "local-display")) {
2024 ck = NULL;
2025 wanted_display_type = DisplayType_DisplayName;
2026 }
2027 else if (!strcmp(s1: filter, s2: "all-pretty") ||
2028 !strcmp(s1: filter, s2: "local-pretty")) {
2029 ck = NULL;
2030 wanted_display_type = DisplayType_Pretty;
2031 }
2032 else if (!strcmp(s1: filter, s2: "none")) K = (enum CXCursorKind) ~0;
2033 else if (!strcmp(s1: filter, s2: "category")) K = CXCursor_ObjCCategoryDecl;
2034 else if (!strcmp(s1: filter, s2: "interface")) K = CXCursor_ObjCInterfaceDecl;
2035 else if (!strcmp(s1: filter, s2: "protocol")) K = CXCursor_ObjCProtocolDecl;
2036 else if (!strcmp(s1: filter, s2: "function")) K = CXCursor_FunctionDecl;
2037 else if (!strcmp(s1: filter, s2: "typedef")) K = CXCursor_TypedefDecl;
2038 else if (!strcmp(s1: filter, s2: "scan-function")) Visitor = FunctionScanVisitor;
2039 else {
2040 fprintf(stderr, format: "Unknown filter for -test-load-tu: %s\n", filter);
2041 return 1;
2042 }
2043
2044 Data.TU = TU;
2045 Data.Filter = ck;
2046 Data.CommentSchemaFile = CommentSchemaFile;
2047 clang_visitChildren(parent: clang_getTranslationUnitCursor(TU), visitor: Visitor, client_data: &Data);
2048 }
2049
2050 if (PV)
2051 PV(TU);
2052
2053 PrintDiagnostics(TU);
2054 if (checkForErrors(TU) != 0) {
2055 clang_disposeTranslationUnit(TU);
2056 return -1;
2057 }
2058
2059 clang_disposeTranslationUnit(TU);
2060 return 0;
2061}
2062
2063int perform_test_load_tu(const char *file, const char *filter,
2064 const char *prefix, CXCursorVisitor Visitor,
2065 PostVisitTU PV) {
2066 CXIndex Idx;
2067 CXTranslationUnit TU;
2068 int result;
2069 Idx = clang_createIndex(/* excludeDeclsFromPCH */
2070 excludeDeclarationsFromPCH: !strcmp(s1: filter, s2: "local") ? 1 : 0,
2071 /* displayDiagnostics=*/1);
2072
2073 if (!CreateTranslationUnit(Idx, file, TU: &TU)) {
2074 clang_disposeIndex(index: Idx);
2075 return 1;
2076 }
2077
2078 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
2079 clang_disposeIndex(index: Idx);
2080 return result;
2081}
2082
2083int perform_test_load_source(int argc, const char **argv,
2084 const char *filter, CXCursorVisitor Visitor,
2085 PostVisitTU PV) {
2086 CXIndex Idx;
2087 CXTranslationUnit TU;
2088 const char *CommentSchemaFile;
2089 struct CXUnsavedFile *unsaved_files = 0;
2090 int num_unsaved_files = 0;
2091 enum CXErrorCode Err;
2092 int result;
2093 unsigned Repeats = 0;
2094 unsigned I;
2095
2096 Idx =
2097 createIndexWithInvocationEmissionPath(/* excludeDeclsFromPCH */
2098 ExcludeDeclarationsFromPCH: (!strcmp(s1: filter, s2: "local") ||
2099 !strcmp(s1: filter, s2: "local-display") ||
2100 !strcmp(s1: filter, s2: "local-pretty"))
2101 ? 1
2102 : 0,
2103 /* displayDiagnostics=*/DisplayDiagnostics: 1);
2104 if (!Idx)
2105 return -1;
2106
2107 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
2108 argc--;
2109 argv++;
2110 }
2111
2112 if (parse_remapped_files(argc, argv, start_arg: 0, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
2113 clang_disposeIndex(index: Idx);
2114 return -1;
2115 }
2116
2117 if (getenv(name: "CINDEXTEST_EDITING"))
2118 Repeats = 5;
2119
2120 Err = clang_parseTranslationUnit2(CIdx: Idx, source_filename: 0,
2121 command_line_args: argv + num_unsaved_files,
2122 num_command_line_args: argc - num_unsaved_files,
2123 unsaved_files, num_unsaved_files,
2124 options: getDefaultParsingOptions(), out_TU: &TU);
2125 if (Err != CXError_Success) {
2126 fprintf(stderr, format: "Unable to load translation unit!\n");
2127 describeLibclangFailure(Err);
2128 free_remapped_files(unsaved_files, num_unsaved_files);
2129 clang_disposeIndex(index: Idx);
2130 return 1;
2131 }
2132
2133 for (I = 0; I != Repeats; ++I) {
2134 if (checkForErrors(TU) != 0)
2135 return -1;
2136
2137 if (Repeats > 1) {
2138 clang_suspendTranslationUnit(TU);
2139
2140 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2141 options: clang_defaultReparseOptions(TU));
2142 if (Err != CXError_Success) {
2143 describeLibclangFailure(Err);
2144 free_remapped_files(unsaved_files, num_unsaved_files);
2145 clang_disposeIndex(index: Idx);
2146 return 1;
2147 }
2148 }
2149 }
2150
2151 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
2152 CommentSchemaFile);
2153 free_remapped_files(unsaved_files, num_unsaved_files);
2154 clang_disposeIndex(index: Idx);
2155 return result;
2156}
2157
2158int perform_test_reparse_source(int argc, const char **argv, int trials,
2159 const char *filter, CXCursorVisitor Visitor,
2160 PostVisitTU PV) {
2161 CXIndex Idx;
2162 CXTranslationUnit TU;
2163 struct CXUnsavedFile *unsaved_files = 0;
2164 int num_unsaved_files = 0;
2165 int compiler_arg_idx = 0;
2166 enum CXErrorCode Err;
2167 int result, i;
2168 int trial;
2169 int execute_after_trial = 0;
2170 const char *execute_command = NULL;
2171 int remap_after_trial = 0;
2172 char *endptr = 0;
2173
2174 Idx = clang_createIndex(/* excludeDeclsFromPCH */
2175 excludeDeclarationsFromPCH: !strcmp(s1: filter, s2: "local") ? 1 : 0,
2176 /* displayDiagnostics=*/1);
2177
2178 if (parse_remapped_files(argc, argv, start_arg: 0, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
2179 clang_disposeIndex(index: Idx);
2180 return -1;
2181 }
2182
2183 for (i = 0; i < argc; ++i) {
2184 if (strcmp(s1: argv[i], s2: "--") == 0)
2185 break;
2186 }
2187 if (i < argc)
2188 compiler_arg_idx = i+1;
2189 if (num_unsaved_files > compiler_arg_idx)
2190 compiler_arg_idx = num_unsaved_files;
2191
2192 /* Load the initial translation unit -- we do this without honoring remapped
2193 * files, so that we have a way to test results after changing the source. */
2194 Err = clang_parseTranslationUnit2(CIdx: Idx, source_filename: 0,
2195 command_line_args: argv + compiler_arg_idx,
2196 num_command_line_args: argc - compiler_arg_idx,
2197 unsaved_files: 0, num_unsaved_files: 0, options: getDefaultParsingOptions(), out_TU: &TU);
2198 if (Err != CXError_Success) {
2199 fprintf(stderr, format: "Unable to load translation unit!\n");
2200 describeLibclangFailure(Err);
2201 free_remapped_files(unsaved_files, num_unsaved_files);
2202 clang_disposeIndex(index: Idx);
2203 return 1;
2204 }
2205
2206 if (checkForErrors(TU) != 0)
2207 return -1;
2208
2209 if (getenv(name: "CINDEXTEST_EXECUTE_COMMAND")) {
2210 execute_command = getenv(name: "CINDEXTEST_EXECUTE_COMMAND");
2211 }
2212 if (getenv(name: "CINDEXTEST_EXECUTE_AFTER_TRIAL")) {
2213 execute_after_trial =
2214 strtol(nptr: getenv(name: "CINDEXTEST_EXECUTE_AFTER_TRIAL"), endptr: &endptr, base: 10);
2215 }
2216
2217 if (getenv(name: "CINDEXTEST_REMAP_AFTER_TRIAL")) {
2218 remap_after_trial =
2219 strtol(nptr: getenv(name: "CINDEXTEST_REMAP_AFTER_TRIAL"), endptr: &endptr, base: 10);
2220 }
2221
2222 for (trial = 0; trial < trials; ++trial) {
2223 if (execute_command && trial == execute_after_trial) {
2224 result = indextest_perform_shell_execution(command_line: execute_command);
2225 if (result != 0)
2226 return result;
2227 }
2228
2229 free_remapped_files(unsaved_files, num_unsaved_files);
2230 if (parse_remapped_files_with_try(try_idx: trial, argc, argv, start_arg: 0,
2231 unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
2232 clang_disposeTranslationUnit(TU);
2233 clang_disposeIndex(index: Idx);
2234 return -1;
2235 }
2236
2237 Err = clang_reparseTranslationUnit(
2238 TU,
2239 num_unsaved_files: trial >= remap_after_trial ? num_unsaved_files : 0,
2240 unsaved_files: trial >= remap_after_trial ? unsaved_files : 0,
2241 options: clang_defaultReparseOptions(TU));
2242 if (Err != CXError_Success) {
2243 fprintf(stderr, format: "Unable to reparse translation unit!\n");
2244 describeLibclangFailure(Err);
2245 clang_disposeTranslationUnit(TU);
2246 free_remapped_files(unsaved_files, num_unsaved_files);
2247 clang_disposeIndex(index: Idx);
2248 return -1;
2249 }
2250
2251 if (checkForErrors(TU) != 0)
2252 return -1;
2253 }
2254
2255 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
2256
2257 free_remapped_files(unsaved_files, num_unsaved_files);
2258 clang_disposeIndex(index: Idx);
2259 return result;
2260}
2261
2262static int perform_single_file_parse(const char *filename) {
2263 CXIndex Idx;
2264 CXTranslationUnit TU;
2265 enum CXErrorCode Err;
2266 int result;
2267
2268 Idx = clang_createIndex(/* excludeDeclsFromPCH */excludeDeclarationsFromPCH: 1,
2269 /* displayDiagnostics=*/1);
2270
2271 Err = clang_parseTranslationUnit2(CIdx: Idx, source_filename: filename,
2272 /*command_line_args=*/NULL,
2273 /*num_command_line_args=*/0,
2274 /*unsaved_files=*/NULL,
2275 /*num_unsaved_files=*/0,
2276 options: CXTranslationUnit_SingleFileParse, out_TU: &TU);
2277 if (Err != CXError_Success) {
2278 fprintf(stderr, format: "Unable to load translation unit!\n");
2279 describeLibclangFailure(Err);
2280 clang_disposeIndex(index: Idx);
2281 return 1;
2282 }
2283
2284 result = perform_test_load(Idx, TU, /*filter=*/"all", /*prefix=*/NULL, Visitor: FilteredPrintingVisitor, /*PostVisit=*/NULL,
2285 /*CommentSchemaFile=*/NULL);
2286 clang_disposeIndex(index: Idx);
2287 return result;
2288}
2289
2290static int perform_file_retain_excluded_cb(const char *filename) {
2291 CXIndex Idx;
2292 CXTranslationUnit TU;
2293 enum CXErrorCode Err;
2294 int result;
2295
2296 Idx = clang_createIndex(/* excludeDeclsFromPCH */excludeDeclarationsFromPCH: 1,
2297 /* displayDiagnostics=*/1);
2298
2299 Err = clang_parseTranslationUnit2(CIdx: Idx, source_filename: filename,
2300 /*command_line_args=*/NULL,
2301 /*num_command_line_args=*/0,
2302 /*unsaved_files=*/NULL,
2303 /*num_unsaved_files=*/0,
2304 options: CXTranslationUnit_RetainExcludedConditionalBlocks, out_TU: &TU);
2305 if (Err != CXError_Success) {
2306 fprintf(stderr, format: "Unable to load translation unit!\n");
2307 describeLibclangFailure(Err);
2308 clang_disposeIndex(index: Idx);
2309 return 1;
2310 }
2311
2312 result = perform_test_load(Idx, TU, /*filter=*/"all", /*prefix=*/NULL, Visitor: FilteredPrintingVisitor, /*PostVisit=*/NULL,
2313 /*CommentSchemaFile=*/NULL);
2314 clang_disposeIndex(index: Idx);
2315 return result;
2316}
2317
2318/******************************************************************************/
2319/* Logic for testing clang_getCursor(). */
2320/******************************************************************************/
2321
2322static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
2323 unsigned start_line, unsigned start_col,
2324 unsigned end_line, unsigned end_col,
2325 const char *prefix) {
2326 printf(format: "// %s: ", FileCheckPrefix);
2327 if (prefix)
2328 printf(format: "-%s", prefix);
2329 PrintExtent(stdout, begin_line: start_line, begin_column: start_col, end_line, end_column: end_col);
2330 printf(format: " ");
2331 PrintCursor(Cursor: cursor, NULL);
2332 printf(format: "\n");
2333}
2334
2335static int perform_file_scan(const char *ast_file, const char *source_file,
2336 const char *prefix) {
2337 CXIndex Idx;
2338 CXTranslationUnit TU;
2339 FILE *fp;
2340 CXCursor prevCursor = clang_getNullCursor();
2341 CXFile file;
2342 unsigned line = 1, col = 1;
2343 unsigned start_line = 1, start_col = 1;
2344
2345 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ excludeDeclarationsFromPCH: 1,
2346 /* displayDiagnostics=*/1))) {
2347 fprintf(stderr, format: "Could not create Index\n");
2348 return 1;
2349 }
2350
2351 if (!CreateTranslationUnit(Idx, file: ast_file, TU: &TU))
2352 return 1;
2353
2354 if ((fp = fopen(filename: source_file, modes: "r")) == NULL) {
2355 fprintf(stderr, format: "Could not open '%s'\n", source_file);
2356 clang_disposeTranslationUnit(TU);
2357 return 1;
2358 }
2359
2360 file = clang_getFile(tu: TU, file_name: source_file);
2361 for (;;) {
2362 CXCursor cursor;
2363 int c = fgetc(stream: fp);
2364
2365 if (c == '\n') {
2366 ++line;
2367 col = 1;
2368 } else
2369 ++col;
2370
2371 /* Check the cursor at this position, and dump the previous one if we have
2372 * found something new.
2373 */
2374 cursor = clang_getCursor(TU, clang_getLocation(tu: TU, file, line, column: col));
2375 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
2376 prevCursor.kind != CXCursor_InvalidFile) {
2377 print_cursor_file_scan(TU, cursor: prevCursor, start_line, start_col,
2378 end_line: line, end_col: col, prefix);
2379 start_line = line;
2380 start_col = col;
2381 }
2382 if (c == EOF)
2383 break;
2384
2385 prevCursor = cursor;
2386 }
2387
2388 fclose(stream: fp);
2389 clang_disposeTranslationUnit(TU);
2390 clang_disposeIndex(index: Idx);
2391 return 0;
2392}
2393
2394/******************************************************************************/
2395/* Logic for testing clang code completion. */
2396/******************************************************************************/
2397
2398/* Parse file:line:column from the input string. Returns 0 on success, non-zero
2399 on failure. If successful, the pointer *filename will contain newly-allocated
2400 memory (that will be owned by the caller) to store the file name. */
2401int parse_file_line_column(const char *input, char **filename, unsigned *line,
2402 unsigned *column, unsigned *second_line,
2403 unsigned *second_column) {
2404 /* Find the second colon. */
2405 const char *last_colon = strrchr(s: input, c: ':');
2406 unsigned values[4], i;
2407 unsigned num_values = (second_line && second_column)? 4 : 2;
2408
2409 char *endptr = 0;
2410 if (!last_colon || last_colon == input) {
2411 if (num_values == 4)
2412 fprintf(stderr, format: "could not parse filename:line:column:line:column in "
2413 "'%s'\n", input);
2414 else
2415 fprintf(stderr, format: "could not parse filename:line:column in '%s'\n", input);
2416 return 1;
2417 }
2418
2419 for (i = 0; i != num_values; ++i) {
2420 const char *prev_colon;
2421
2422 /* Parse the next line or column. */
2423 values[num_values - i - 1] = strtol(nptr: last_colon + 1, endptr: &endptr, base: 10);
2424 if (*endptr != 0 && *endptr != ':') {
2425 fprintf(stderr, format: "could not parse %s in '%s'\n",
2426 (i % 2 ? "column" : "line"), input);
2427 return 1;
2428 }
2429
2430 if (i + 1 == num_values)
2431 break;
2432
2433 /* Find the previous colon. */
2434 prev_colon = last_colon - 1;
2435 while (prev_colon != input && *prev_colon != ':')
2436 --prev_colon;
2437 if (prev_colon == input) {
2438 fprintf(stderr, format: "could not parse %s in '%s'\n",
2439 (i % 2 == 0? "column" : "line"), input);
2440 return 1;
2441 }
2442
2443 last_colon = prev_colon;
2444 }
2445
2446 *line = values[0];
2447 *column = values[1];
2448
2449 if (second_line && second_column) {
2450 *second_line = values[2];
2451 *second_column = values[3];
2452 }
2453
2454 /* Copy the file name. */
2455 *filename = (char*)malloc(size: last_colon - input + 1);
2456 assert(*filename);
2457 memcpy(dest: *filename, src: input, n: last_colon - input);
2458 (*filename)[last_colon - input] = 0;
2459 return 0;
2460}
2461
2462const char *
2463clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
2464 switch (Kind) {
2465 case CXCompletionChunk_Optional: return "Optional";
2466 case CXCompletionChunk_TypedText: return "TypedText";
2467 case CXCompletionChunk_Text: return "Text";
2468 case CXCompletionChunk_Placeholder: return "Placeholder";
2469 case CXCompletionChunk_Informative: return "Informative";
2470 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
2471 case CXCompletionChunk_LeftParen: return "LeftParen";
2472 case CXCompletionChunk_RightParen: return "RightParen";
2473 case CXCompletionChunk_LeftBracket: return "LeftBracket";
2474 case CXCompletionChunk_RightBracket: return "RightBracket";
2475 case CXCompletionChunk_LeftBrace: return "LeftBrace";
2476 case CXCompletionChunk_RightBrace: return "RightBrace";
2477 case CXCompletionChunk_LeftAngle: return "LeftAngle";
2478 case CXCompletionChunk_RightAngle: return "RightAngle";
2479 case CXCompletionChunk_Comma: return "Comma";
2480 case CXCompletionChunk_ResultType: return "ResultType";
2481 case CXCompletionChunk_Colon: return "Colon";
2482 case CXCompletionChunk_SemiColon: return "SemiColon";
2483 case CXCompletionChunk_Equal: return "Equal";
2484 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
2485 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
2486 }
2487
2488 return "Unknown";
2489}
2490
2491static int checkForErrors(CXTranslationUnit TU) {
2492 unsigned Num, i;
2493 CXDiagnostic Diag;
2494 CXString DiagStr;
2495
2496 if (!getenv(name: "CINDEXTEST_FAILONERROR"))
2497 return 0;
2498
2499 Num = clang_getNumDiagnostics(Unit: TU);
2500 for (i = 0; i != Num; ++i) {
2501 Diag = clang_getDiagnostic(Unit: TU, Index: i);
2502 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
2503 DiagStr = clang_formatDiagnostic(Diagnostic: Diag,
2504 Options: clang_defaultDiagnosticDisplayOptions());
2505 fprintf(stderr, format: "%s\n", clang_getCString(string: DiagStr));
2506 clang_disposeString(string: DiagStr);
2507 clang_disposeDiagnostic(Diagnostic: Diag);
2508 return -1;
2509 }
2510 clang_disposeDiagnostic(Diagnostic: Diag);
2511 }
2512
2513 return 0;
2514}
2515
2516static void print_completion_string(CXCompletionString completion_string,
2517 FILE *file) {
2518 int I, N;
2519
2520 N = clang_getNumCompletionChunks(completion_string);
2521 for (I = 0; I != N; ++I) {
2522 CXString text;
2523 const char *cstr;
2524 enum CXCompletionChunkKind Kind
2525 = clang_getCompletionChunkKind(completion_string, chunk_number: I);
2526
2527 if (Kind == CXCompletionChunk_Optional) {
2528 fprintf(stream: file, format: "{Optional ");
2529 print_completion_string(
2530 completion_string: clang_getCompletionChunkCompletionString(completion_string, chunk_number: I),
2531 file);
2532 fprintf(stream: file, format: "}");
2533 continue;
2534 }
2535
2536 if (Kind == CXCompletionChunk_VerticalSpace) {
2537 fprintf(stream: file, format: "{VerticalSpace }");
2538 continue;
2539 }
2540
2541 text = clang_getCompletionChunkText(completion_string, chunk_number: I);
2542 cstr = clang_getCString(string: text);
2543 fprintf(stream: file, format: "{%s %s}",
2544 clang_getCompletionChunkKindSpelling(Kind),
2545 cstr ? cstr : "");
2546 clang_disposeString(string: text);
2547 }
2548
2549}
2550
2551static void print_line_column(CXSourceLocation location, FILE *file) {
2552 unsigned line, column;
2553 clang_getExpansionLocation(location, NULL, line: &line, column: &column, NULL);
2554 fprintf(stream: file, format: "%d:%d", line, column);
2555}
2556
2557static void print_token_range(CXTranslationUnit translation_unit,
2558 CXSourceLocation start, FILE *file) {
2559 CXToken *token = clang_getToken(TU: translation_unit, Location: start);
2560
2561 fprintf(stream: file, format: "{");
2562 if (token != NULL) {
2563 CXSourceRange token_range = clang_getTokenExtent(translation_unit, *token);
2564 print_line_column(location: clang_getRangeStart(range: token_range), file);
2565 fprintf(stream: file, format: "-");
2566 print_line_column(location: clang_getRangeEnd(range: token_range), file);
2567 clang_disposeTokens(TU: translation_unit, Tokens: token, NumTokens: 1);
2568 }
2569
2570 fprintf(stream: file, format: "}");
2571}
2572
2573static void print_completion_result(CXTranslationUnit translation_unit,
2574 CXCodeCompleteResults *completion_results,
2575 unsigned index,
2576 FILE *file) {
2577 CXCompletionResult *completion_result = completion_results->Results + index;
2578 CXString ks = clang_getCursorKindSpelling(Kind: completion_result->CursorKind);
2579 unsigned annotationCount;
2580 enum CXCursorKind ParentKind;
2581 CXString ParentName;
2582 CXString BriefComment;
2583 CXString Annotation;
2584 const char *BriefCommentCString;
2585 unsigned i;
2586
2587 fprintf(stream: file, format: "%s:", clang_getCString(string: ks));
2588 clang_disposeString(string: ks);
2589
2590 print_completion_string(completion_string: completion_result->CompletionString, file);
2591 fprintf(stream: file, format: " (%u)",
2592 clang_getCompletionPriority(completion_string: completion_result->CompletionString));
2593 switch (clang_getCompletionAvailability(completion_string: completion_result->CompletionString)){
2594 case CXAvailability_Available:
2595 break;
2596
2597 case CXAvailability_Deprecated:
2598 fprintf(stream: file, format: " (deprecated)");
2599 break;
2600
2601 case CXAvailability_NotAvailable:
2602 fprintf(stream: file, format: " (unavailable)");
2603 break;
2604
2605 case CXAvailability_NotAccessible:
2606 fprintf(stream: file, format: " (inaccessible)");
2607 break;
2608 }
2609
2610 annotationCount = clang_getCompletionNumAnnotations(
2611 completion_string: completion_result->CompletionString);
2612 if (annotationCount) {
2613 unsigned i;
2614 fprintf(stream: file, format: " (");
2615 for (i = 0; i < annotationCount; ++i) {
2616 if (i != 0)
2617 fprintf(stream: file, format: ", ");
2618 Annotation =
2619 clang_getCompletionAnnotation(completion_string: completion_result->CompletionString, annotation_number: i);
2620 fprintf(stream: file, format: "\"%s\"", clang_getCString(string: Annotation));
2621 clang_disposeString(string: Annotation);
2622 }
2623 fprintf(stream: file, format: ")");
2624 }
2625
2626 if (!getenv(name: "CINDEXTEST_NO_COMPLETION_PARENTS")) {
2627 ParentName = clang_getCompletionParent(completion_string: completion_result->CompletionString,
2628 kind: &ParentKind);
2629 if (ParentKind != CXCursor_NotImplemented) {
2630 CXString KindSpelling = clang_getCursorKindSpelling(Kind: ParentKind);
2631 fprintf(stream: file, format: " (parent: %s '%s')",
2632 clang_getCString(string: KindSpelling),
2633 clang_getCString(string: ParentName));
2634 clang_disposeString(string: KindSpelling);
2635 }
2636 clang_disposeString(string: ParentName);
2637 }
2638
2639 BriefComment = clang_getCompletionBriefComment(
2640 completion_string: completion_result->CompletionString);
2641 BriefCommentCString = clang_getCString(string: BriefComment);
2642 if (BriefCommentCString && *BriefCommentCString != '\0') {
2643 fprintf(stream: file, format: "(brief comment: %s)", BriefCommentCString);
2644 }
2645 clang_disposeString(string: BriefComment);
2646
2647 for (i = 0; i < clang_getCompletionNumFixIts(results: completion_results, completion_index: index);
2648 ++i) {
2649 CXSourceRange correction_range;
2650 CXString FixIt = clang_getCompletionFixIt(results: completion_results, completion_index: index, fixit_index: i,
2651 replacement_range: &correction_range);
2652 fprintf(stream: file, format: " (requires fix-it: ");
2653 print_token_range(translation_unit, start: clang_getRangeStart(range: correction_range),
2654 file);
2655 fprintf(stream: file, format: " to \"%s\")", clang_getCString(string: FixIt));
2656 clang_disposeString(string: FixIt);
2657 }
2658
2659 fprintf(stream: file, format: "\n");
2660}
2661
2662void print_completion_contexts(unsigned long long contexts, FILE *file) {
2663 fprintf(stream: file, format: "Completion contexts:\n");
2664 if (contexts == CXCompletionContext_Unknown) {
2665 fprintf(stream: file, format: "Unknown\n");
2666 }
2667 if (contexts & CXCompletionContext_AnyType) {
2668 fprintf(stream: file, format: "Any type\n");
2669 }
2670 if (contexts & CXCompletionContext_AnyValue) {
2671 fprintf(stream: file, format: "Any value\n");
2672 }
2673 if (contexts & CXCompletionContext_ObjCObjectValue) {
2674 fprintf(stream: file, format: "Objective-C object value\n");
2675 }
2676 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2677 fprintf(stream: file, format: "Objective-C selector value\n");
2678 }
2679 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2680 fprintf(stream: file, format: "C++ class type value\n");
2681 }
2682 if (contexts & CXCompletionContext_DotMemberAccess) {
2683 fprintf(stream: file, format: "Dot member access\n");
2684 }
2685 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2686 fprintf(stream: file, format: "Arrow member access\n");
2687 }
2688 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2689 fprintf(stream: file, format: "Objective-C property access\n");
2690 }
2691 if (contexts & CXCompletionContext_EnumTag) {
2692 fprintf(stream: file, format: "Enum tag\n");
2693 }
2694 if (contexts & CXCompletionContext_UnionTag) {
2695 fprintf(stream: file, format: "Union tag\n");
2696 }
2697 if (contexts & CXCompletionContext_StructTag) {
2698 fprintf(stream: file, format: "Struct tag\n");
2699 }
2700 if (contexts & CXCompletionContext_ClassTag) {
2701 fprintf(stream: file, format: "Class name\n");
2702 }
2703 if (contexts & CXCompletionContext_Namespace) {
2704 fprintf(stream: file, format: "Namespace or namespace alias\n");
2705 }
2706 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2707 fprintf(stream: file, format: "Nested name specifier\n");
2708 }
2709 if (contexts & CXCompletionContext_ObjCInterface) {
2710 fprintf(stream: file, format: "Objective-C interface\n");
2711 }
2712 if (contexts & CXCompletionContext_ObjCProtocol) {
2713 fprintf(stream: file, format: "Objective-C protocol\n");
2714 }
2715 if (contexts & CXCompletionContext_ObjCCategory) {
2716 fprintf(stream: file, format: "Objective-C category\n");
2717 }
2718 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2719 fprintf(stream: file, format: "Objective-C instance method\n");
2720 }
2721 if (contexts & CXCompletionContext_ObjCClassMessage) {
2722 fprintf(stream: file, format: "Objective-C class method\n");
2723 }
2724 if (contexts & CXCompletionContext_ObjCSelectorName) {
2725 fprintf(stream: file, format: "Objective-C selector name\n");
2726 }
2727 if (contexts & CXCompletionContext_MacroName) {
2728 fprintf(stream: file, format: "Macro name\n");
2729 }
2730 if (contexts & CXCompletionContext_NaturalLanguage) {
2731 fprintf(stream: file, format: "Natural language\n");
2732 }
2733}
2734
2735int perform_code_completion(int argc, const char **argv, int timing_only) {
2736 const char *input = argv[1];
2737 char *filename = 0;
2738 unsigned line;
2739 unsigned column;
2740 CXIndex CIdx;
2741 int errorCode;
2742 struct CXUnsavedFile *unsaved_files = 0;
2743 int num_unsaved_files = 0;
2744 CXCodeCompleteResults *results = 0;
2745 enum CXErrorCode Err;
2746 CXTranslationUnit TU;
2747 unsigned I, Repeats = 1;
2748 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2749
2750 if (getenv(name: "CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2751 completionOptions |= CXCodeComplete_IncludeCodePatterns;
2752 if (getenv(name: "CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2753 completionOptions |= CXCodeComplete_IncludeBriefComments;
2754 if (getenv(name: "CINDEXTEST_COMPLETION_SKIP_PREAMBLE"))
2755 completionOptions |= CXCodeComplete_SkipPreamble;
2756 if (getenv(name: "CINDEXTEST_COMPLETION_INCLUDE_FIXITS"))
2757 completionOptions |= CXCodeComplete_IncludeCompletionsWithFixIts;
2758
2759 if (timing_only)
2760 input += strlen(s: "-code-completion-timing=");
2761 else
2762 input += strlen(s: "-code-completion-at=");
2763
2764 if ((errorCode = parse_file_line_column(input, filename: &filename, line: &line, column: &column,
2765 second_line: 0, second_column: 0)))
2766 return errorCode;
2767
2768 if (parse_remapped_files(argc, argv, start_arg: 2, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files))
2769 return -1;
2770
2771 CIdx = createIndexWithInvocationEmissionPath(ExcludeDeclarationsFromPCH: 0, DisplayDiagnostics: 0);
2772 if (!CIdx)
2773 return -1;
2774
2775 if (getenv(name: "CINDEXTEST_EDITING"))
2776 Repeats = 5;
2777
2778 Err = clang_parseTranslationUnit2(CIdx, source_filename: 0,
2779 command_line_args: argv + num_unsaved_files + 2,
2780 num_command_line_args: argc - num_unsaved_files - 2,
2781 unsaved_files: 0, num_unsaved_files: 0, options: getDefaultParsingOptions(), out_TU: &TU);
2782 if (Err != CXError_Success) {
2783 fprintf(stderr, format: "Unable to load translation unit!\n");
2784 describeLibclangFailure(Err);
2785 return 1;
2786 }
2787
2788 Err = clang_reparseTranslationUnit(TU, num_unsaved_files: 0, unsaved_files: 0,
2789 options: clang_defaultReparseOptions(TU));
2790
2791 if (Err != CXError_Success) {
2792 fprintf(stderr, format: "Unable to reparse translation unit!\n");
2793 describeLibclangFailure(Err);
2794 clang_disposeTranslationUnit(TU);
2795 return 1;
2796 }
2797
2798 for (I = 0; I != Repeats; ++I) {
2799 results = clang_codeCompleteAt(TU, complete_filename: filename, complete_line: line, complete_column: column,
2800 unsaved_files, num_unsaved_files,
2801 options: completionOptions);
2802 if (!results) {
2803 fprintf(stderr, format: "Unable to perform code completion!\n");
2804 return 1;
2805 }
2806 if (I != Repeats-1)
2807 clang_disposeCodeCompleteResults(Results: results);
2808 }
2809
2810 if (results) {
2811 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
2812 unsigned long long contexts;
2813 enum CXCursorKind containerKind;
2814 CXString objCSelector;
2815 const char *selectorString;
2816 if (!timing_only) {
2817 /* Sort the code-completion results based on the typed text. */
2818 clang_sortCodeCompletionResults(Results: results->Results, NumResults: results->NumResults);
2819
2820 for (i = 0; i != n; ++i)
2821 print_completion_result(translation_unit: TU, completion_results: results, index: i, stdout);
2822 }
2823 n = clang_codeCompleteGetNumDiagnostics(Results: results);
2824 for (i = 0; i != n; ++i) {
2825 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(Results: results, Index: i);
2826 PrintDiagnostic(Diagnostic: diag);
2827 clang_disposeDiagnostic(Diagnostic: diag);
2828 }
2829
2830 contexts = clang_codeCompleteGetContexts(Results: results);
2831 print_completion_contexts(contexts, stdout);
2832
2833 containerKind = clang_codeCompleteGetContainerKind(Results: results,
2834 IsIncomplete: &containerIsIncomplete);
2835
2836 if (containerKind != CXCursor_InvalidCode) {
2837 /* We have found a container */
2838 CXString containerUSR, containerKindSpelling;
2839 containerKindSpelling = clang_getCursorKindSpelling(Kind: containerKind);
2840 printf(format: "Container Kind: %s\n", clang_getCString(string: containerKindSpelling));
2841 clang_disposeString(string: containerKindSpelling);
2842
2843 if (containerIsIncomplete) {
2844 printf(format: "Container is incomplete\n");
2845 }
2846 else {
2847 printf(format: "Container is complete\n");
2848 }
2849
2850 containerUSR = clang_codeCompleteGetContainerUSR(Results: results);
2851 printf(format: "Container USR: %s\n", clang_getCString(string: containerUSR));
2852 clang_disposeString(string: containerUSR);
2853 }
2854
2855 objCSelector = clang_codeCompleteGetObjCSelector(Results: results);
2856 selectorString = clang_getCString(string: objCSelector);
2857 if (selectorString && strlen(s: selectorString) > 0) {
2858 printf(format: "Objective-C selector: %s\n", selectorString);
2859 }
2860 clang_disposeString(string: objCSelector);
2861
2862 clang_disposeCodeCompleteResults(Results: results);
2863 }
2864 clang_disposeTranslationUnit(TU);
2865 clang_disposeIndex(index: CIdx);
2866 free(ptr: filename);
2867
2868 free_remapped_files(unsaved_files, num_unsaved_files);
2869
2870 return 0;
2871}
2872
2873typedef struct {
2874 char *filename;
2875 unsigned line;
2876 unsigned column;
2877} CursorSourceLocation;
2878
2879typedef void (*cursor_handler_t)(CXCursor cursor);
2880
2881static int inspect_cursor_at(int argc, const char **argv,
2882 const char *locations_flag,
2883 cursor_handler_t handler) {
2884 CXIndex CIdx;
2885 int errorCode;
2886 struct CXUnsavedFile *unsaved_files = 0;
2887 int num_unsaved_files = 0;
2888 enum CXErrorCode Err;
2889 CXTranslationUnit TU;
2890 CXCursor Cursor;
2891 CursorSourceLocation *Locations = 0;
2892 unsigned NumLocations = 0, Loc;
2893 unsigned Repeats = 1;
2894 unsigned I;
2895
2896 /* Count the number of locations. */
2897 while (strstr(haystack: argv[NumLocations+1], needle: locations_flag) == argv[NumLocations+1])
2898 ++NumLocations;
2899
2900 /* Parse the locations. */
2901 assert(NumLocations > 0 && "Unable to count locations?");
2902 Locations = (CursorSourceLocation *)malloc(
2903 size: NumLocations * sizeof(CursorSourceLocation));
2904 assert(Locations);
2905 for (Loc = 0; Loc < NumLocations; ++Loc) {
2906 const char *input = argv[Loc + 1] + strlen(s: locations_flag);
2907 if ((errorCode = parse_file_line_column(input, filename: &Locations[Loc].filename,
2908 line: &Locations[Loc].line,
2909 column: &Locations[Loc].column, second_line: 0, second_column: 0)))
2910 return errorCode;
2911 }
2912
2913 if (parse_remapped_files(argc, argv, start_arg: NumLocations + 1, unsaved_files: &unsaved_files,
2914 num_unsaved_files: &num_unsaved_files))
2915 return -1;
2916
2917 if (getenv(name: "CINDEXTEST_EDITING"))
2918 Repeats = 5;
2919
2920 /* Parse the translation unit. When we're testing clang_getCursor() after
2921 reparsing, don't remap unsaved files until the second parse. */
2922 CIdx = clang_createIndex(excludeDeclarationsFromPCH: 1, displayDiagnostics: 1);
2923 Err = clang_parseTranslationUnit2(CIdx, source_filename: argv[argc - 1],
2924 command_line_args: argv + num_unsaved_files + 1 + NumLocations,
2925 num_command_line_args: argc - num_unsaved_files - 2 - NumLocations,
2926 unsaved_files,
2927 num_unsaved_files: Repeats > 1? 0 : num_unsaved_files,
2928 options: getDefaultParsingOptions(), out_TU: &TU);
2929 if (Err != CXError_Success) {
2930 fprintf(stderr, format: "unable to parse input\n");
2931 describeLibclangFailure(Err);
2932 return -1;
2933 }
2934
2935 if (checkForErrors(TU) != 0)
2936 return -1;
2937
2938 for (I = 0; I != Repeats; ++I) {
2939 if (Repeats > 1) {
2940 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2941 options: clang_defaultReparseOptions(TU));
2942 if (Err != CXError_Success) {
2943 describeLibclangFailure(Err);
2944 clang_disposeTranslationUnit(TU);
2945 return 1;
2946 }
2947 }
2948
2949 if (checkForErrors(TU) != 0)
2950 return -1;
2951
2952 for (Loc = 0; Loc < NumLocations; ++Loc) {
2953 CXFile file = clang_getFile(tu: TU, file_name: Locations[Loc].filename);
2954 if (!file)
2955 continue;
2956
2957 Cursor = clang_getCursor(TU,
2958 clang_getLocation(tu: TU, file, line: Locations[Loc].line,
2959 column: Locations[Loc].column));
2960
2961 if (checkForErrors(TU) != 0)
2962 return -1;
2963
2964 if (I + 1 == Repeats) {
2965 handler(Cursor);
2966 free(ptr: Locations[Loc].filename);
2967 }
2968 }
2969 }
2970
2971 PrintDiagnostics(TU);
2972 clang_disposeTranslationUnit(TU);
2973 clang_disposeIndex(index: CIdx);
2974 free(ptr: Locations);
2975 free_remapped_files(unsaved_files, num_unsaved_files);
2976 return 0;
2977}
2978
2979static void inspect_print_cursor(CXCursor Cursor) {
2980 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2981 CXCompletionString completionString = clang_getCursorCompletionString(
2982 cursor: Cursor);
2983 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2984 CXString Spelling;
2985 const char *cspell;
2986 unsigned line, column;
2987 clang_getSpellingLocation(location: CursorLoc, file: 0, line: &line, column: &column, offset: 0);
2988 printf(format: "%d:%d ", line, column);
2989 PrintCursor(Cursor, NULL);
2990 PrintCursorExtent(C: Cursor);
2991 Spelling = clang_getCursorSpelling(Cursor);
2992 cspell = clang_getCString(string: Spelling);
2993 if (cspell && strlen(s: cspell) != 0) {
2994 unsigned pieceIndex;
2995 printf(format: " Spelling=%s (", cspell);
2996 for (pieceIndex = 0; ; ++pieceIndex) {
2997 CXSourceRange range =
2998 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, options: 0);
2999 if (clang_Range_isNull(range))
3000 break;
3001 PrintRange(R: range, str: 0);
3002 }
3003 printf(format: ")");
3004 }
3005 clang_disposeString(string: Spelling);
3006 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
3007 printf(format: " Selector index=%d",
3008 clang_Cursor_getObjCSelectorIndex(Cursor));
3009 if (clang_Cursor_isDynamicCall(C: Cursor))
3010 printf(format: " Dynamic-call");
3011 if (Cursor.kind == CXCursor_ObjCMessageExpr ||
3012 Cursor.kind == CXCursor_MemberRefExpr) {
3013 CXType T = clang_Cursor_getReceiverType(C: Cursor);
3014 if (T.kind != CXType_Invalid) {
3015 CXString S = clang_getTypeKindSpelling(K: T.kind);
3016 printf(format: " Receiver-type=%s", clang_getCString(string: S));
3017 clang_disposeString(string: S);
3018 }
3019 }
3020
3021 {
3022 CXModule mod = clang_Cursor_getModule(C: Cursor);
3023 CXFile astFile;
3024 CXString name, astFilename;
3025 unsigned i, numHeaders;
3026 if (mod) {
3027 astFile = clang_Module_getASTFile(Module: mod);
3028 astFilename = clang_getFileName(SFile: astFile);
3029 name = clang_Module_getFullName(Module: mod);
3030 numHeaders = clang_Module_getNumTopLevelHeaders(TU, Module: mod);
3031 printf(format: " ModuleName=%s (%s) system=%d Headers(%d):",
3032 clang_getCString(string: name), clang_getCString(string: astFilename),
3033 clang_Module_isSystem(Module: mod), numHeaders);
3034 clang_disposeString(string: name);
3035 clang_disposeString(string: astFilename);
3036 for (i = 0; i < numHeaders; ++i) {
3037 CXFile file = clang_Module_getTopLevelHeader(TU, Module: mod, Index: i);
3038 CXString filename = clang_getFileName(SFile: file);
3039 printf(format: "\n%s", clang_getCString(string: filename));
3040 clang_disposeString(string: filename);
3041 }
3042 }
3043 }
3044
3045 if (completionString != NULL) {
3046 printf(format: "\nCompletion string: ");
3047 print_completion_string(completion_string: completionString, stdout);
3048 }
3049 printf(format: "\n");
3050}
3051
3052static void display_evaluate_results(CXEvalResult result) {
3053 switch (clang_EvalResult_getKind(E: result)) {
3054 case CXEval_Int:
3055 {
3056 printf(format: "Kind: Int, ");
3057 if (clang_EvalResult_isUnsignedInt(E: result)) {
3058 unsigned long long val = clang_EvalResult_getAsUnsigned(E: result);
3059 printf(format: "unsigned, Value: %llu", val);
3060 } else {
3061 long long val = clang_EvalResult_getAsLongLong(E: result);
3062 printf(format: "Value: %lld", val);
3063 }
3064 break;
3065 }
3066 case CXEval_Float:
3067 {
3068 double val = clang_EvalResult_getAsDouble(E: result);
3069 printf(format: "Kind: Float , Value: %f", val);
3070 break;
3071 }
3072 case CXEval_ObjCStrLiteral:
3073 {
3074 const char* str = clang_EvalResult_getAsStr(E: result);
3075 printf(format: "Kind: ObjCString , Value: %s", str);
3076 break;
3077 }
3078 case CXEval_StrLiteral:
3079 {
3080 const char* str = clang_EvalResult_getAsStr(E: result);
3081 printf(format: "Kind: CString , Value: %s", str);
3082 break;
3083 }
3084 case CXEval_CFStr:
3085 {
3086 const char* str = clang_EvalResult_getAsStr(E: result);
3087 printf(format: "Kind: CFString , Value: %s", str);
3088 break;
3089 }
3090 default:
3091 printf(format: "Unexposed");
3092 break;
3093 }
3094}
3095
3096static void inspect_evaluate_cursor(CXCursor Cursor) {
3097 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
3098 CXString Spelling;
3099 const char *cspell;
3100 unsigned line, column;
3101 CXEvalResult ER;
3102
3103 clang_getSpellingLocation(location: CursorLoc, file: 0, line: &line, column: &column, offset: 0);
3104 printf(format: "%d:%d ", line, column);
3105 PrintCursor(Cursor, NULL);
3106 PrintCursorExtent(C: Cursor);
3107 Spelling = clang_getCursorSpelling(Cursor);
3108 cspell = clang_getCString(string: Spelling);
3109 if (cspell && strlen(s: cspell) != 0) {
3110 unsigned pieceIndex;
3111 printf(format: " Spelling=%s (", cspell);
3112 for (pieceIndex = 0; ; ++pieceIndex) {
3113 CXSourceRange range =
3114 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, options: 0);
3115 if (clang_Range_isNull(range))
3116 break;
3117 PrintRange(R: range, str: 0);
3118 }
3119 printf(format: ")");
3120 }
3121 clang_disposeString(string: Spelling);
3122
3123 ER = clang_Cursor_Evaluate(C: Cursor);
3124 if (!ER) {
3125 printf(format: "Not Evaluatable");
3126 } else {
3127 display_evaluate_results(result: ER);
3128 clang_EvalResult_dispose(E: ER);
3129 }
3130 printf(format: "\n");
3131}
3132
3133static void inspect_macroinfo_cursor(CXCursor Cursor) {
3134 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
3135 CXString Spelling;
3136 const char *cspell;
3137 unsigned line, column;
3138 clang_getSpellingLocation(location: CursorLoc, file: 0, line: &line, column: &column, offset: 0);
3139 printf(format: "%d:%d ", line, column);
3140 PrintCursor(Cursor, NULL);
3141 PrintCursorExtent(C: Cursor);
3142 Spelling = clang_getCursorSpelling(Cursor);
3143 cspell = clang_getCString(string: Spelling);
3144 if (cspell && strlen(s: cspell) != 0) {
3145 unsigned pieceIndex;
3146 printf(format: " Spelling=%s (", cspell);
3147 for (pieceIndex = 0; ; ++pieceIndex) {
3148 CXSourceRange range =
3149 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, options: 0);
3150 if (clang_Range_isNull(range))
3151 break;
3152 PrintRange(R: range, str: 0);
3153 }
3154 printf(format: ")");
3155 }
3156 clang_disposeString(string: Spelling);
3157
3158 if (clang_Cursor_isMacroBuiltin(C: Cursor)) {
3159 printf(format: "[builtin macro]");
3160 } else if (clang_Cursor_isMacroFunctionLike(C: Cursor)) {
3161 printf(format: "[function macro]");
3162 }
3163 printf(format: "\n");
3164}
3165
3166static enum CXVisitorResult findFileRefsVisit(void *context,
3167 CXCursor cursor, CXSourceRange range) {
3168 if (clang_Range_isNull(range))
3169 return CXVisit_Continue;
3170
3171 PrintCursor(Cursor: cursor, NULL);
3172 PrintRange(R: range, str: "");
3173 printf(format: "\n");
3174 return CXVisit_Continue;
3175}
3176
3177static int find_file_refs_at(int argc, const char **argv) {
3178 CXIndex CIdx;
3179 int errorCode;
3180 struct CXUnsavedFile *unsaved_files = 0;
3181 int num_unsaved_files = 0;
3182 enum CXErrorCode Err;
3183 CXTranslationUnit TU;
3184 CXCursor Cursor;
3185 CursorSourceLocation *Locations = 0;
3186 unsigned NumLocations = 0, Loc;
3187 unsigned Repeats = 1;
3188 unsigned I;
3189
3190 /* Count the number of locations. */
3191 while (strstr(haystack: argv[NumLocations+1], needle: "-file-refs-at=") == argv[NumLocations+1])
3192 ++NumLocations;
3193
3194 /* Parse the locations. */
3195 assert(NumLocations > 0 && "Unable to count locations?");
3196 Locations = (CursorSourceLocation *)malloc(
3197 size: NumLocations * sizeof(CursorSourceLocation));
3198 assert(Locations);
3199 for (Loc = 0; Loc < NumLocations; ++Loc) {
3200 const char *input = argv[Loc + 1] + strlen(s: "-file-refs-at=");
3201 if ((errorCode = parse_file_line_column(input, filename: &Locations[Loc].filename,
3202 line: &Locations[Loc].line,
3203 column: &Locations[Loc].column, second_line: 0, second_column: 0)))
3204 return errorCode;
3205 }
3206
3207 if (parse_remapped_files(argc, argv, start_arg: NumLocations + 1, unsaved_files: &unsaved_files,
3208 num_unsaved_files: &num_unsaved_files))
3209 return -1;
3210
3211 if (getenv(name: "CINDEXTEST_EDITING"))
3212 Repeats = 5;
3213
3214 /* Parse the translation unit. When we're testing clang_getCursor() after
3215 reparsing, don't remap unsaved files until the second parse. */
3216 CIdx = clang_createIndex(excludeDeclarationsFromPCH: 1, displayDiagnostics: 1);
3217 Err = clang_parseTranslationUnit2(CIdx, source_filename: argv[argc - 1],
3218 command_line_args: argv + num_unsaved_files + 1 + NumLocations,
3219 num_command_line_args: argc - num_unsaved_files - 2 - NumLocations,
3220 unsaved_files,
3221 num_unsaved_files: Repeats > 1? 0 : num_unsaved_files,
3222 options: getDefaultParsingOptions(), out_TU: &TU);
3223 if (Err != CXError_Success) {
3224 fprintf(stderr, format: "unable to parse input\n");
3225 describeLibclangFailure(Err);
3226 clang_disposeTranslationUnit(TU);
3227 return -1;
3228 }
3229
3230 if (checkForErrors(TU) != 0)
3231 return -1;
3232
3233 for (I = 0; I != Repeats; ++I) {
3234 if (Repeats > 1) {
3235 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3236 options: clang_defaultReparseOptions(TU));
3237 if (Err != CXError_Success) {
3238 describeLibclangFailure(Err);
3239 clang_disposeTranslationUnit(TU);
3240 return 1;
3241 }
3242 }
3243
3244 if (checkForErrors(TU) != 0)
3245 return -1;
3246
3247 for (Loc = 0; Loc < NumLocations; ++Loc) {
3248 CXFile file = clang_getFile(tu: TU, file_name: Locations[Loc].filename);
3249 if (!file)
3250 continue;
3251
3252 Cursor = clang_getCursor(TU,
3253 clang_getLocation(tu: TU, file, line: Locations[Loc].line,
3254 column: Locations[Loc].column));
3255
3256 if (checkForErrors(TU) != 0)
3257 return -1;
3258
3259 if (I + 1 == Repeats) {
3260 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
3261 PrintCursor(Cursor, NULL);
3262 printf(format: "\n");
3263 clang_findReferencesInFile(cursor: Cursor, file, visitor);
3264 free(ptr: Locations[Loc].filename);
3265
3266 if (checkForErrors(TU) != 0)
3267 return -1;
3268 }
3269 }
3270 }
3271
3272 PrintDiagnostics(TU);
3273 clang_disposeTranslationUnit(TU);
3274 clang_disposeIndex(index: CIdx);
3275 free(ptr: Locations);
3276 free_remapped_files(unsaved_files, num_unsaved_files);
3277 return 0;
3278}
3279
3280static enum CXVisitorResult findFileIncludesVisit(void *context,
3281 CXCursor cursor, CXSourceRange range) {
3282 PrintCursor(Cursor: cursor, NULL);
3283 PrintRange(R: range, str: "");
3284 printf(format: "\n");
3285 return CXVisit_Continue;
3286}
3287
3288static int find_file_includes_in(int argc, const char **argv) {
3289 CXIndex CIdx;
3290 struct CXUnsavedFile *unsaved_files = 0;
3291 int num_unsaved_files = 0;
3292 enum CXErrorCode Err;
3293 CXTranslationUnit TU;
3294 const char **Filenames = 0;
3295 unsigned NumFilenames = 0;
3296 unsigned Repeats = 1;
3297 unsigned I, FI;
3298
3299 /* Count the number of locations. */
3300 while (strstr(haystack: argv[NumFilenames+1], needle: "-file-includes-in=") == argv[NumFilenames+1])
3301 ++NumFilenames;
3302
3303 /* Parse the locations. */
3304 assert(NumFilenames > 0 && "Unable to count filenames?");
3305 Filenames = (const char **)malloc(size: NumFilenames * sizeof(const char *));
3306 assert(Filenames);
3307 for (I = 0; I < NumFilenames; ++I) {
3308 const char *input = argv[I + 1] + strlen(s: "-file-includes-in=");
3309 /* Copy the file name. */
3310 Filenames[I] = input;
3311 }
3312
3313 if (parse_remapped_files(argc, argv, start_arg: NumFilenames + 1, unsaved_files: &unsaved_files,
3314 num_unsaved_files: &num_unsaved_files))
3315 return -1;
3316
3317 if (getenv(name: "CINDEXTEST_EDITING"))
3318 Repeats = 2;
3319
3320 /* Parse the translation unit. When we're testing clang_getCursor() after
3321 reparsing, don't remap unsaved files until the second parse. */
3322 CIdx = clang_createIndex(excludeDeclarationsFromPCH: 1, displayDiagnostics: 1);
3323 Err = clang_parseTranslationUnit2(
3324 CIdx, source_filename: argv[argc - 1],
3325 command_line_args: argv + num_unsaved_files + 1 + NumFilenames,
3326 num_command_line_args: argc - num_unsaved_files - 2 - NumFilenames,
3327 unsaved_files,
3328 num_unsaved_files: Repeats > 1 ? 0 : num_unsaved_files, options: getDefaultParsingOptions(), out_TU: &TU);
3329
3330 if (Err != CXError_Success) {
3331 fprintf(stderr, format: "unable to parse input\n");
3332 describeLibclangFailure(Err);
3333 clang_disposeTranslationUnit(TU);
3334 return -1;
3335 }
3336
3337 if (checkForErrors(TU) != 0)
3338 return -1;
3339
3340 for (I = 0; I != Repeats; ++I) {
3341 if (Repeats > 1) {
3342 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3343 options: clang_defaultReparseOptions(TU));
3344 if (Err != CXError_Success) {
3345 describeLibclangFailure(Err);
3346 clang_disposeTranslationUnit(TU);
3347 return 1;
3348 }
3349 }
3350
3351 if (checkForErrors(TU) != 0)
3352 return -1;
3353
3354 for (FI = 0; FI < NumFilenames; ++FI) {
3355 CXFile file = clang_getFile(tu: TU, file_name: Filenames[FI]);
3356 if (!file)
3357 continue;
3358
3359 if (checkForErrors(TU) != 0)
3360 return -1;
3361
3362 if (I + 1 == Repeats) {
3363 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
3364 clang_findIncludesInFile(TU, file, visitor);
3365
3366 if (checkForErrors(TU) != 0)
3367 return -1;
3368 }
3369 }
3370 }
3371
3372 PrintDiagnostics(TU);
3373 clang_disposeTranslationUnit(TU);
3374 clang_disposeIndex(index: CIdx);
3375 free(ptr: (void *)Filenames);
3376 free_remapped_files(unsaved_files, num_unsaved_files);
3377 return 0;
3378}
3379
3380#define MAX_IMPORTED_ASTFILES 200
3381
3382typedef struct {
3383 char **filenames;
3384 unsigned num_files;
3385} ImportedASTFilesData;
3386
3387static ImportedASTFilesData *importedASTs_create(void) {
3388 ImportedASTFilesData *p;
3389 p = malloc(size: sizeof(ImportedASTFilesData));
3390 assert(p);
3391 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
3392 assert(p->filenames);
3393 p->num_files = 0;
3394 return p;
3395}
3396
3397static void importedASTs_dispose(ImportedASTFilesData *p) {
3398 unsigned i;
3399 if (!p)
3400 return;
3401
3402 for (i = 0; i < p->num_files; ++i)
3403 free(ptr: p->filenames[i]);
3404 free(ptr: p->filenames);
3405 free(ptr: p);
3406}
3407
3408static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
3409 unsigned i;
3410 assert(p && file);
3411 for (i = 0; i < p->num_files; ++i)
3412 if (strcmp(s1: file, s2: p->filenames[i]) == 0)
3413 return;
3414 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
3415 p->filenames[p->num_files++] = strdup(s: file);
3416}
3417
3418typedef struct IndexDataStringList_ {
3419 struct IndexDataStringList_ *next;
3420 char data[1]; /* Dynamically sized. */
3421} IndexDataStringList;
3422
3423typedef struct {
3424 const char *check_prefix;
3425 int first_check_printed;
3426 int fail_for_error;
3427 int abort;
3428 CXString main_filename;
3429 ImportedASTFilesData *importedASTs;
3430 IndexDataStringList *strings;
3431 CXTranslationUnit TU;
3432} IndexData;
3433
3434static void free_client_data(IndexData *index_data) {
3435 IndexDataStringList *node = index_data->strings;
3436 while (node) {
3437 IndexDataStringList *next = node->next;
3438 free(ptr: node);
3439 node = next;
3440 }
3441 index_data->strings = NULL;
3442}
3443
3444static void printCheck(IndexData *data) {
3445 if (data->check_prefix) {
3446 if (data->first_check_printed) {
3447 printf(format: "// %s-NEXT: ", data->check_prefix);
3448 } else {
3449 printf(format: "// %s : ", data->check_prefix);
3450 data->first_check_printed = 1;
3451 }
3452 }
3453}
3454
3455static void printCXIndexFile(CXIdxClientFile file) {
3456 CXString filename = clang_getFileName(SFile: (CXFile)file);
3457 printf(format: "%s", clang_getCString(string: filename));
3458 clang_disposeString(string: filename);
3459}
3460
3461static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
3462 IndexData *index_data;
3463 CXString filename;
3464 const char *cname;
3465 CXIdxClientFile file;
3466 unsigned line, column;
3467 const char *main_filename;
3468 int isMainFile;
3469
3470 index_data = (IndexData *)client_data;
3471 clang_indexLoc_getFileLocation(loc, indexFile: &file, file: 0, line: &line, column: &column, offset: 0);
3472 if (line == 0) {
3473 printf(format: "<invalid>");
3474 return;
3475 }
3476 if (!file) {
3477 printf(format: "<no idxfile>");
3478 return;
3479 }
3480 filename = clang_getFileName(SFile: (CXFile)file);
3481 cname = clang_getCString(string: filename);
3482 main_filename = clang_getCString(string: index_data->main_filename);
3483 if (strcmp(s1: cname, s2: main_filename) == 0)
3484 isMainFile = 1;
3485 else
3486 isMainFile = 0;
3487 clang_disposeString(string: filename);
3488
3489 if (!isMainFile) {
3490 printCXIndexFile(file);
3491 printf(format: ":");
3492 }
3493 printf(format: "%d:%d", line, column);
3494}
3495
3496static unsigned digitCount(unsigned val) {
3497 unsigned c = 1;
3498 while (1) {
3499 if (val < 10)
3500 return c;
3501 ++c;
3502 val /= 10;
3503 }
3504}
3505
3506static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
3507 const CXIdxEntityInfo *info,
3508 CXIdxLoc loc) {
3509 IndexData *index_data;
3510 IndexDataStringList *node;
3511 const char *name;
3512 char *newStr;
3513 CXIdxClientFile file;
3514 unsigned line, column;
3515
3516 name = info->name;
3517 if (!name)
3518 name = "<anon-tag>";
3519
3520 clang_indexLoc_getFileLocation(loc, indexFile: &file, file: 0, line: &line, column: &column, offset: 0);
3521
3522 node =
3523 (IndexDataStringList *)malloc(size: sizeof(IndexDataStringList) + strlen(s: name) +
3524 digitCount(val: line) + digitCount(val: column) + 2);
3525 assert(node);
3526 newStr = node->data;
3527 sprintf(s: newStr, format: "%s:%d:%d", name, line, column);
3528
3529 /* Remember string so it can be freed later. */
3530 index_data = (IndexData *)client_data;
3531 node->next = index_data->strings;
3532 index_data->strings = node;
3533
3534 return (CXIdxClientContainer)newStr;
3535}
3536
3537static void printCXIndexContainer(const CXIdxContainerInfo *info) {
3538 CXIdxClientContainer container;
3539 container = clang_index_getClientContainer(info);
3540 if (!container)
3541 printf(format: "[<<NULL>>]");
3542 else
3543 printf(format: "[%s]", (const char *)container);
3544}
3545
3546static const char *getEntityKindString(CXIdxEntityKind kind) {
3547 switch (kind) {
3548 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
3549 case CXIdxEntity_Typedef: return "typedef";
3550 case CXIdxEntity_Function: return "function";
3551 case CXIdxEntity_Variable: return "variable";
3552 case CXIdxEntity_Field: return "field";
3553 case CXIdxEntity_EnumConstant: return "enumerator";
3554 case CXIdxEntity_ObjCClass: return "objc-class";
3555 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
3556 case CXIdxEntity_ObjCCategory: return "objc-category";
3557 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
3558 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
3559 case CXIdxEntity_ObjCProperty: return "objc-property";
3560 case CXIdxEntity_ObjCIvar: return "objc-ivar";
3561 case CXIdxEntity_Enum: return "enum";
3562 case CXIdxEntity_Struct: return "struct";
3563 case CXIdxEntity_Union: return "union";
3564 case CXIdxEntity_CXXClass: return "c++-class";
3565 case CXIdxEntity_CXXNamespace: return "namespace";
3566 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
3567 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
3568 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
3569 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
3570 case CXIdxEntity_CXXConstructor: return "constructor";
3571 case CXIdxEntity_CXXDestructor: return "destructor";
3572 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
3573 case CXIdxEntity_CXXTypeAlias: return "type-alias";
3574 case CXIdxEntity_CXXInterface: return "c++-__interface";
3575 case CXIdxEntity_CXXConcept:
3576 return "concept";
3577 }
3578 assert(0 && "Garbage entity kind");
3579 return 0;
3580}
3581
3582static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
3583 switch (kind) {
3584 case CXIdxEntity_NonTemplate: return "";
3585 case CXIdxEntity_Template: return "-template";
3586 case CXIdxEntity_TemplatePartialSpecialization:
3587 return "-template-partial-spec";
3588 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
3589 }
3590 assert(0 && "Garbage entity kind");
3591 return 0;
3592}
3593
3594static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
3595 switch (kind) {
3596 case CXIdxEntityLang_None: return "<none>";
3597 case CXIdxEntityLang_C: return "C";
3598 case CXIdxEntityLang_ObjC: return "ObjC";
3599 case CXIdxEntityLang_CXX: return "C++";
3600 case CXIdxEntityLang_Swift: return "Swift";
3601 }
3602 assert(0 && "Garbage language kind");
3603 return 0;
3604}
3605
3606static void printEntityInfo(const char *cb,
3607 CXClientData client_data,
3608 const CXIdxEntityInfo *info) {
3609 const char *name;
3610 IndexData *index_data;
3611 unsigned i;
3612 index_data = (IndexData *)client_data;
3613 printCheck(data: index_data);
3614
3615 if (!info) {
3616 printf(format: "%s: <<NULL>>", cb);
3617 return;
3618 }
3619
3620 name = info->name;
3621 if (!name)
3622 name = "<anon-tag>";
3623
3624 printf(format: "%s: kind: %s%s", cb, getEntityKindString(kind: info->kind),
3625 getEntityTemplateKindString(kind: info->templateKind));
3626 printf(format: " | name: %s", name);
3627 printf(format: " | USR: %s", info->USR);
3628 printf(format: " | lang: %s", getEntityLanguageString(kind: info->lang));
3629
3630 for (i = 0; i != info->numAttributes; ++i) {
3631 const CXIdxAttrInfo *Attr = info->attributes[i];
3632 printf(format: " <attribute>: ");
3633 PrintCursor(Cursor: Attr->cursor, NULL);
3634 }
3635}
3636
3637static void printBaseClassInfo(CXClientData client_data,
3638 const CXIdxBaseClassInfo *info) {
3639 printEntityInfo(cb: " <base>", client_data, info: info->base);
3640 printf(format: " | cursor: ");
3641 PrintCursor(Cursor: info->cursor, NULL);
3642 printf(format: " | loc: ");
3643 printCXIndexLoc(loc: info->loc, client_data);
3644}
3645
3646static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3647 CXClientData client_data) {
3648 unsigned i;
3649 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3650 printEntityInfo(cb: " <protocol>", client_data,
3651 info: ProtoInfo->protocols[i]->protocol);
3652 printf(format: " | cursor: ");
3653 PrintCursor(Cursor: ProtoInfo->protocols[i]->cursor, NULL);
3654 printf(format: " | loc: ");
3655 printCXIndexLoc(loc: ProtoInfo->protocols[i]->loc, client_data);
3656 printf(format: "\n");
3657 }
3658}
3659
3660static void printSymbolRole(CXSymbolRole role) {
3661 if (role & CXSymbolRole_Declaration)
3662 printf(format: " decl");
3663 if (role & CXSymbolRole_Definition)
3664 printf(format: " def");
3665 if (role & CXSymbolRole_Reference)
3666 printf(format: " ref");
3667 if (role & CXSymbolRole_Read)
3668 printf(format: " read");
3669 if (role & CXSymbolRole_Write)
3670 printf(format: " write");
3671 if (role & CXSymbolRole_Call)
3672 printf(format: " call");
3673 if (role & CXSymbolRole_Dynamic)
3674 printf(format: " dyn");
3675 if (role & CXSymbolRole_AddressOf)
3676 printf(format: " addr");
3677 if (role & CXSymbolRole_Implicit)
3678 printf(format: " implicit");
3679}
3680
3681static void index_diagnostic(CXClientData client_data,
3682 CXDiagnosticSet diagSet, void *reserved) {
3683 CXString str;
3684 const char *cstr;
3685 unsigned numDiags, i;
3686 CXDiagnostic diag;
3687 IndexData *index_data;
3688 index_data = (IndexData *)client_data;
3689 printCheck(data: index_data);
3690
3691 numDiags = clang_getNumDiagnosticsInSet(Diags: diagSet);
3692 for (i = 0; i != numDiags; ++i) {
3693 diag = clang_getDiagnosticInSet(Diags: diagSet, Index: i);
3694 str = clang_formatDiagnostic(Diagnostic: diag, Options: clang_defaultDiagnosticDisplayOptions());
3695 cstr = clang_getCString(string: str);
3696 printf(format: "[diagnostic]: %s\n", cstr);
3697 clang_disposeString(string: str);
3698
3699 if (getenv(name: "CINDEXTEST_FAILONERROR") &&
3700 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3701 index_data->fail_for_error = 1;
3702 }
3703 }
3704}
3705
3706static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3707 CXFile file, void *reserved) {
3708 IndexData *index_data;
3709
3710 index_data = (IndexData *)client_data;
3711 printCheck(data: index_data);
3712
3713 index_data->main_filename = clang_getFileName(SFile: file);
3714
3715 printf(format: "[enteredMainFile]: ");
3716 printCXIndexFile(file: (CXIdxClientFile)file);
3717 printf(format: "\n");
3718
3719 return (CXIdxClientFile)file;
3720}
3721
3722static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
3723 const CXIdxIncludedFileInfo *info) {
3724 IndexData *index_data;
3725 CXModule Mod;
3726 index_data = (IndexData *)client_data;
3727 printCheck(data: index_data);
3728
3729 printf(format: "[ppIncludedFile]: ");
3730 printCXIndexFile(file: (CXIdxClientFile)info->file);
3731 printf(format: " | name: \"%s\"", info->filename);
3732 printf(format: " | hash loc: ");
3733 printCXIndexLoc(loc: info->hashLoc, client_data);
3734 printf(format: " | isImport: %d | isAngled: %d | isModule: %d",
3735 info->isImport, info->isAngled, info->isModuleImport);
3736
3737 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3738 if (Mod) {
3739 CXString str = clang_Module_getFullName(Module: Mod);
3740 const char *cstr = clang_getCString(string: str);
3741 printf(format: " | module: %s", cstr);
3742 clang_disposeString(string: str);
3743 }
3744
3745 printf(format: "\n");
3746
3747 return (CXIdxClientFile)info->file;
3748}
3749
3750static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3751 const CXIdxImportedASTFileInfo *info) {
3752 IndexData *index_data;
3753 index_data = (IndexData *)client_data;
3754 printCheck(data: index_data);
3755
3756 if (index_data->importedASTs) {
3757 CXString filename = clang_getFileName(SFile: info->file);
3758 importedASTS_insert(p: index_data->importedASTs, file: clang_getCString(string: filename));
3759 clang_disposeString(string: filename);
3760 }
3761
3762 printf(format: "[importedASTFile]: ");
3763 printCXIndexFile(file: (CXIdxClientFile)info->file);
3764 if (info->module) {
3765 CXString name = clang_Module_getFullName(Module: info->module);
3766 printf(format: " | loc: ");
3767 printCXIndexLoc(loc: info->loc, client_data);
3768 printf(format: " | name: \"%s\"", clang_getCString(string: name));
3769 printf(format: " | isImplicit: %d\n", info->isImplicit);
3770 clang_disposeString(string: name);
3771 } else {
3772 /* PCH file, the rest are not relevant. */
3773 printf(format: "\n");
3774 }
3775
3776 return (CXIdxClientFile)info->file;
3777}
3778
3779static CXIdxClientContainer
3780index_startedTranslationUnit(CXClientData client_data, void *reserved) {
3781 IndexData *index_data;
3782 index_data = (IndexData *)client_data;
3783 printCheck(data: index_data);
3784
3785 printf(format: "[startedTranslationUnit]\n");
3786#ifdef __GNUC__
3787#pragma GCC diagnostic push
3788#pragma GCC diagnostic ignored "-Wcast-qual"
3789#endif
3790 return (CXIdxClientContainer)"TU";
3791#ifdef __GNUC__
3792#pragma GCC diagnostic pop
3793#endif
3794}
3795
3796static void index_indexDeclaration(CXClientData client_data,
3797 const CXIdxDeclInfo *info) {
3798 IndexData *index_data;
3799 const CXIdxObjCCategoryDeclInfo *CatInfo;
3800 const CXIdxObjCInterfaceDeclInfo *InterInfo;
3801 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
3802 const CXIdxObjCPropertyDeclInfo *PropInfo;
3803 const CXIdxCXXClassDeclInfo *CXXClassInfo;
3804 unsigned i;
3805 index_data = (IndexData *)client_data;
3806
3807 printEntityInfo(cb: "[indexDeclaration]", client_data, info: info->entityInfo);
3808 printf(format: " | cursor: ");
3809 PrintCursor(Cursor: info->cursor, NULL);
3810 printf(format: " | loc: ");
3811 printCXIndexLoc(loc: info->loc, client_data);
3812 printf(format: " | semantic-container: ");
3813 printCXIndexContainer(info: info->semanticContainer);
3814 printf(format: " | lexical-container: ");
3815 printCXIndexContainer(info: info->lexicalContainer);
3816 printf(format: " | isRedecl: %d", info->isRedeclaration);
3817 printf(format: " | isDef: %d", info->isDefinition);
3818 if (info->flags & CXIdxDeclFlag_Skipped) {
3819 assert(!info->isContainer);
3820 printf(format: " | isContainer: skipped");
3821 } else {
3822 printf(format: " | isContainer: %d", info->isContainer);
3823 }
3824 printf(format: " | isImplicit: %d\n", info->isImplicit);
3825
3826 for (i = 0; i != info->numAttributes; ++i) {
3827 const CXIdxAttrInfo *Attr = info->attributes[i];
3828 printf(format: " <attribute>: ");
3829 PrintCursor(Cursor: Attr->cursor, NULL);
3830 printf(format: "\n");
3831 }
3832
3833 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3834 const char *kindName = 0;
3835 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3836 switch (K) {
3837 case CXIdxObjCContainer_ForwardRef:
3838 kindName = "forward-ref"; break;
3839 case CXIdxObjCContainer_Interface:
3840 kindName = "interface"; break;
3841 case CXIdxObjCContainer_Implementation:
3842 kindName = "implementation"; break;
3843 }
3844 printCheck(data: index_data);
3845 printf(format: " <ObjCContainerInfo>: kind: %s\n", kindName);
3846 }
3847
3848 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
3849 printEntityInfo(cb: " <ObjCCategoryInfo>: class", client_data,
3850 info: CatInfo->objcClass);
3851 printf(format: " | cursor: ");
3852 PrintCursor(Cursor: CatInfo->classCursor, NULL);
3853 printf(format: " | loc: ");
3854 printCXIndexLoc(loc: CatInfo->classLoc, client_data);
3855 printf(format: "\n");
3856 }
3857
3858 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3859 if (InterInfo->superInfo) {
3860 printBaseClassInfo(client_data, info: InterInfo->superInfo);
3861 printf(format: "\n");
3862 }
3863 }
3864
3865 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3866 printProtocolList(ProtoInfo, client_data);
3867 }
3868
3869 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3870 if (PropInfo->getter) {
3871 printEntityInfo(cb: " <getter>", client_data, info: PropInfo->getter);
3872 printf(format: "\n");
3873 }
3874 if (PropInfo->setter) {
3875 printEntityInfo(cb: " <setter>", client_data, info: PropInfo->setter);
3876 printf(format: "\n");
3877 }
3878 }
3879
3880 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3881 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3882 printBaseClassInfo(client_data, info: CXXClassInfo->bases[i]);
3883 printf(format: "\n");
3884 }
3885 }
3886
3887 if (info->declAsContainer)
3888 clang_index_setClientContainer(
3889 info->declAsContainer,
3890 makeClientContainer(client_data, info: info->entityInfo, loc: info->loc));
3891}
3892
3893static void index_indexEntityReference(CXClientData client_data,
3894 const CXIdxEntityRefInfo *info) {
3895 printEntityInfo(cb: "[indexEntityReference]", client_data,
3896 info: info->referencedEntity);
3897 printf(format: " | cursor: ");
3898 PrintCursor(Cursor: info->cursor, NULL);
3899 printf(format: " | loc: ");
3900 printCXIndexLoc(loc: info->loc, client_data);
3901 printEntityInfo(cb: " | <parent>:", client_data, info: info->parentEntity);
3902 printf(format: " | container: ");
3903 printCXIndexContainer(info: info->container);
3904 printf(format: " | refkind: ");
3905 switch (info->kind) {
3906 case CXIdxEntityRef_Direct: printf(format: "direct"); break;
3907 case CXIdxEntityRef_Implicit: printf(format: "implicit"); break;
3908 }
3909 printf(format: " | role:");
3910 printSymbolRole(role: info->role);
3911 printf(format: "\n");
3912}
3913
3914static int index_abortQuery(CXClientData client_data, void *reserved) {
3915 IndexData *index_data;
3916 index_data = (IndexData *)client_data;
3917 return index_data->abort;
3918}
3919
3920static IndexerCallbacks IndexCB = {
3921 index_abortQuery,
3922 index_diagnostic,
3923 index_enteredMainFile,
3924 index_ppIncludedFile,
3925 index_importedASTFile,
3926 index_startedTranslationUnit,
3927 index_indexDeclaration,
3928 index_indexEntityReference
3929};
3930
3931static unsigned getIndexOptions(void) {
3932 unsigned index_opts;
3933 index_opts = 0;
3934 if (getenv(name: "CINDEXTEST_SUPPRESSREFS"))
3935 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3936 if (getenv(name: "CINDEXTEST_INDEXLOCALSYMBOLS"))
3937 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
3938 if (!getenv(name: "CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3939 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
3940 if (getenv(name: "CINDEXTEST_INDEXIMPLICITTEMPLATEINSTANTIATIONS"))
3941 index_opts |= CXIndexOpt_IndexImplicitTemplateInstantiations;
3942
3943 return index_opts;
3944}
3945
3946static int index_compile_args(int num_args, const char **args,
3947 CXIndexAction idxAction,
3948 ImportedASTFilesData *importedASTs,
3949 const char *check_prefix) {
3950 IndexData index_data;
3951 unsigned index_opts;
3952 int result;
3953
3954 if (num_args == 0) {
3955 fprintf(stderr, format: "no compiler arguments\n");
3956 return -1;
3957 }
3958
3959 index_data.check_prefix = check_prefix;
3960 index_data.first_check_printed = 0;
3961 index_data.fail_for_error = 0;
3962 index_data.abort = 0;
3963 index_data.main_filename = createCXString(CS: "");
3964 index_data.importedASTs = importedASTs;
3965 index_data.strings = NULL;
3966 index_data.TU = NULL;
3967
3968 index_opts = getIndexOptions();
3969 result = clang_indexSourceFile(idxAction, client_data: &index_data,
3970 index_callbacks: &IndexCB,index_callbacks_size: sizeof(IndexCB), index_options: index_opts,
3971 source_filename: 0, command_line_args: args, num_command_line_args: num_args, unsaved_files: 0, num_unsaved_files: 0, out_TU: 0,
3972 TU_options: getDefaultParsingOptions());
3973 if (result != CXError_Success)
3974 describeLibclangFailure(Err: result);
3975
3976 if (index_data.fail_for_error)
3977 result = -1;
3978
3979 clang_disposeString(string: index_data.main_filename);
3980 free_client_data(index_data: &index_data);
3981 return result;
3982}
3983
3984static int index_ast_file(const char *ast_file,
3985 CXIndex Idx,
3986 CXIndexAction idxAction,
3987 ImportedASTFilesData *importedASTs,
3988 const char *check_prefix) {
3989 CXTranslationUnit TU;
3990 IndexData index_data;
3991 unsigned index_opts;
3992 int result;
3993
3994 if (!CreateTranslationUnit(Idx, file: ast_file, TU: &TU))
3995 return -1;
3996
3997 index_data.check_prefix = check_prefix;
3998 index_data.first_check_printed = 0;
3999 index_data.fail_for_error = 0;
4000 index_data.abort = 0;
4001 index_data.main_filename = createCXString(CS: "");
4002 index_data.importedASTs = importedASTs;
4003 index_data.strings = NULL;
4004 index_data.TU = TU;
4005
4006 index_opts = getIndexOptions();
4007 result = clang_indexTranslationUnit(idxAction, client_data: &index_data,
4008 index_callbacks: &IndexCB,index_callbacks_size: sizeof(IndexCB),
4009 index_options: index_opts, TU);
4010 if (index_data.fail_for_error)
4011 result = -1;
4012
4013 clang_disposeTranslationUnit(TU);
4014 clang_disposeString(string: index_data.main_filename);
4015 free_client_data(index_data: &index_data);
4016 return result;
4017}
4018
4019static int index_file(int argc, const char **argv, int full) {
4020 const char *check_prefix;
4021 CXIndex Idx;
4022 CXIndexAction idxAction;
4023 ImportedASTFilesData *importedASTs;
4024 int result;
4025
4026 check_prefix = 0;
4027 if (argc > 0) {
4028 if (strstr(haystack: argv[0], needle: "-check-prefix=") == argv[0]) {
4029 check_prefix = argv[0] + strlen(s: "-check-prefix=");
4030 ++argv;
4031 --argc;
4032 }
4033 }
4034
4035 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ excludeDeclarationsFromPCH: 1,
4036 /* displayDiagnostics=*/1))) {
4037 fprintf(stderr, format: "Could not create Index\n");
4038 return 1;
4039 }
4040 idxAction = clang_IndexAction_create(CIdx: Idx);
4041 importedASTs = 0;
4042 if (full)
4043 importedASTs = importedASTs_create();
4044
4045 result = index_compile_args(num_args: argc, args: argv, idxAction, importedASTs, check_prefix);
4046 if (result != 0)
4047 goto finished;
4048
4049 if (full) {
4050 unsigned i;
4051 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
4052 result = index_ast_file(ast_file: importedASTs->filenames[i], Idx, idxAction,
4053 importedASTs, check_prefix);
4054 }
4055 }
4056
4057finished:
4058 importedASTs_dispose(p: importedASTs);
4059 clang_IndexAction_dispose(idxAction);
4060 clang_disposeIndex(index: Idx);
4061 return result;
4062}
4063
4064static int index_tu(int argc, const char **argv) {
4065 const char *check_prefix;
4066 CXIndex Idx;
4067 CXIndexAction idxAction;
4068 int result;
4069
4070 check_prefix = 0;
4071 if (argc > 0) {
4072 if (strstr(haystack: argv[0], needle: "-check-prefix=") == argv[0]) {
4073 check_prefix = argv[0] + strlen(s: "-check-prefix=");
4074 ++argv;
4075 --argc;
4076 }
4077 }
4078
4079 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ excludeDeclarationsFromPCH: 1,
4080 /* displayDiagnostics=*/1))) {
4081 fprintf(stderr, format: "Could not create Index\n");
4082 return 1;
4083 }
4084 idxAction = clang_IndexAction_create(CIdx: Idx);
4085
4086 result = index_ast_file(ast_file: argv[0], Idx, idxAction,
4087 /*importedASTs=*/0, check_prefix);
4088
4089 clang_IndexAction_dispose(idxAction);
4090 clang_disposeIndex(index: Idx);
4091 return result;
4092}
4093
4094static int index_compile_db(int argc, const char **argv) {
4095 const char *check_prefix;
4096 CXIndex Idx;
4097 CXIndexAction idxAction;
4098 int errorCode = 0;
4099
4100 check_prefix = 0;
4101 if (argc > 0) {
4102 if (strstr(haystack: argv[0], needle: "-check-prefix=") == argv[0]) {
4103 check_prefix = argv[0] + strlen(s: "-check-prefix=");
4104 ++argv;
4105 --argc;
4106 }
4107 }
4108
4109 if (argc == 0) {
4110 fprintf(stderr, format: "no compilation database\n");
4111 return -1;
4112 }
4113
4114 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ excludeDeclarationsFromPCH: 1,
4115 /* displayDiagnostics=*/1))) {
4116 fprintf(stderr, format: "Could not create Index\n");
4117 return 1;
4118 }
4119 idxAction = clang_IndexAction_create(CIdx: Idx);
4120
4121 {
4122 const char *database = argv[0];
4123 CXCompilationDatabase db = 0;
4124 CXCompileCommands CCmds = 0;
4125 CXCompileCommand CCmd;
4126 CXCompilationDatabase_Error ec;
4127 CXString wd;
4128#define MAX_COMPILE_ARGS 512
4129 CXString cxargs[MAX_COMPILE_ARGS];
4130 const char *args[MAX_COMPILE_ARGS];
4131 char *tmp;
4132 unsigned len;
4133 char *buildDir;
4134 int i, a, numCmds, numArgs;
4135
4136 len = strlen(s: database);
4137 tmp = (char *) malloc(size: len+1);
4138 assert(tmp);
4139 memcpy(dest: tmp, src: database, n: len+1);
4140 buildDir = dirname(tmp);
4141
4142 db = clang_CompilationDatabase_fromDirectory(BuildDir: buildDir, ErrorCode: &ec);
4143
4144 if (db) {
4145
4146 if (ec!=CXCompilationDatabase_NoError) {
4147 printf(format: "unexpected error %d code while loading compilation database\n", ec);
4148 errorCode = -1;
4149 goto cdb_end;
4150 }
4151
4152 if (chdir(path: buildDir) != 0) {
4153 printf(format: "Could not chdir to %s\n", buildDir);
4154 errorCode = -1;
4155 goto cdb_end;
4156 }
4157
4158 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
4159 if (!CCmds) {
4160 printf(format: "compilation db is empty\n");
4161 errorCode = -1;
4162 goto cdb_end;
4163 }
4164
4165 numCmds = clang_CompileCommands_getSize(CCmds);
4166
4167 if (numCmds==0) {
4168 fprintf(stderr, format: "should not get an empty compileCommand set\n");
4169 errorCode = -1;
4170 goto cdb_end;
4171 }
4172
4173 for (i=0; i<numCmds && errorCode == 0; ++i) {
4174 CCmd = clang_CompileCommands_getCommand(CCmds, I: i);
4175
4176 wd = clang_CompileCommand_getDirectory(CCmd);
4177 if (chdir(path: clang_getCString(string: wd)) != 0) {
4178 printf(format: "Could not chdir to %s\n", clang_getCString(string: wd));
4179 errorCode = -1;
4180 goto cdb_end;
4181 }
4182 clang_disposeString(string: wd);
4183
4184 numArgs = clang_CompileCommand_getNumArgs(CCmd);
4185 if (numArgs > MAX_COMPILE_ARGS){
4186 fprintf(stderr, format: "got more compile arguments than maximum\n");
4187 errorCode = -1;
4188 goto cdb_end;
4189 }
4190 for (a=0; a<numArgs; ++a) {
4191 cxargs[a] = clang_CompileCommand_getArg(CCmd, I: a);
4192 args[a] = clang_getCString(string: cxargs[a]);
4193 }
4194
4195 errorCode = index_compile_args(num_args: numArgs, args, idxAction,
4196 /*importedASTs=*/0, check_prefix);
4197
4198 for (a=0; a<numArgs; ++a)
4199 clang_disposeString(string: cxargs[a]);
4200 }
4201 } else {
4202 printf(format: "database loading failed with error code %d.\n", ec);
4203 errorCode = -1;
4204 }
4205
4206 cdb_end:
4207 clang_CompileCommands_dispose(CCmds);
4208 clang_CompilationDatabase_dispose(db);
4209 free(ptr: tmp);
4210
4211 }
4212
4213 clang_IndexAction_dispose(idxAction);
4214 clang_disposeIndex(index: Idx);
4215 return errorCode;
4216}
4217
4218int perform_token_annotation(int argc, const char **argv) {
4219 const char *input = argv[1];
4220 char *filename = 0;
4221 unsigned line, second_line;
4222 unsigned column, second_column;
4223 CXIndex CIdx;
4224 CXTranslationUnit TU = 0;
4225 int errorCode;
4226 struct CXUnsavedFile *unsaved_files = 0;
4227 int num_unsaved_files = 0;
4228 CXToken *tokens;
4229 unsigned num_tokens;
4230 CXSourceRange range;
4231 CXSourceLocation startLoc, endLoc;
4232 CXFile file = 0;
4233 CXCursor *cursors = 0;
4234 CXSourceRangeList *skipped_ranges = 0;
4235 enum CXErrorCode Err;
4236 unsigned i;
4237
4238 input += strlen(s: "-test-annotate-tokens=");
4239 if ((errorCode = parse_file_line_column(input, filename: &filename, line: &line, column: &column,
4240 second_line: &second_line, second_column: &second_column)))
4241 return errorCode;
4242
4243 if (parse_remapped_files(argc, argv, start_arg: 2, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
4244 free(ptr: filename);
4245 return -1;
4246 }
4247
4248 CIdx = clang_createIndex(excludeDeclarationsFromPCH: 0, displayDiagnostics: 1);
4249 Err = clang_parseTranslationUnit2(CIdx, source_filename: argv[argc - 1],
4250 command_line_args: argv + num_unsaved_files + 2,
4251 num_command_line_args: argc - num_unsaved_files - 3,
4252 unsaved_files,
4253 num_unsaved_files,
4254 options: getDefaultParsingOptions(), out_TU: &TU);
4255 if (Err != CXError_Success) {
4256 fprintf(stderr, format: "unable to parse input\n");
4257 describeLibclangFailure(Err);
4258 clang_disposeIndex(index: CIdx);
4259 free(ptr: filename);
4260 free_remapped_files(unsaved_files, num_unsaved_files);
4261 return -1;
4262 }
4263 errorCode = 0;
4264
4265 if (checkForErrors(TU) != 0) {
4266 errorCode = -1;
4267 goto teardown;
4268 }
4269
4270 if (getenv(name: "CINDEXTEST_EDITING")) {
4271 for (i = 0; i < 5; ++i) {
4272 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
4273 options: clang_defaultReparseOptions(TU));
4274 if (Err != CXError_Success) {
4275 fprintf(stderr, format: "Unable to reparse translation unit!\n");
4276 describeLibclangFailure(Err);
4277 errorCode = -1;
4278 goto teardown;
4279 }
4280 }
4281 }
4282
4283 if (checkForErrors(TU) != 0) {
4284 errorCode = -1;
4285 goto teardown;
4286 }
4287
4288 file = clang_getFile(tu: TU, file_name: filename);
4289 if (!file) {
4290 fprintf(stderr, format: "file %s is not in this translation unit\n", filename);
4291 errorCode = -1;
4292 goto teardown;
4293 }
4294
4295 startLoc = clang_getLocation(tu: TU, file, line, column);
4296 if (clang_equalLocations(loc1: clang_getNullLocation(), loc2: startLoc)) {
4297 fprintf(stderr, format: "invalid source location %s:%d:%d\n", filename, line,
4298 column);
4299 errorCode = -1;
4300 goto teardown;
4301 }
4302
4303 endLoc = clang_getLocation(tu: TU, file, line: second_line, column: second_column);
4304 if (clang_equalLocations(loc1: clang_getNullLocation(), loc2: endLoc)) {
4305 fprintf(stderr, format: "invalid source location %s:%d:%d\n", filename,
4306 second_line, second_column);
4307 errorCode = -1;
4308 goto teardown;
4309 }
4310
4311 range = clang_getRange(begin: startLoc, end: endLoc);
4312 clang_tokenize(TU, Range: range, Tokens: &tokens, NumTokens: &num_tokens);
4313
4314 if (checkForErrors(TU) != 0) {
4315 errorCode = -1;
4316 goto teardown;
4317 }
4318
4319 cursors = (CXCursor *)malloc(size: num_tokens * sizeof(CXCursor));
4320 assert(cursors);
4321 clang_annotateTokens(TU, Tokens: tokens, NumTokens: num_tokens, Cursors: cursors);
4322
4323 if (checkForErrors(TU) != 0) {
4324 errorCode = -1;
4325 goto teardown;
4326 }
4327
4328 skipped_ranges = clang_getSkippedRanges(tu: TU, file);
4329 for (i = 0; i != skipped_ranges->count; ++i) {
4330 unsigned start_line, start_column, end_line, end_column;
4331 clang_getSpellingLocation(location: clang_getRangeStart(range: skipped_ranges->ranges[i]),
4332 file: 0, line: &start_line, column: &start_column, offset: 0);
4333 clang_getSpellingLocation(location: clang_getRangeEnd(range: skipped_ranges->ranges[i]),
4334 file: 0, line: &end_line, column: &end_column, offset: 0);
4335 printf(format: "Skipping: ");
4336 PrintExtent(stdout, begin_line: start_line, begin_column: start_column, end_line, end_column);
4337 printf(format: "\n");
4338 }
4339 clang_disposeSourceRangeList(ranges: skipped_ranges);
4340
4341 for (i = 0; i != num_tokens; ++i) {
4342 const char *kind = "<unknown>";
4343 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
4344 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
4345 unsigned start_line, start_column, end_line, end_column;
4346
4347 switch (clang_getTokenKind(tokens[i])) {
4348 case CXToken_Punctuation: kind = "Punctuation"; break;
4349 case CXToken_Keyword: kind = "Keyword"; break;
4350 case CXToken_Identifier: kind = "Identifier"; break;
4351 case CXToken_Literal: kind = "Literal"; break;
4352 case CXToken_Comment: kind = "Comment"; break;
4353 }
4354 clang_getSpellingLocation(location: clang_getRangeStart(range: extent),
4355 file: 0, line: &start_line, column: &start_column, offset: 0);
4356 clang_getSpellingLocation(location: clang_getRangeEnd(range: extent),
4357 file: 0, line: &end_line, column: &end_column, offset: 0);
4358 printf(format: "%s: \"%s\" ", kind, clang_getCString(string: spelling));
4359 clang_disposeString(string: spelling);
4360 PrintExtent(stdout, begin_line: start_line, begin_column: start_column, end_line, end_column);
4361 if (!clang_isInvalid(cursors[i].kind)) {
4362 printf(format: " ");
4363 PrintCursor(Cursor: cursors[i], NULL);
4364 }
4365 printf(format: "\n");
4366 }
4367 free(ptr: cursors);
4368 clang_disposeTokens(TU, Tokens: tokens, NumTokens: num_tokens);
4369
4370 teardown:
4371 PrintDiagnostics(TU);
4372 clang_disposeTranslationUnit(TU);
4373 clang_disposeIndex(index: CIdx);
4374 free(ptr: filename);
4375 free_remapped_files(unsaved_files, num_unsaved_files);
4376 return errorCode;
4377}
4378
4379static int
4380perform_test_compilation_db(const char *database, int argc, const char **argv) {
4381 CXCompilationDatabase db;
4382 CXCompileCommands CCmds;
4383 CXCompileCommand CCmd;
4384 CXCompilationDatabase_Error ec;
4385 CXString wd;
4386 CXString arg;
4387 int errorCode = 0;
4388 char *tmp;
4389 unsigned len;
4390 char *buildDir;
4391 int i, j, a, numCmds, numArgs;
4392
4393 len = strlen(s: database);
4394 tmp = (char *) malloc(size: len+1);
4395 assert(tmp);
4396 memcpy(dest: tmp, src: database, n: len+1);
4397 buildDir = dirname(tmp);
4398
4399 db = clang_CompilationDatabase_fromDirectory(BuildDir: buildDir, ErrorCode: &ec);
4400
4401 if (db) {
4402
4403 if (ec!=CXCompilationDatabase_NoError) {
4404 printf(format: "unexpected error %d code while loading compilation database\n", ec);
4405 errorCode = -1;
4406 goto cdb_end;
4407 }
4408
4409 for (i=0; i<argc && errorCode==0; ) {
4410 if (strcmp(s1: argv[i],s2: "lookup")==0){
4411 CCmds = clang_CompilationDatabase_getCompileCommands(db, CompleteFileName: argv[i+1]);
4412
4413 if (!CCmds) {
4414 printf(format: "file %s not found in compilation db\n", argv[i+1]);
4415 errorCode = -1;
4416 break;
4417 }
4418
4419 numCmds = clang_CompileCommands_getSize(CCmds);
4420
4421 if (numCmds==0) {
4422 fprintf(stderr, format: "should not get an empty compileCommand set for file"
4423 " '%s'\n", argv[i+1]);
4424 errorCode = -1;
4425 break;
4426 }
4427
4428 for (j=0; j<numCmds; ++j) {
4429 CCmd = clang_CompileCommands_getCommand(CCmds, I: j);
4430
4431 wd = clang_CompileCommand_getDirectory(CCmd);
4432 printf(format: "workdir:'%s'", clang_getCString(string: wd));
4433 clang_disposeString(string: wd);
4434
4435 printf(format: " cmdline:'");
4436 numArgs = clang_CompileCommand_getNumArgs(CCmd);
4437 for (a=0; a<numArgs; ++a) {
4438 if (a) printf(format: " ");
4439 arg = clang_CompileCommand_getArg(CCmd, I: a);
4440 printf(format: "%s", clang_getCString(string: arg));
4441 clang_disposeString(string: arg);
4442 }
4443 printf(format: "'\n");
4444 }
4445
4446 clang_CompileCommands_dispose(CCmds);
4447
4448 i += 2;
4449 }
4450 }
4451 clang_CompilationDatabase_dispose(db);
4452 } else {
4453 printf(format: "database loading failed with error code %d.\n", ec);
4454 errorCode = -1;
4455 }
4456
4457cdb_end:
4458 free(ptr: tmp);
4459
4460 return errorCode;
4461}
4462
4463/******************************************************************************/
4464/* USR printing. */
4465/******************************************************************************/
4466
4467static int insufficient_usr(const char *kind, const char *usage) {
4468 fprintf(stderr, format: "USR for '%s' requires: %s\n", kind, usage);
4469 return 1;
4470}
4471
4472static unsigned isUSR(const char *s) {
4473 return s[0] == 'c' && s[1] == ':';
4474}
4475
4476static int not_usr(const char *s, const char *arg) {
4477 fprintf(stderr, format: "'%s' argument ('%s') is not a USR\n", s, arg);
4478 return 1;
4479}
4480
4481static void print_usr(CXString usr) {
4482 const char *s = clang_getCString(string: usr);
4483 printf(format: "%s\n", s);
4484 clang_disposeString(string: usr);
4485}
4486
4487static void display_usrs(void) {
4488 fprintf(stderr, format: "-print-usrs options:\n"
4489 " ObjCCategory <class name> <category name>\n"
4490 " ObjCClass <class name>\n"
4491 " ObjCIvar <ivar name> <class USR>\n"
4492 " ObjCMethod <selector> [0=class method|1=instance method] "
4493 "<class USR>\n"
4494 " ObjCProperty <property name> <class USR>\n"
4495 " ObjCProtocol <protocol name>\n");
4496}
4497
4498int print_usrs(const char **I, const char **E) {
4499 while (I != E) {
4500 const char *kind = *I;
4501 unsigned len = strlen(s: kind);
4502 switch (len) {
4503 case 8:
4504 if (memcmp(s1: kind, s2: "ObjCIvar", n: 8) == 0) {
4505 if (I + 2 >= E)
4506 return insufficient_usr(kind, usage: "<ivar name> <class USR>");
4507 if (!isUSR(s: I[2]))
4508 return not_usr(s: "<class USR>", arg: I[2]);
4509 else {
4510 CXString x = createCXString(CS: I[2]);
4511 print_usr(usr: clang_constructUSR_ObjCIvar(name: I[1], classUSR: x));
4512 }
4513
4514 I += 3;
4515 continue;
4516 }
4517 break;
4518 case 9:
4519 if (memcmp(s1: kind, s2: "ObjCClass", n: 9) == 0) {
4520 if (I + 1 >= E)
4521 return insufficient_usr(kind, usage: "<class name>");
4522 print_usr(usr: clang_constructUSR_ObjCClass(class_name: I[1]));
4523 I += 2;
4524 continue;
4525 }
4526 break;
4527 case 10:
4528 if (memcmp(s1: kind, s2: "ObjCMethod", n: 10) == 0) {
4529 if (I + 3 >= E)
4530 return insufficient_usr(kind, usage: "<method selector> "
4531 "[0=class method|1=instance method] <class USR>");
4532 if (!isUSR(s: I[3]))
4533 return not_usr(s: "<class USR>", arg: I[3]);
4534 else {
4535 CXString x = createCXString(CS: I[3]);
4536 print_usr(usr: clang_constructUSR_ObjCMethod(name: I[1], isInstanceMethod: atoi(nptr: I[2]), classUSR: x));
4537 }
4538 I += 4;
4539 continue;
4540 }
4541 break;
4542 case 12:
4543 if (memcmp(s1: kind, s2: "ObjCCategory", n: 12) == 0) {
4544 if (I + 2 >= E)
4545 return insufficient_usr(kind, usage: "<class name> <category name>");
4546 print_usr(usr: clang_constructUSR_ObjCCategory(class_name: I[1], category_name: I[2]));
4547 I += 3;
4548 continue;
4549 }
4550 if (memcmp(s1: kind, s2: "ObjCProtocol", n: 12) == 0) {
4551 if (I + 1 >= E)
4552 return insufficient_usr(kind, usage: "<protocol name>");
4553 print_usr(usr: clang_constructUSR_ObjCProtocol(protocol_name: I[1]));
4554 I += 2;
4555 continue;
4556 }
4557 if (memcmp(s1: kind, s2: "ObjCProperty", n: 12) == 0) {
4558 if (I + 2 >= E)
4559 return insufficient_usr(kind, usage: "<property name> <class USR>");
4560 if (!isUSR(s: I[2]))
4561 return not_usr(s: "<class USR>", arg: I[2]);
4562 else {
4563 CXString x = createCXString(CS: I[2]);
4564 print_usr(usr: clang_constructUSR_ObjCProperty(property: I[1], classUSR: x));
4565 }
4566 I += 3;
4567 continue;
4568 }
4569 break;
4570 default:
4571 break;
4572 }
4573 break;
4574 }
4575
4576 if (I != E) {
4577 fprintf(stderr, format: "Invalid USR kind: %s\n", *I);
4578 display_usrs();
4579 return 1;
4580 }
4581 return 0;
4582}
4583
4584int print_usrs_file(const char *file_name) {
4585 char line[2048];
4586 const char *args[128];
4587 unsigned numChars = 0;
4588
4589 FILE *fp = fopen(filename: file_name, modes: "r");
4590 if (!fp) {
4591 fprintf(stderr, format: "error: cannot open '%s'\n", file_name);
4592 return 1;
4593 }
4594
4595 /* This code is not really all that safe, but it works fine for testing. */
4596 while (!feof(stream: fp)) {
4597 char c = fgetc(stream: fp);
4598 if (c == '\n') {
4599 unsigned i = 0;
4600 const char *s = 0;
4601
4602 if (numChars == 0)
4603 continue;
4604
4605 line[numChars] = '\0';
4606 numChars = 0;
4607
4608 if (line[0] == '/' && line[1] == '/')
4609 continue;
4610
4611 s = strtok(s: line, delim: " ");
4612 while (s) {
4613 args[i] = s;
4614 ++i;
4615 s = strtok(s: 0, delim: " ");
4616 }
4617 if (print_usrs(I: &args[0], E: &args[i]))
4618 return 1;
4619 }
4620 else
4621 line[numChars++] = c;
4622 }
4623
4624 fclose(stream: fp);
4625 return 0;
4626}
4627
4628/******************************************************************************/
4629/* Command line processing. */
4630/******************************************************************************/
4631int write_pch_file(const char *filename, int argc, const char *argv[]) {
4632 CXIndex Idx;
4633 CXTranslationUnit TU;
4634 struct CXUnsavedFile *unsaved_files = 0;
4635 int num_unsaved_files = 0;
4636 enum CXErrorCode Err;
4637 int result = 0;
4638
4639 Idx = clang_createIndex(/* excludeDeclsFromPCH */excludeDeclarationsFromPCH: 1, /* displayDiagnostics=*/1);
4640
4641 if (parse_remapped_files(argc, argv, start_arg: 0, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
4642 clang_disposeIndex(index: Idx);
4643 return -1;
4644 }
4645
4646 Err = clang_parseTranslationUnit2(
4647 CIdx: Idx, source_filename: 0, command_line_args: argv + num_unsaved_files, num_command_line_args: argc - num_unsaved_files,
4648 unsaved_files, num_unsaved_files,
4649 options: CXTranslationUnit_Incomplete |
4650 CXTranslationUnit_DetailedPreprocessingRecord |
4651 CXTranslationUnit_ForSerialization,
4652 out_TU: &TU);
4653 if (Err != CXError_Success) {
4654 fprintf(stderr, format: "Unable to load translation unit!\n");
4655 describeLibclangFailure(Err);
4656 free_remapped_files(unsaved_files, num_unsaved_files);
4657 clang_disposeTranslationUnit(TU);
4658 clang_disposeIndex(index: Idx);
4659 return 1;
4660 }
4661
4662 switch (clang_saveTranslationUnit(TU, FileName: filename,
4663 options: clang_defaultSaveOptions(TU))) {
4664 case CXSaveError_None:
4665 break;
4666
4667 case CXSaveError_TranslationErrors:
4668 fprintf(stderr, format: "Unable to write PCH file %s: translation errors\n",
4669 filename);
4670 result = 2;
4671 break;
4672
4673 case CXSaveError_InvalidTU:
4674 fprintf(stderr, format: "Unable to write PCH file %s: invalid translation unit\n",
4675 filename);
4676 result = 3;
4677 break;
4678
4679 case CXSaveError_Unknown:
4680 default:
4681 fprintf(stderr, format: "Unable to write PCH file %s: unknown error \n", filename);
4682 result = 1;
4683 break;
4684 }
4685
4686 clang_disposeTranslationUnit(TU);
4687 free_remapped_files(unsaved_files, num_unsaved_files);
4688 clang_disposeIndex(index: Idx);
4689 return result;
4690}
4691
4692/******************************************************************************/
4693/* Serialized diagnostics. */
4694/******************************************************************************/
4695
4696static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4697 switch (error) {
4698 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4699 case CXLoadDiag_None: break;
4700 case CXLoadDiag_Unknown: return "Unknown";
4701 case CXLoadDiag_InvalidFile: return "Invalid File";
4702 }
4703 return "None";
4704}
4705
4706static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4707 switch (severity) {
4708 case CXDiagnostic_Note: return "note";
4709 case CXDiagnostic_Error: return "error";
4710 case CXDiagnostic_Fatal: return "fatal";
4711 case CXDiagnostic_Ignored: return "ignored";
4712 case CXDiagnostic_Warning: return "warning";
4713 }
4714 return "unknown";
4715}
4716
4717static void printIndent(unsigned indent) {
4718 if (indent == 0)
4719 return;
4720 fprintf(stderr, format: "+");
4721 --indent;
4722 while (indent > 0) {
4723 fprintf(stderr, format: "-");
4724 --indent;
4725 }
4726}
4727
4728static void printLocation(CXSourceLocation L) {
4729 CXFile File;
4730 CXString FileName;
4731 unsigned line, column, offset;
4732
4733 clang_getExpansionLocation(location: L, file: &File, line: &line, column: &column, offset: &offset);
4734 FileName = clang_getFileName(SFile: File);
4735
4736 fprintf(stderr, format: "%s:%d:%d", clang_getCString(string: FileName), line, column);
4737 clang_disposeString(string: FileName);
4738}
4739
4740static void printRanges(CXDiagnostic D, unsigned indent) {
4741 unsigned i, n = clang_getDiagnosticNumRanges(D);
4742
4743 for (i = 0; i < n; ++i) {
4744 CXSourceLocation Start, End;
4745 CXSourceRange SR = clang_getDiagnosticRange(Diagnostic: D, Range: i);
4746 Start = clang_getRangeStart(range: SR);
4747 End = clang_getRangeEnd(range: SR);
4748
4749 printIndent(indent);
4750 fprintf(stderr, format: "Range: ");
4751 printLocation(L: Start);
4752 fprintf(stderr, format: " ");
4753 printLocation(L: End);
4754 fprintf(stderr, format: "\n");
4755 }
4756}
4757
4758static void printFixIts(CXDiagnostic D, unsigned indent) {
4759 unsigned i, n = clang_getDiagnosticNumFixIts(Diagnostic: D);
4760 fprintf(stderr, format: "Number FIXITs = %d\n", n);
4761 for (i = 0 ; i < n; ++i) {
4762 CXSourceRange ReplacementRange;
4763 CXString text;
4764 text = clang_getDiagnosticFixIt(Diagnostic: D, FixIt: i, ReplacementRange: &ReplacementRange);
4765
4766 printIndent(indent);
4767 fprintf(stderr, format: "FIXIT: (");
4768 printLocation(L: clang_getRangeStart(range: ReplacementRange));
4769 fprintf(stderr, format: " - ");
4770 printLocation(L: clang_getRangeEnd(range: ReplacementRange));
4771 fprintf(stderr, format: "): \"%s\"\n", clang_getCString(string: text));
4772 clang_disposeString(string: text);
4773 }
4774}
4775
4776static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
4777 unsigned i, n;
4778
4779 if (!Diags)
4780 return;
4781
4782 n = clang_getNumDiagnosticsInSet(Diags);
4783 for (i = 0; i < n; ++i) {
4784 CXSourceLocation DiagLoc;
4785 CXDiagnostic D;
4786 CXFile File;
4787 CXString FileName, DiagSpelling, DiagOption, DiagCat;
4788 unsigned line, column, offset;
4789 const char *FileNameStr = 0, *DiagOptionStr = 0, *DiagCatStr = 0;
4790
4791 D = clang_getDiagnosticInSet(Diags, Index: i);
4792 DiagLoc = clang_getDiagnosticLocation(D);
4793 clang_getExpansionLocation(location: DiagLoc, file: &File, line: &line, column: &column, offset: &offset);
4794 FileName = clang_getFileName(SFile: File);
4795 FileNameStr = clang_getCString(string: FileName);
4796 DiagSpelling = clang_getDiagnosticSpelling(D);
4797
4798 printIndent(indent);
4799
4800 fprintf(stderr, format: "%s:%d:%d: %s: %s",
4801 FileNameStr ? FileNameStr : "(null)",
4802 line,
4803 column,
4804 getSeverityString(severity: clang_getDiagnosticSeverity(D)),
4805 clang_getCString(string: DiagSpelling));
4806
4807 DiagOption = clang_getDiagnosticOption(Diag: D, Disable: 0);
4808 DiagOptionStr = clang_getCString(string: DiagOption);
4809 if (DiagOptionStr) {
4810 fprintf(stderr, format: " [%s]", DiagOptionStr);
4811 }
4812
4813 DiagCat = clang_getDiagnosticCategoryText(D);
4814 DiagCatStr = clang_getCString(string: DiagCat);
4815 if (DiagCatStr) {
4816 fprintf(stderr, format: " [%s]", DiagCatStr);
4817 }
4818
4819 fprintf(stderr, format: "\n");
4820
4821 printRanges(D, indent);
4822 printFixIts(D, indent);
4823
4824 /* Print subdiagnostics. */
4825 printDiagnosticSet(Diags: clang_getChildDiagnostics(D), indent: indent+2);
4826
4827 clang_disposeString(string: FileName);
4828 clang_disposeString(string: DiagSpelling);
4829 clang_disposeString(string: DiagOption);
4830 clang_disposeString(string: DiagCat);
4831 }
4832}
4833
4834static int read_diagnostics(const char *filename) {
4835 enum CXLoadDiag_Error error;
4836 CXString errorString;
4837 CXDiagnosticSet Diags = 0;
4838
4839 Diags = clang_loadDiagnostics(file: filename, error: &error, errorString: &errorString);
4840 if (!Diags) {
4841 fprintf(stderr, format: "Trouble deserializing file (%s): %s\n",
4842 getDiagnosticCodeStr(error),
4843 clang_getCString(string: errorString));
4844 clang_disposeString(string: errorString);
4845 return 1;
4846 }
4847
4848 printDiagnosticSet(Diags, indent: 0);
4849 fprintf(stderr, format: "Number of diagnostics: %d\n",
4850 clang_getNumDiagnosticsInSet(Diags));
4851 clang_disposeDiagnosticSet(Diags);
4852 return 0;
4853}
4854
4855static int perform_print_build_session_timestamp(void) {
4856 printf(format: "%lld\n", clang_getBuildSessionTimestamp());
4857 return 0;
4858}
4859
4860static int perform_test_single_symbol_sgf(const char *input, int argc,
4861 const char *argv[]) {
4862 CXIndex Idx;
4863 CXTranslationUnit TU;
4864 CXAPISet API;
4865 struct CXUnsavedFile *unsaved_files = 0;
4866 int num_unsaved_files = 0;
4867 enum CXErrorCode Err;
4868 int result = 0;
4869 CXString SGF;
4870 const char *usr;
4871
4872 usr = input + strlen(s: "-single-symbol-sgf-for=");
4873
4874 Idx = createIndexWithInvocationEmissionPath(/* excludeDeclsFromPCH */ ExcludeDeclarationsFromPCH: 1,
4875 /* displayDiagnostics=*/DisplayDiagnostics: 0);
4876 if (!Idx)
4877 return -1;
4878
4879 if (parse_remapped_files(argc, argv, start_arg: 0, unsaved_files: &unsaved_files, num_unsaved_files: &num_unsaved_files)) {
4880 result = -1;
4881 goto dispose_index;
4882 }
4883
4884 Err = clang_parseTranslationUnit2(
4885 CIdx: Idx, source_filename: 0, command_line_args: argv + num_unsaved_files, num_command_line_args: argc - num_unsaved_files, unsaved_files,
4886 num_unsaved_files, options: getDefaultParsingOptions(), out_TU: &TU);
4887 if (Err != CXError_Success) {
4888 fprintf(stderr, format: "Unable to load translation unit!\n");
4889 describeLibclangFailure(Err);
4890 result = 1;
4891 goto free_remapped_files;
4892 }
4893
4894 Err = clang_createAPISet(tu: TU, out_api: &API);
4895 if (Err != CXError_Success) {
4896 fprintf(stderr,
4897 format: "Unable to create API Set for API information extraction!\n");
4898 result = 2;
4899 goto dispose_tu;
4900 }
4901
4902 SGF = clang_getSymbolGraphForUSR(usr, api: API);
4903 printf(format: "%s", clang_getCString(string: SGF));
4904
4905 clang_disposeString(string: SGF);
4906 clang_disposeAPISet(api: API);
4907dispose_tu:
4908 clang_disposeTranslationUnit(TU);
4909free_remapped_files:
4910 free_remapped_files(unsaved_files, num_unsaved_files);
4911dispose_index:
4912 clang_disposeIndex(index: Idx);
4913 return result;
4914}
4915
4916static void inspect_single_symbol_sgf_cursor(CXCursor Cursor) {
4917 CXSourceLocation CursorLoc;
4918 CXString SGFData;
4919 const char *SGF;
4920 unsigned line, column;
4921 CursorLoc = clang_getCursorLocation(Cursor);
4922 clang_getSpellingLocation(location: CursorLoc, file: 0, line: &line, column: &column, offset: 0);
4923
4924 SGFData = clang_getSymbolGraphForCursor(cursor: Cursor);
4925 SGF = clang_getCString(string: SGFData);
4926 if (SGF)
4927 printf(format: "%d:%d: %s\n", line, column, SGF);
4928
4929 clang_disposeString(string: SGFData);
4930}
4931
4932/******************************************************************************/
4933/* Command line processing. */
4934/******************************************************************************/
4935
4936static CXCursorVisitor GetVisitor(const char *s) {
4937 if (s[0] == '\0')
4938 return FilteredPrintingVisitor;
4939 if (strcmp(s1: s, s2: "-usrs") == 0)
4940 return USRVisitor;
4941 if (strncmp(s1: s, s2: "-memory-usage", n: 13) == 0)
4942 return GetVisitor(s: s + 13);
4943 return NULL;
4944}
4945
4946static void print_usage(void) {
4947 fprintf(stderr,
4948 format: "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
4949 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
4950 " c-index-test -cursor-at=<site> <compiler arguments>\n"
4951 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4952 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
4953 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4954 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
4955 fprintf(stderr,
4956 format: " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
4957 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
4958 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
4959 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
4960 " c-index-test -test-file-scan <AST file> <source file> "
4961 "[FileCheck prefix]\n");
4962 fprintf(stderr,
4963 format: " c-index-test -test-load-tu <AST file> <symbol filter> "
4964 "[FileCheck prefix]\n"
4965 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4966 "[FileCheck prefix]\n"
4967 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
4968 fprintf(stderr,
4969 format: " c-index-test -test-load-source-memory-usage "
4970 "<symbol filter> {<args>}*\n"
4971 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4972 " {<args>}*\n"
4973 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
4974 " c-index-test -test-load-source-usrs-memory-usage "
4975 "<symbol filter> {<args>}*\n"
4976 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4977 " c-index-test -test-inclusion-stack-source {<args>}*\n"
4978 " c-index-test -test-inclusion-stack-tu <AST file>\n");
4979 fprintf(stderr,
4980 format: " c-index-test -test-print-linkage-source {<args>}*\n"
4981 " c-index-test -test-print-visibility {<args>}*\n"
4982 " c-index-test -test-print-type {<args>}*\n"
4983 " c-index-test -test-print-type-size {<args>}*\n"
4984 " c-index-test -test-print-bitwidth {<args>}*\n"
4985 " c-index-test -test-print-target-info {<args>}*\n"
4986 " c-index-test -test-print-type-declaration {<args>}*\n"
4987 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
4988 " c-index-test -print-usr-file <file>\n");
4989 fprintf(stderr,
4990 format: " c-index-test -single-symbol-sgfs <symbol filter> {<args>*}\n"
4991 " c-index-test -single-symbol-sgf-at=<site> {<args>*}\n"
4992 " c-index-test -single-symbol-sgf-for=<usr> {<args>}*\n");
4993 fprintf(stderr,
4994 format: " c-index-test -write-pch <file> <compiler arguments>\n"
4995 " c-index-test -compilation-db [lookup <filename>] database\n");
4996 fprintf(stderr,
4997 format: " c-index-test -print-build-session-timestamp\n");
4998 fprintf(stderr,
4999 format: " c-index-test -read-diagnostics <file>\n\n");
5000 fprintf(stderr,
5001 format: " <symbol filter> values:\n%s",
5002 " all - load all symbols, including those from PCH\n"
5003 " local - load all symbols except those in PCH\n"
5004 " category - only load ObjC categories (non-PCH)\n"
5005 " interface - only load ObjC interfaces (non-PCH)\n"
5006 " protocol - only load ObjC protocols (non-PCH)\n"
5007 " function - only load functions (non-PCH)\n"
5008 " typedef - only load typdefs (non-PCH)\n"
5009 " scan-function - scan function bodies (non-PCH)\n\n");
5010}
5011
5012/***/
5013
5014int cindextest_main(int argc, const char **argv) {
5015 clang_enableStackTraces();
5016 if (argc > 2 && strcmp(s1: argv[1], s2: "-read-diagnostics") == 0)
5017 return read_diagnostics(filename: argv[2]);
5018 if (argc > 2 && strstr(haystack: argv[1], needle: "-code-completion-at=") == argv[1])
5019 return perform_code_completion(argc, argv, timing_only: 0);
5020 if (argc > 2 && strstr(haystack: argv[1], needle: "-code-completion-timing=") == argv[1])
5021 return perform_code_completion(argc, argv, timing_only: 1);
5022 if (argc > 2 && strstr(haystack: argv[1], needle: "-cursor-at=") == argv[1])
5023 return inspect_cursor_at(argc, argv, locations_flag: "-cursor-at=", handler: inspect_print_cursor);
5024 if (argc > 2 && strstr(haystack: argv[1], needle: "-evaluate-cursor-at=") == argv[1])
5025 return inspect_cursor_at(argc, argv, locations_flag: "-evaluate-cursor-at=",
5026 handler: inspect_evaluate_cursor);
5027 if (argc > 2 && strstr(haystack: argv[1], needle: "-get-macro-info-cursor-at=") == argv[1])
5028 return inspect_cursor_at(argc, argv, locations_flag: "-get-macro-info-cursor-at=",
5029 handler: inspect_macroinfo_cursor);
5030 if (argc > 2 && strstr(haystack: argv[1], needle: "-file-refs-at=") == argv[1])
5031 return find_file_refs_at(argc, argv);
5032 if (argc > 2 && strstr(haystack: argv[1], needle: "-file-includes-in=") == argv[1])
5033 return find_file_includes_in(argc, argv);
5034 if (argc > 2 && strcmp(s1: argv[1], s2: "-index-file") == 0)
5035 return index_file(argc: argc - 2, argv: argv + 2, /*full=*/0);
5036 if (argc > 2 && strcmp(s1: argv[1], s2: "-index-file-full") == 0)
5037 return index_file(argc: argc - 2, argv: argv + 2, /*full=*/1);
5038 if (argc > 2 && strcmp(s1: argv[1], s2: "-index-tu") == 0)
5039 return index_tu(argc: argc - 2, argv: argv + 2);
5040 if (argc > 2 && strcmp(s1: argv[1], s2: "-index-compile-db") == 0)
5041 return index_compile_db(argc: argc - 2, argv: argv + 2);
5042 else if (argc >= 4 && strncmp(s1: argv[1], s2: "-test-load-tu", n: 13) == 0) {
5043 CXCursorVisitor I = GetVisitor(s: argv[1] + 13);
5044 if (I)
5045 return perform_test_load_tu(file: argv[2], filter: argv[3], prefix: argc >= 5 ? argv[4] : 0, Visitor: I,
5046 NULL);
5047 }
5048 else if (argc >= 5 && strncmp(s1: argv[1], s2: "-test-load-source-reparse", n: 25) == 0){
5049 CXCursorVisitor I = GetVisitor(s: argv[1] + 25);
5050 if (I) {
5051 int trials = atoi(nptr: argv[2]);
5052 return perform_test_reparse_source(argc: argc - 4, argv: argv + 4, trials, filter: argv[3], Visitor: I,
5053 NULL);
5054 }
5055 }
5056 else if (argc >= 4 && strncmp(s1: argv[1], s2: "-test-load-source", n: 17) == 0) {
5057 CXCursorVisitor I = GetVisitor(s: argv[1] + 17);
5058
5059 PostVisitTU postVisit = 0;
5060 if (strstr(haystack: argv[1], needle: "-memory-usage"))
5061 postVisit = PrintMemoryUsage;
5062
5063 if (I)
5064 return perform_test_load_source(argc: argc - 3, argv: argv + 3, filter: argv[2], Visitor: I,
5065 PV: postVisit);
5066 }
5067 else if (argc >= 3 && strcmp(s1: argv[1], s2: "-single-file-parse") == 0)
5068 return perform_single_file_parse(filename: argv[2]);
5069 else if (argc >= 3 && strcmp(s1: argv[1], s2: "-retain-excluded-conditional-blocks") == 0)
5070 return perform_file_retain_excluded_cb(filename: argv[2]);
5071 else if (argc >= 4 && strcmp(s1: argv[1], s2: "-test-file-scan") == 0)
5072 return perform_file_scan(ast_file: argv[2], source_file: argv[3],
5073 prefix: argc >= 5 ? argv[4] : 0);
5074 else if (argc > 2 && strstr(haystack: argv[1], needle: "-test-annotate-tokens=") == argv[1])
5075 return perform_token_annotation(argc, argv);
5076 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-inclusion-stack-source") == 0)
5077 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all", NULL,
5078 PV: PrintInclusionStack);
5079 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-inclusion-stack-tu") == 0)
5080 return perform_test_load_tu(file: argv[2], filter: "all", NULL, NULL,
5081 PV: PrintInclusionStack);
5082 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-linkage-source") == 0)
5083 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all", Visitor: PrintLinkage,
5084 NULL);
5085 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-visibility") == 0)
5086 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all", Visitor: PrintVisibility,
5087 NULL);
5088 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-type") == 0)
5089 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all",
5090 Visitor: PrintType, PV: 0);
5091 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-type-size") == 0)
5092 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all",
5093 Visitor: PrintTypeSize, PV: 0);
5094 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-type-declaration") == 0)
5095 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all",
5096 Visitor: PrintTypeDeclaration, PV: 0);
5097 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-decl-attributes") == 0)
5098 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all",
5099 Visitor: PrintDeclAttributes, PV: 0);
5100 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-bitwidth") == 0)
5101 return perform_test_load_source(argc: argc - 2, argv: argv + 2, filter: "all",
5102 Visitor: PrintBitWidth, PV: 0);
5103 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-mangle") == 0)
5104 return perform_test_load_tu(file: argv[2], filter: "all", NULL, Visitor: PrintMangledName, NULL);
5105 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-manglings") == 0)
5106 return perform_test_load_tu(file: argv[2], filter: "all", NULL, Visitor: PrintManglings, NULL);
5107 else if (argc > 2 && strcmp(s1: argv[1], s2: "-test-print-target-info") == 0)
5108 return print_target_info(argc: argc - 2, argv: argv + 2);
5109 else if (argc > 1 && strcmp(s1: argv[1], s2: "-print-usr") == 0) {
5110 if (argc > 2)
5111 return print_usrs(I: argv + 2, E: argv + argc);
5112 else {
5113 display_usrs();
5114 return 1;
5115 }
5116 }
5117 else if (argc > 2 && strcmp(s1: argv[1], s2: "-print-usr-file") == 0)
5118 return print_usrs_file(file_name: argv[2]);
5119 else if (argc > 2 && strcmp(s1: argv[1], s2: "-write-pch") == 0)
5120 return write_pch_file(filename: argv[2], argc: argc - 3, argv: argv + 3);
5121 else if (argc > 2 && strcmp(s1: argv[1], s2: "-compilation-db") == 0)
5122 return perform_test_compilation_db(database: argv[argc-1], argc: argc - 3, argv: argv + 2);
5123 else if (argc == 2 && strcmp(s1: argv[1], s2: "-print-build-session-timestamp") == 0)
5124 return perform_print_build_session_timestamp();
5125 else if (argc > 3 && strcmp(s1: argv[1], s2: "-single-symbol-sgfs") == 0)
5126 return perform_test_load_source(argc: argc - 3, argv: argv + 3, filter: argv[2],
5127 Visitor: PrintSingleSymbolSGFs, NULL);
5128 else if (argc > 2 && strstr(haystack: argv[1], needle: "-single-symbol-sgf-at=") == argv[1])
5129 return inspect_cursor_at(
5130 argc, argv, locations_flag: "-single-symbol-sgf-at=", handler: inspect_single_symbol_sgf_cursor);
5131 else if (argc > 2 && strstr(haystack: argv[1], needle: "-single-symbol-sgf-for=") == argv[1])
5132 return perform_test_single_symbol_sgf(input: argv[1], argc: argc - 2, argv: argv + 2);
5133
5134 print_usage();
5135 return 1;
5136}
5137
5138/***/
5139
5140/* We intentionally run in a separate thread to ensure we at least minimal
5141 * testing of a multithreaded environment (for example, having a reduced stack
5142 * size). */
5143
5144typedef struct thread_info {
5145 int (*main_func)(int argc, const char **argv);
5146 int argc;
5147 const char **argv;
5148 int result;
5149} thread_info;
5150void thread_runner(void *client_data_v) {
5151 thread_info *client_data = client_data_v;
5152 client_data->result = client_data->main_func(client_data->argc,
5153 client_data->argv);
5154}
5155
5156static void flush_atexit(void) {
5157 /* stdout, and surprisingly even stderr, are not always flushed on process
5158 * and thread exit, particularly when the system is under heavy load. */
5159 fflush(stdout);
5160 fflush(stderr);
5161}
5162
5163int main(int argc, const char **argv) {
5164 thread_info client_data;
5165
5166#ifdef __MVS__
5167 if (enableAutoConversion(fileno(stdout)) == -1)
5168 fprintf(stderr, "Setting conversion on stdout failed\n");
5169
5170 if (enableAutoConversion(fileno(stderr)) == -1)
5171 fprintf(stderr, "Setting conversion on stderr failed\n");
5172#endif
5173
5174 atexit(func: flush_atexit);
5175
5176#ifdef CLANG_HAVE_LIBXML
5177 LIBXML_TEST_VERSION
5178#endif
5179
5180 if (argc > 1 && strcmp(s1: argv[1], s2: "core") == 0)
5181 return indextest_core_main(argc, argv);
5182
5183 client_data.main_func = cindextest_main;
5184 client_data.argc = argc;
5185 client_data.argv = argv;
5186
5187 if (getenv(name: "CINDEXTEST_NOTHREADS"))
5188 return client_data.main_func(client_data.argc, client_data.argv);
5189
5190 clang_executeOnThread(fn: thread_runner, user_data: &client_data, stack_size: 0);
5191 return client_data.result;
5192}
5193

source code of clang/tools/c-index-test/c-index-test.c