blob: 423fa9343af10c103cc0583c160b9a508a4f040a [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001/* c-index-test.c */
2
3#include "clang-c/Index.h"
4#include <stdlib.h>
5#include <stdio.h>
6#include <string.h>
7#include <assert.h>
8
9/******************************************************************************/
10/* Utility functions. */
11/******************************************************************************/
12
13#ifdef _MSC_VER
14char *basename(const char* path)
15{
16 char* base1 = (char*)strrchr(path, '/');
17 char* base2 = (char*)strrchr(path, '\\');
18 if (base1 && base2)
19 return((base1 > base2) ? base1 + 1 : base2 + 1);
20 else if (base1)
21 return(base1 + 1);
22 else if (base2)
23 return(base2 + 1);
24
25 return((char*)path);
26}
27#else
28extern char *basename(const char *);
29#endif
30
31static void PrintDiagnosticCallback(CXDiagnostic Diagnostic,
32 CXClientData ClientData);
33
34static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
35 CXTranslationUnit *TU) {
36
37 *TU = clang_createTranslationUnit(Idx, file, PrintDiagnosticCallback, 0);
38 if (!TU) {
39 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
40 return 0;
41 }
42 return 1;
43}
44
45void free_remapped_files(struct CXUnsavedFile *unsaved_files,
46 int num_unsaved_files) {
47 int i;
48 for (i = 0; i != num_unsaved_files; ++i) {
49 free((char *)unsaved_files[i].Filename);
50 free((char *)unsaved_files[i].Contents);
51 }
52}
53
54int parse_remapped_files(int argc, const char **argv, int start_arg,
55 struct CXUnsavedFile **unsaved_files,
56 int *num_unsaved_files) {
57 int i;
58 int arg;
59 int prefix_len = strlen("-remap-file=");
60 *unsaved_files = 0;
61 *num_unsaved_files = 0;
62
63 /* Count the number of remapped files. */
64 for (arg = start_arg; arg < argc; ++arg) {
65 if (strncmp(argv[arg], "-remap-file=", prefix_len))
66 break;
67
68 ++*num_unsaved_files;
69 }
70
71 if (*num_unsaved_files == 0)
72 return 0;
73
74 *unsaved_files
75 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
76 *num_unsaved_files);
77 for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) {
78 struct CXUnsavedFile *unsaved = *unsaved_files + i;
79 const char *arg_string = argv[arg] + prefix_len;
80 int filename_len;
81 char *filename;
82 char *contents;
83 FILE *to_file;
84 const char *semi = strchr(arg_string, ';');
85 if (!semi) {
86 fprintf(stderr,
87 "error: -remap-file=from;to argument is missing semicolon\n");
88 free_remapped_files(*unsaved_files, i);
89 *unsaved_files = 0;
90 *num_unsaved_files = 0;
91 return -1;
92 }
93
94 /* Open the file that we're remapping to. */
95 to_file = fopen(semi + 1, "r");
96 if (!to_file) {
97 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
98 semi + 1);
99 free_remapped_files(*unsaved_files, i);
100 *unsaved_files = 0;
101 *num_unsaved_files = 0;
102 return -1;
103 }
104
105 /* Determine the length of the file we're remapping to. */
106 fseek(to_file, 0, SEEK_END);
107 unsaved->Length = ftell(to_file);
108 fseek(to_file, 0, SEEK_SET);
109
110 /* Read the contents of the file we're remapping to. */
111 contents = (char *)malloc(unsaved->Length + 1);
112 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
113 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
114 (feof(to_file) ? "EOF" : "error"), semi + 1);
115 fclose(to_file);
116 free_remapped_files(*unsaved_files, i);
117 *unsaved_files = 0;
118 *num_unsaved_files = 0;
119 return -1;
120 }
121 contents[unsaved->Length] = 0;
122 unsaved->Contents = contents;
123
124 /* Close the file. */
125 fclose(to_file);
126
127 /* Copy the file name that we're remapping from. */
128 filename_len = semi - arg_string;
129 filename = (char *)malloc(filename_len + 1);
130 memcpy(filename, arg_string, filename_len);
131 filename[filename_len] = 0;
132 unsaved->Filename = filename;
133 }
134
135 return 0;
136}
137
138/******************************************************************************/
139/* Pretty-printing. */
140/******************************************************************************/
141
142static void PrintCursor(CXCursor Cursor) {
143 if (clang_isInvalid(Cursor.kind))
144 printf("Invalid Cursor => %s", clang_getCursorKindSpelling(Cursor.kind));
145 else {
146 CXString string;
147 CXCursor Referenced;
148 unsigned line, column;
149 string = clang_getCursorSpelling(Cursor);
150 printf("%s=%s", clang_getCursorKindSpelling(Cursor.kind),
151 clang_getCString(string));
152 clang_disposeString(string);
153
154 Referenced = clang_getCursorReferenced(Cursor);
155 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
156 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
157 clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
158 printf(":%d:%d", line, column);
159 }
160
161 if (clang_isCursorDefinition(Cursor))
162 printf(" (Definition)");
163 }
164}
165
166static const char* GetCursorSource(CXCursor Cursor) {
167 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
168 const char *source;
169 CXFile file;
170 clang_getInstantiationLocation(Loc, &file, 0, 0, 0);
171 source = clang_getFileName(file);
172 if (!source)
173 return "<invalid loc>";
174 return basename(source);
175}
176
177/******************************************************************************/
178/* Callbacks. */
179/******************************************************************************/
180
181typedef void (*PostVisitTU)(CXTranslationUnit);
182
183static void PrintDiagnosticCallback(CXDiagnostic Diagnostic,
184 CXClientData ClientData) {
185 FILE *out = (FILE *)ClientData;
186 CXFile file;
187 unsigned line, column;
188 CXString text;
189 enum CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(Diagnostic);
190
191 /* Ignore diagnostics that should be ignored. */
192 if (severity == CXDiagnostic_Ignored)
193 return;
194
195 /* Print file:line:column. */
196 clang_getInstantiationLocation(clang_getDiagnosticLocation(Diagnostic),
197 &file, &line, &column, 0);
198 if (file) {
199 unsigned i, n;
200 unsigned printed_any_ranges = 0;
201
202 fprintf(out, "%s:%d:%d:", clang_getFileName(file), line, column);
203
204 n = clang_getDiagnosticNumRanges(Diagnostic);
205 for (i = 0; i != n; ++i) {
206 CXFile start_file, end_file;
207 CXSourceRange range = clang_getDiagnosticRange(Diagnostic, i);
208
209 unsigned start_line, start_column, end_line, end_column;
210 clang_getInstantiationLocation(clang_getRangeStart(range),
211 &start_file, &start_line, &start_column,0);
212 clang_getInstantiationLocation(clang_getRangeEnd(range),
213 &end_file, &end_line, &end_column, 0);
214
215 if (start_file != end_file || start_file != file)
216 continue;
217
218 fprintf(out, "{%d:%d-%d:%d}", start_line, start_column, end_line,
219 end_column+1);
220 printed_any_ranges = 1;
221 }
222 if (printed_any_ranges)
223 fprintf(out, ":");
224
225 fprintf(out, " ");
226 }
227
228 /* Print warning/error/etc. */
229 switch (severity) {
230 case CXDiagnostic_Ignored: assert(0 && "impossible"); break;
231 case CXDiagnostic_Note: fprintf(out, "note: "); break;
232 case CXDiagnostic_Warning: fprintf(out, "warning: "); break;
233 case CXDiagnostic_Error: fprintf(out, "error: "); break;
234 case CXDiagnostic_Fatal: fprintf(out, "fatal error: "); break;
235 }
236
237 text = clang_getDiagnosticSpelling(Diagnostic);
238 if (clang_getCString(text))
239 fprintf(out, "%s\n", clang_getCString(text));
240 else
241 fprintf(out, "<no diagnostic text>\n");
242 clang_disposeString(text);
243
244 if (file) {
245 unsigned i, num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
246 for (i = 0; i != num_fixits; ++i) {
247 switch (clang_getDiagnosticFixItKind(Diagnostic, i)) {
248 case CXFixIt_Insertion: {
249 CXSourceLocation insertion_loc;
250 CXFile insertion_file;
251 unsigned insertion_line, insertion_column;
252 text = clang_getDiagnosticFixItInsertion(Diagnostic, i, &insertion_loc);
253 clang_getInstantiationLocation(insertion_loc, &insertion_file,
254 &insertion_line, &insertion_column, 0);
255 if (insertion_file == file)
256 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
257 clang_getCString(text), insertion_line, insertion_column);
258 clang_disposeString(text);
259 break;
260 }
261
262 case CXFixIt_Removal: {
263 CXFile start_file, end_file;
264 unsigned start_line, start_column, end_line, end_column;
265 CXSourceRange remove_range
266 = clang_getDiagnosticFixItRemoval(Diagnostic, i);
267 clang_getInstantiationLocation(clang_getRangeStart(remove_range),
268 &start_file, &start_line, &start_column,
269 0);
270 clang_getInstantiationLocation(clang_getRangeEnd(remove_range),
271 &end_file, &end_line, &end_column, 0);
272 if (start_file == file && end_file == file)
273 fprintf(out, "FIX-IT: Remove %d:%d-%d:%d\n",
274 start_line, start_column, end_line, end_column+1);
275 break;
276 }
277
278 case CXFixIt_Replacement: {
279 CXFile start_file, end_file;
280 unsigned start_line, start_column, end_line, end_column;
281 CXSourceRange remove_range;
282 text = clang_getDiagnosticFixItReplacement(Diagnostic, i,&remove_range);
283 clang_getInstantiationLocation(clang_getRangeStart(remove_range),
284 &start_file, &start_line, &start_column,
285 0);
286 clang_getInstantiationLocation(clang_getRangeEnd(remove_range),
287 &end_file, &end_line, &end_column, 0);
288 if (start_file == end_file)
289 fprintf(out, "FIX-IT: Replace %d:%d-%d:%d with \"%s\"\n",
290 start_line, start_column, end_line, end_column+1,
291 clang_getCString(text));
292 clang_disposeString(text);
293 break;
294 }
295 }
296 }
297 }
298}
299
300/******************************************************************************/
301/* Logic for testing traversal. */
302/******************************************************************************/
303
304static const char *FileCheckPrefix = "CHECK";
305
306static void PrintCursorExtent(CXCursor C) {
307 CXSourceRange extent = clang_getCursorExtent(C);
308 CXFile begin_file, end_file;
309 unsigned begin_line, begin_column, end_line, end_column;
310
311 clang_getInstantiationLocation(clang_getRangeStart(extent),
312 &begin_file, &begin_line, &begin_column, 0);
313 clang_getInstantiationLocation(clang_getRangeEnd(extent),
314 &end_file, &end_line, &end_column, 0);
315 if (!begin_file || !end_file)
316 return;
317
318 printf(" [Extent=%d:%d:%d:%d]", begin_line, begin_column,
319 end_line, end_column);
320}
321
322/* Data used by all of the visitors. */
323typedef struct {
324 CXTranslationUnit TU;
325 enum CXCursorKind *Filter;
326} VisitorData;
327
328
329enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
330 CXCursor Parent,
331 CXClientData ClientData) {
332 VisitorData *Data = (VisitorData *)ClientData;
333 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
334 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
335 unsigned line, column;
336 clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
337 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
338 GetCursorSource(Cursor), line, column);
339 PrintCursor(Cursor);
340 PrintCursorExtent(Cursor);
341 printf("\n");
342 return CXChildVisit_Recurse;
343 }
344
345 return CXChildVisit_Continue;
346}
347
348static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
349 CXCursor Parent,
350 CXClientData ClientData) {
351 const char *startBuf, *endBuf;
352 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
353 CXCursor Ref;
354 VisitorData *Data = (VisitorData *)ClientData;
355
356 if (Cursor.kind != CXCursor_FunctionDecl ||
357 !clang_isCursorDefinition(Cursor))
358 return CXChildVisit_Continue;
359
360 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
361 &startLine, &startColumn,
362 &endLine, &endColumn);
363 /* Probe the entire body, looking for both decls and refs. */
364 curLine = startLine;
365 curColumn = startColumn;
366
367 while (startBuf < endBuf) {
368 CXSourceLocation Loc;
369 CXFile file;
370 const char *source = 0;
371
372 if (*startBuf == '\n') {
373 startBuf++;
374 curLine++;
375 curColumn = 1;
376 } else if (*startBuf != '\t')
377 curColumn++;
378
379 Loc = clang_getCursorLocation(Cursor);
380 clang_getInstantiationLocation(Loc, &file, 0, 0, 0);
381 source = clang_getFileName(file);
382 if (source) {
383 CXSourceLocation RefLoc
384 = clang_getLocation(Data->TU, file, curLine, curColumn);
385 Ref = clang_getCursor(Data->TU, RefLoc);
386 if (Ref.kind == CXCursor_NoDeclFound) {
387 /* Nothing found here; that's fine. */
388 } else if (Ref.kind != CXCursor_FunctionDecl) {
389 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
390 curLine, curColumn);
391 PrintCursor(Ref);
392 printf("\n");
393 }
394 }
395 startBuf++;
396 }
397
398 return CXChildVisit_Continue;
399}
400
401/******************************************************************************/
402/* USR testing. */
403/******************************************************************************/
404
405enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
406 CXClientData ClientData) {
407 VisitorData *Data = (VisitorData *)ClientData;
408 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
409 CXString USR = clang_getCursorUSR(C);
410 if (!USR.Spelling) {
411 clang_disposeString(USR);
412 return CXChildVisit_Continue;
413 }
414 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), USR.Spelling);
415 PrintCursorExtent(C);
416 printf("\n");
417 clang_disposeString(USR);
418
419 return CXChildVisit_Recurse;
420 }
421
422 return CXChildVisit_Continue;
423}
424
425/******************************************************************************/
426/* Inclusion stack testing. */
427/******************************************************************************/
428
429void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
430 unsigned includeStackLen, CXClientData data) {
431
432 unsigned i;
433 printf("file: %s\nincluded by:\n", clang_getFileName(includedFile));
434 for (i = 0; i < includeStackLen; ++i) {
435 CXFile includingFile;
436 unsigned line, column;
437 clang_getInstantiationLocation(includeStack[i], &includingFile, &line,
438 &column, 0);
439 printf(" %s:%d:%d\n", clang_getFileName(includingFile), line, column);
440 }
441 printf("\n");
442}
443
444void PrintInclusionStack(CXTranslationUnit TU) {
445 clang_getInclusions(TU, InclusionVisitor, NULL);
446}
447
448/******************************************************************************/
449/* Loading ASTs/source. */
450/******************************************************************************/
451
452static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
453 const char *filter, const char *prefix,
454 CXCursorVisitor Visitor,
455 PostVisitTU PV) {
456
457 if (prefix)
458 FileCheckPrefix = prefix;
459
460 if (Visitor) {
461 enum CXCursorKind K = CXCursor_NotImplemented;
462 enum CXCursorKind *ck = &K;
463 VisitorData Data;
464
465 /* Perform some simple filtering. */
466 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
467 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
468 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
469 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
470 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
471 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
472 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
473 else {
474 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
475 return 1;
476 }
477
478 Data.TU = TU;
479 Data.Filter = ck;
480 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
481 }
482
483 if (PV)
484 PV(TU);
485
486 clang_disposeTranslationUnit(TU);
487 return 0;
488}
489
490int perform_test_load_tu(const char *file, const char *filter,
491 const char *prefix, CXCursorVisitor Visitor,
492 PostVisitTU PV) {
493 CXIndex Idx;
494 CXTranslationUnit TU;
495 Idx = clang_createIndex(/* excludeDeclsFromPCH */
496 !strcmp(filter, "local") ? 1 : 0);
497
498 if (!CreateTranslationUnit(Idx, file, &TU))
499 return 1;
500
501 return perform_test_load(Idx, TU, filter, prefix, Visitor, PV);
502}
503
504int perform_test_load_source(int argc, const char **argv,
505 const char *filter, CXCursorVisitor Visitor,
506 PostVisitTU PV) {
507 const char *UseExternalASTs =
508 getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION");
509 CXIndex Idx;
510 CXTranslationUnit TU;
511 struct CXUnsavedFile *unsaved_files = 0;
512 int num_unsaved_files = 0;
513 int result;
514
515 Idx = clang_createIndex(/* excludeDeclsFromPCH */
516 !strcmp(filter, "local") ? 1 : 0);
517
518 if (UseExternalASTs && strlen(UseExternalASTs))
519 clang_setUseExternalASTGeneration(Idx, 1);
520
521 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files))
522 return -1;
523
524 TU = clang_createTranslationUnitFromSourceFile(Idx, 0,
525 argc - num_unsaved_files,
526 argv + num_unsaved_files,
527 num_unsaved_files,
528 unsaved_files,
529 PrintDiagnosticCallback,
530 stderr);
531 if (!TU) {
532 fprintf(stderr, "Unable to load translation unit!\n");
533 return 1;
534 }
535
536 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
537 free_remapped_files(unsaved_files, num_unsaved_files);
538 return result;
539}
540
541/******************************************************************************/
542/* Logic for testing clang_getCursor(). */
543/******************************************************************************/
544
545static void print_cursor_file_scan(CXCursor cursor,
546 unsigned start_line, unsigned start_col,
547 unsigned end_line, unsigned end_col,
548 const char *prefix) {
549 printf("// %s: ", FileCheckPrefix);
550 if (prefix)
551 printf("-%s", prefix);
552 printf("{start_line=%d start_col=%d end_line=%d end_col=%d} ",
553 start_line, start_col, end_line, end_col);
554 PrintCursor(cursor);
555 printf("\n");
556}
557
558static int perform_file_scan(const char *ast_file, const char *source_file,
559 const char *prefix) {
560 CXIndex Idx;
561 CXTranslationUnit TU;
562 FILE *fp;
563 unsigned line;
564 CXCursor prevCursor;
565 CXFile file;
566 unsigned printed;
567 unsigned start_line, start_col, last_line, last_col;
568 size_t i;
569
570 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1))) {
571 fprintf(stderr, "Could not create Index\n");
572 return 1;
573 }
574
575 if (!CreateTranslationUnit(Idx, ast_file, &TU))
576 return 1;
577
578 if ((fp = fopen(source_file, "r")) == NULL) {
579 fprintf(stderr, "Could not open '%s'\n", source_file);
580 return 1;
581 }
582
583 line = 0;
584 prevCursor = clang_getNullCursor();
585 printed = 0;
586 start_line = last_line = 1;
587 start_col = last_col = 1;
588
589 file = clang_getFile(TU, source_file);
590 while (!feof(fp)) {
591 size_t len = 0;
592 int c;
593
594 while ((c = fgetc(fp)) != EOF) {
595 len++;
596 if (c == '\n')
597 break;
598 }
599
600 ++line;
601
602 for (i = 0; i < len ; ++i) {
603 CXCursor cursor;
604 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, i+1));
605
606 if (!clang_equalCursors(cursor, prevCursor) &&
607 prevCursor.kind != CXCursor_InvalidFile) {
608 print_cursor_file_scan(prevCursor, start_line, start_col,
609 last_line, last_col, prefix);
610 printed = 1;
611 start_line = line;
612 start_col = (unsigned) i+1;
613 }
614 else {
615 printed = 0;
616 }
617
618 prevCursor = cursor;
619 last_line = line;
620 last_col = (unsigned) i+1;
621 }
622 }
623
624 if (!printed && prevCursor.kind != CXCursor_InvalidFile) {
625 print_cursor_file_scan(prevCursor, start_line, start_col,
626 last_line, last_col, prefix);
627 }
628
629 fclose(fp);
630 return 0;
631}
632
633/******************************************************************************/
634/* Logic for testing clang_codeComplete(). */
635/******************************************************************************/
636
637/* Parse file:line:column from the input string. Returns 0 on success, non-zero
638 on failure. If successful, the pointer *filename will contain newly-allocated
639 memory (that will be owned by the caller) to store the file name. */
640int parse_file_line_column(const char *input, char **filename, unsigned *line,
641 unsigned *column, unsigned *second_line,
642 unsigned *second_column) {
643 /* Find the second colon. */
644 const char *last_colon = strrchr(input, ':');
645 unsigned values[4], i;
646 unsigned num_values = (second_line && second_column)? 4 : 2;
647
648 char *endptr = 0;
649 if (!last_colon || last_colon == input) {
650 if (num_values == 4)
651 fprintf(stderr, "could not parse filename:line:column:line:column in "
652 "'%s'\n", input);
653 else
654 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
655 return 1;
656 }
657
658 for (i = 0; i != num_values; ++i) {
659 const char *prev_colon;
660
661 /* Parse the next line or column. */
662 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
663 if (*endptr != 0 && *endptr != ':') {
664 fprintf(stderr, "could not parse %s in '%s'\n",
665 (i % 2 ? "column" : "line"), input);
666 return 1;
667 }
668
669 if (i + 1 == num_values)
670 break;
671
672 /* Find the previous colon. */
673 prev_colon = last_colon - 1;
674 while (prev_colon != input && *prev_colon != ':')
675 --prev_colon;
676 if (prev_colon == input) {
677 fprintf(stderr, "could not parse %s in '%s'\n",
678 (i % 2 == 0? "column" : "line"), input);
679 return 1;
680 }
681
682 last_colon = prev_colon;
683 }
684
685 *line = values[0];
686 *column = values[1];
687
688 if (second_line && second_column) {
689 *second_line = values[2];
690 *second_column = values[3];
691 }
692
693 /* Copy the file name. */
694 *filename = (char*)malloc(last_colon - input + 1);
695 memcpy(*filename, input, last_colon - input);
696 (*filename)[last_colon - input] = 0;
697 return 0;
698}
699
700const char *
701clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
702 switch (Kind) {
703 case CXCompletionChunk_Optional: return "Optional";
704 case CXCompletionChunk_TypedText: return "TypedText";
705 case CXCompletionChunk_Text: return "Text";
706 case CXCompletionChunk_Placeholder: return "Placeholder";
707 case CXCompletionChunk_Informative: return "Informative";
708 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
709 case CXCompletionChunk_LeftParen: return "LeftParen";
710 case CXCompletionChunk_RightParen: return "RightParen";
711 case CXCompletionChunk_LeftBracket: return "LeftBracket";
712 case CXCompletionChunk_RightBracket: return "RightBracket";
713 case CXCompletionChunk_LeftBrace: return "LeftBrace";
714 case CXCompletionChunk_RightBrace: return "RightBrace";
715 case CXCompletionChunk_LeftAngle: return "LeftAngle";
716 case CXCompletionChunk_RightAngle: return "RightAngle";
717 case CXCompletionChunk_Comma: return "Comma";
718 case CXCompletionChunk_ResultType: return "ResultType";
719 case CXCompletionChunk_Colon: return "Colon";
720 case CXCompletionChunk_SemiColon: return "SemiColon";
721 case CXCompletionChunk_Equal: return "Equal";
722 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
723 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
724 }
725
726 return "Unknown";
727}
728
729void print_completion_string(CXCompletionString completion_string, FILE *file) {
730 int I, N;
731
732 N = clang_getNumCompletionChunks(completion_string);
733 for (I = 0; I != N; ++I) {
734 const char *text = 0;
735 enum CXCompletionChunkKind Kind
736 = clang_getCompletionChunkKind(completion_string, I);
737
738 if (Kind == CXCompletionChunk_Optional) {
739 fprintf(file, "{Optional ");
740 print_completion_string(
741 clang_getCompletionChunkCompletionString(completion_string, I),
742 file);
743 fprintf(file, "}");
744 continue;
745 }
746
747 text = clang_getCompletionChunkText(completion_string, I);
748 fprintf(file, "{%s %s}",
749 clang_getCompletionChunkKindSpelling(Kind),
750 text? text : "");
751 }
752}
753
754void print_completion_result(CXCompletionResult *completion_result,
755 CXClientData client_data) {
756 FILE *file = (FILE *)client_data;
757 fprintf(file, "%s:",
758 clang_getCursorKindSpelling(completion_result->CursorKind));
759 print_completion_string(completion_result->CompletionString, file);
760 fprintf(file, "\n");
761}
762
763int perform_code_completion(int argc, const char **argv) {
764 const char *input = argv[1];
765 char *filename = 0;
766 unsigned line;
767 unsigned column;
768 CXIndex CIdx;
769 int errorCode;
770 struct CXUnsavedFile *unsaved_files = 0;
771 int num_unsaved_files = 0;
772 CXCodeCompleteResults *results = 0;
773
774 input += strlen("-code-completion-at=");
775 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
776 0, 0)))
777 return errorCode;
778
779 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
780 return -1;
781
782 CIdx = clang_createIndex(0);
783 results = clang_codeComplete(CIdx,
784 argv[argc - 1], argc - num_unsaved_files - 3,
785 argv + num_unsaved_files + 2,
786 num_unsaved_files, unsaved_files,
787 filename, line, column,
788 PrintDiagnosticCallback, stderr);
789
790 if (results) {
791 unsigned i, n = results->NumResults;
792 for (i = 0; i != n; ++i)
793 print_completion_result(results->Results + i, stdout);
794 clang_disposeCodeCompleteResults(results);
795 }
796
797 clang_disposeIndex(CIdx);
798 free(filename);
799
800 free_remapped_files(unsaved_files, num_unsaved_files);
801
802 return 0;
803}
804
805typedef struct {
806 char *filename;
807 unsigned line;
808 unsigned column;
809} CursorSourceLocation;
810
811int inspect_cursor_at(int argc, const char **argv) {
812 CXIndex CIdx;
813 int errorCode;
814 struct CXUnsavedFile *unsaved_files = 0;
815 int num_unsaved_files = 0;
816 CXTranslationUnit TU;
817 CXCursor Cursor;
818 CursorSourceLocation *Locations = 0;
819 unsigned NumLocations = 0, Loc;
820
821 /* Count the number of locations. */
822 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
823 ++NumLocations;
824
825 /* Parse the locations. */
826 assert(NumLocations > 0 && "Unable to count locations?");
827 Locations = (CursorSourceLocation *)malloc(
828 NumLocations * sizeof(CursorSourceLocation));
829 for (Loc = 0; Loc < NumLocations; ++Loc) {
830 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
831 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
832 &Locations[Loc].line,
833 &Locations[Loc].column, 0, 0)))
834 return errorCode;
835 }
836
837 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
838 &num_unsaved_files))
839 return -1;
840
841 CIdx = clang_createIndex(0);
842 TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
843 argc - num_unsaved_files - 2 - NumLocations,
844 argv + num_unsaved_files + 1 + NumLocations,
845 num_unsaved_files,
846 unsaved_files,
847 PrintDiagnosticCallback,
848 stderr);
849 if (!TU) {
850 fprintf(stderr, "unable to parse input\n");
851 return -1;
852 }
853
854 for (Loc = 0; Loc < NumLocations; ++Loc) {
855 CXFile file = clang_getFile(TU, Locations[Loc].filename);
856 if (!file)
857 continue;
858
859 Cursor = clang_getCursor(TU,
860 clang_getLocation(TU, file, Locations[Loc].line,
861 Locations[Loc].column));
862 PrintCursor(Cursor);
863 printf("\n");
864 free(Locations[Loc].filename);
865 }
866
867 clang_disposeTranslationUnit(TU);
868 clang_disposeIndex(CIdx);
869 free(Locations);
870 free_remapped_files(unsaved_files, num_unsaved_files);
871 return 0;
872}
873
874int perform_token_annotation(int argc, const char **argv) {
875 const char *input = argv[1];
876 char *filename = 0;
877 unsigned line, second_line;
878 unsigned column, second_column;
879 CXIndex CIdx;
880 CXTranslationUnit TU = 0;
881 int errorCode;
882 struct CXUnsavedFile *unsaved_files = 0;
883 int num_unsaved_files = 0;
884 CXToken *tokens;
885 unsigned num_tokens;
886 CXSourceRange range;
887 CXSourceLocation startLoc, endLoc;
888 CXFile file = 0;
889 CXCursor *cursors = 0;
890 unsigned i;
891
892 input += strlen("-test-annotate-tokens=");
893 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
894 &second_line, &second_column)))
895 return errorCode;
896
897 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
898 return -1;
899
900 CIdx = clang_createIndex(0);
901 TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
902 argc - num_unsaved_files - 3,
903 argv + num_unsaved_files + 2,
904 num_unsaved_files,
905 unsaved_files,
906 PrintDiagnosticCallback,
907 stderr);
908 if (!TU) {
909 fprintf(stderr, "unable to parse input\n");
910 clang_disposeIndex(CIdx);
911 free(filename);
912 free_remapped_files(unsaved_files, num_unsaved_files);
913 return -1;
914 }
915 errorCode = 0;
916
917 file = clang_getFile(TU, filename);
918 if (!file) {
919 fprintf(stderr, "file %s is not in this translation unit\n", filename);
920 errorCode = -1;
921 goto teardown;
922 }
923
924 startLoc = clang_getLocation(TU, file, line, column);
925 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
926 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
927 column);
928 errorCode = -1;
929 goto teardown;
930 }
931
932 endLoc = clang_getLocation(TU, file, second_line, second_column);
933 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
934 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
935 second_line, second_column);
936 errorCode = -1;
937 goto teardown;
938 }
939
940 range = clang_getRange(startLoc, endLoc);
941 clang_tokenize(TU, range, &tokens, &num_tokens);
942 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
943 clang_annotateTokens(TU, tokens, num_tokens, cursors);
944 for (i = 0; i != num_tokens; ++i) {
945 const char *kind = "<unknown>";
946 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
947 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
948 unsigned start_line, start_column, end_line, end_column;
949
950 switch (clang_getTokenKind(tokens[i])) {
951 case CXToken_Punctuation: kind = "Punctuation"; break;
952 case CXToken_Keyword: kind = "Keyword"; break;
953 case CXToken_Identifier: kind = "Identifier"; break;
954 case CXToken_Literal: kind = "Literal"; break;
955 case CXToken_Comment: kind = "Comment"; break;
956 }
957 clang_getInstantiationLocation(clang_getRangeStart(extent),
958 0, &start_line, &start_column, 0);
959 clang_getInstantiationLocation(clang_getRangeEnd(extent),
960 0, &end_line, &end_column, 0);
961 printf("%s: \"%s\" [%d:%d - %d:%d]", kind, clang_getCString(spelling),
962 start_line, start_column, end_line, end_column);
963 if (!clang_isInvalid(cursors[i].kind)) {
964 printf(" ");
965 PrintCursor(cursors[i]);
966 }
967 printf("\n");
968 }
969 free(cursors);
970
971 teardown:
972 clang_disposeTranslationUnit(TU);
973 clang_disposeIndex(CIdx);
974 free(filename);
975 free_remapped_files(unsaved_files, num_unsaved_files);
976 return errorCode;
977}
978
979/******************************************************************************/
980/* Command line processing. */
981/******************************************************************************/
982
983static CXCursorVisitor GetVisitor(const char *s) {
984 if (s[0] == '\0')
985 return FilteredPrintingVisitor;
986 if (strcmp(s, "-usrs") == 0)
987 return USRVisitor;
988 return NULL;
989}
990
991static void print_usage(void) {
992 fprintf(stderr,
993 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
994 " c-index-test -cursor-at=<site> <compiler arguments>\n"
995 " c-index-test -test-file-scan <AST file> <source file> "
996 "[FileCheck prefix]\n"
997 " c-index-test -test-load-tu <AST file> <symbol filter> "
998 "[FileCheck prefix]\n"
999 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
1000 "[FileCheck prefix]\n"
1001 " c-index-test -test-load-source <symbol filter> {<args>}*\n"
1002 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n");
1003 fprintf(stderr,
1004 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
1005 " c-index-test -test-inclusion-stack-source {<args>}*\n"
1006 " c-index-test -test-inclusion-stack-tu <AST file>\n\n"
1007 " <symbol filter> values:\n%s",
1008 " all - load all symbols, including those from PCH\n"
1009 " local - load all symbols except those in PCH\n"
1010 " category - only load ObjC categories (non-PCH)\n"
1011 " interface - only load ObjC interfaces (non-PCH)\n"
1012 " protocol - only load ObjC protocols (non-PCH)\n"
1013 " function - only load functions (non-PCH)\n"
1014 " typedef - only load typdefs (non-PCH)\n"
1015 " scan-function - scan function bodies (non-PCH)\n\n");
1016}
1017
1018int main(int argc, const char **argv) {
1019 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
1020 return perform_code_completion(argc, argv);
1021 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
1022 return inspect_cursor_at(argc, argv);
1023 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
1024 CXCursorVisitor I = GetVisitor(argv[1] + 13);
1025 if (I)
1026 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
1027 NULL);
1028 }
1029 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
1030 CXCursorVisitor I = GetVisitor(argv[1] + 17);
1031 if (I)
1032 return perform_test_load_source(argc - 3, argv + 3, argv[2], I, NULL);
1033 }
1034 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
1035 return perform_file_scan(argv[2], argv[3],
1036 argc >= 5 ? argv[4] : 0);
1037 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
1038 return perform_token_annotation(argc, argv);
1039 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
1040 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
1041 PrintInclusionStack);
1042 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
1043 return perform_test_load_tu(argv[2], "all", NULL, NULL,
1044 PrintInclusionStack);
1045
1046 print_usage();
1047 return 1;
1048}