Bug Summary

File:build/source/clang/tools/c-index-test/c-index-test.c
Warning:line 2190, column 9
Null pointer passed to 1st parameter expecting 'nonnull'

Annotated Source Code

Press '?' to see keyboard shortcuts

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