Bug Summary

File:clang/tools/c-index-test/c-index-test.c
Warning:line 3331, column 5
Potential leak of memory pointed to by 'Filenames'

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