Bug Summary

File:build/source/clang/tools/c-index-test/c-index-test.c
Warning:line 2725, column 13
Potential leak of memory pointed to by 'filename'

Annotated Source Code

Press '?' to see keyboard shortcuts

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