c-index-test.c revision 25d9b00ab0b128d651d993c38726a00cd9969124
1/* c-index-test.c */
2
3#include "clang-c/Index.h"
4#include <ctype.h>
5#include <stdlib.h>
6#include <stdio.h>
7#include <string.h>
8#include <assert.h>
9
10/******************************************************************************/
11/* Utility functions.                                                         */
12/******************************************************************************/
13
14#ifdef _MSC_VER
15char *basename(const char* path)
16{
17    char* base1 = (char*)strrchr(path, '/');
18    char* base2 = (char*)strrchr(path, '\\');
19    if (base1 && base2)
20        return((base1 > base2) ? base1 + 1 : base2 + 1);
21    else if (base1)
22        return(base1 + 1);
23    else if (base2)
24        return(base2 + 1);
25
26    return((char*)path);
27}
28#else
29extern char *basename(const char *);
30#endif
31
32/** \brief Return the default parsing options. */
33static unsigned getDefaultParsingOptions() {
34  unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
35
36  if (getenv("CINDEXTEST_EDITING"))
37    options |= clang_defaultEditingTranslationUnitOptions();
38  if (getenv("CINDEXTEST_COMPLETION_CACHING"))
39    options |= CXTranslationUnit_CacheCompletionResults;
40
41  return options;
42}
43
44static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
45                        unsigned end_line, unsigned end_column) {
46  fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
47          end_line, end_column);
48}
49
50static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
51                                      CXTranslationUnit *TU) {
52
53  *TU = clang_createTranslationUnit(Idx, file);
54  if (!*TU) {
55    fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
56    return 0;
57  }
58  return 1;
59}
60
61void free_remapped_files(struct CXUnsavedFile *unsaved_files,
62                         int num_unsaved_files) {
63  int i;
64  for (i = 0; i != num_unsaved_files; ++i) {
65    free((char *)unsaved_files[i].Filename);
66    free((char *)unsaved_files[i].Contents);
67  }
68  free(unsaved_files);
69}
70
71int parse_remapped_files(int argc, const char **argv, int start_arg,
72                         struct CXUnsavedFile **unsaved_files,
73                         int *num_unsaved_files) {
74  int i;
75  int arg;
76  int prefix_len = strlen("-remap-file=");
77  *unsaved_files = 0;
78  *num_unsaved_files = 0;
79
80  /* Count the number of remapped files. */
81  for (arg = start_arg; arg < argc; ++arg) {
82    if (strncmp(argv[arg], "-remap-file=", prefix_len))
83      break;
84
85    ++*num_unsaved_files;
86  }
87
88  if (*num_unsaved_files == 0)
89    return 0;
90
91  *unsaved_files
92    = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
93                                     *num_unsaved_files);
94  for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) {
95    struct CXUnsavedFile *unsaved = *unsaved_files + i;
96    const char *arg_string = argv[arg] + prefix_len;
97    int filename_len;
98    char *filename;
99    char *contents;
100    FILE *to_file;
101    const char *semi = strchr(arg_string, ';');
102    if (!semi) {
103      fprintf(stderr,
104              "error: -remap-file=from;to argument is missing semicolon\n");
105      free_remapped_files(*unsaved_files, i);
106      *unsaved_files = 0;
107      *num_unsaved_files = 0;
108      return -1;
109    }
110
111    /* Open the file that we're remapping to. */
112    to_file = fopen(semi + 1, "r");
113    if (!to_file) {
114      fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
115              semi + 1);
116      free_remapped_files(*unsaved_files, i);
117      *unsaved_files = 0;
118      *num_unsaved_files = 0;
119      return -1;
120    }
121
122    /* Determine the length of the file we're remapping to. */
123    fseek(to_file, 0, SEEK_END);
124    unsaved->Length = ftell(to_file);
125    fseek(to_file, 0, SEEK_SET);
126
127    /* Read the contents of the file we're remapping to. */
128    contents = (char *)malloc(unsaved->Length + 1);
129    if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
130      fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
131              (feof(to_file) ? "EOF" : "error"), semi + 1);
132      fclose(to_file);
133      free_remapped_files(*unsaved_files, i);
134      *unsaved_files = 0;
135      *num_unsaved_files = 0;
136      return -1;
137    }
138    contents[unsaved->Length] = 0;
139    unsaved->Contents = contents;
140
141    /* Close the file. */
142    fclose(to_file);
143
144    /* Copy the file name that we're remapping from. */
145    filename_len = semi - arg_string;
146    filename = (char *)malloc(filename_len + 1);
147    memcpy(filename, arg_string, filename_len);
148    filename[filename_len] = 0;
149    unsaved->Filename = filename;
150  }
151
152  return 0;
153}
154
155/******************************************************************************/
156/* Pretty-printing.                                                           */
157/******************************************************************************/
158
159static void PrintCursor(CXCursor Cursor) {
160  if (clang_isInvalid(Cursor.kind)) {
161    CXString ks = clang_getCursorKindSpelling(Cursor.kind);
162    printf("Invalid Cursor => %s", clang_getCString(ks));
163    clang_disposeString(ks);
164  }
165  else {
166    CXString string, ks;
167    CXCursor Referenced;
168    unsigned line, column;
169    CXCursor SpecializationOf;
170
171    ks = clang_getCursorKindSpelling(Cursor.kind);
172    string = clang_getCursorSpelling(Cursor);
173    printf("%s=%s", clang_getCString(ks),
174                    clang_getCString(string));
175    clang_disposeString(ks);
176    clang_disposeString(string);
177
178    Referenced = clang_getCursorReferenced(Cursor);
179    if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
180      if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
181        unsigned I, N = clang_getNumOverloadedDecls(Referenced);
182        printf("[");
183        for (I = 0; I != N; ++I) {
184          CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
185          CXSourceLocation Loc;
186          if (I)
187            printf(", ");
188
189          Loc = clang_getCursorLocation(Ovl);
190          clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
191          printf("%d:%d", line, column);
192        }
193        printf("]");
194      } else {
195        CXSourceLocation Loc = clang_getCursorLocation(Referenced);
196        clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
197        printf(":%d:%d", line, column);
198      }
199    }
200
201    if (clang_isCursorDefinition(Cursor))
202      printf(" (Definition)");
203
204    switch (clang_getCursorAvailability(Cursor)) {
205      case CXAvailability_Available:
206        break;
207
208      case CXAvailability_Deprecated:
209        printf(" (deprecated)");
210        break;
211
212      case CXAvailability_NotAvailable:
213        printf(" (unavailable)");
214        break;
215    }
216
217    if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
218      CXType T =
219        clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
220      CXString S = clang_getTypeKindSpelling(T.kind);
221      printf(" [IBOutletCollection=%s]", clang_getCString(S));
222      clang_disposeString(S);
223    }
224
225    if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
226      enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
227      unsigned isVirtual = clang_isVirtualBase(Cursor);
228      const char *accessStr = 0;
229
230      switch (access) {
231        case CX_CXXInvalidAccessSpecifier:
232          accessStr = "invalid"; break;
233        case CX_CXXPublic:
234          accessStr = "public"; break;
235        case CX_CXXProtected:
236          accessStr = "protected"; break;
237        case CX_CXXPrivate:
238          accessStr = "private"; break;
239      }
240
241      printf(" [access=%s isVirtual=%s]", accessStr,
242             isVirtual ? "true" : "false");
243    }
244
245    SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
246    if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
247      CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
248      CXString Name = clang_getCursorSpelling(SpecializationOf);
249      clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
250      printf(" [Specialization of %s:%d:%d]",
251             clang_getCString(Name), line, column);
252      clang_disposeString(Name);
253    }
254  }
255}
256
257static const char* GetCursorSource(CXCursor Cursor) {
258  CXSourceLocation Loc = clang_getCursorLocation(Cursor);
259  CXString source;
260  CXFile file;
261  clang_getInstantiationLocation(Loc, &file, 0, 0, 0);
262  source = clang_getFileName(file);
263  if (!clang_getCString(source)) {
264    clang_disposeString(source);
265    return "<invalid loc>";
266  }
267  else {
268    const char *b = basename(clang_getCString(source));
269    clang_disposeString(source);
270    return b;
271  }
272}
273
274/******************************************************************************/
275/* Callbacks.                                                                 */
276/******************************************************************************/
277
278typedef void (*PostVisitTU)(CXTranslationUnit);
279
280void PrintDiagnostic(CXDiagnostic Diagnostic) {
281  FILE *out = stderr;
282  CXFile file;
283  CXString Msg;
284  unsigned display_opts = CXDiagnostic_DisplaySourceLocation
285    | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges;
286  unsigned i, num_fixits;
287
288  if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
289    return;
290
291  Msg = clang_formatDiagnostic(Diagnostic, display_opts);
292  fprintf(stderr, "%s\n", clang_getCString(Msg));
293  clang_disposeString(Msg);
294
295  clang_getInstantiationLocation(clang_getDiagnosticLocation(Diagnostic),
296                                 &file, 0, 0, 0);
297  if (!file)
298    return;
299
300  num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
301  for (i = 0; i != num_fixits; ++i) {
302    CXSourceRange range;
303    CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
304    CXSourceLocation start = clang_getRangeStart(range);
305    CXSourceLocation end = clang_getRangeEnd(range);
306    unsigned start_line, start_column, end_line, end_column;
307    CXFile start_file, end_file;
308    clang_getInstantiationLocation(start, &start_file, &start_line,
309                                   &start_column, 0);
310    clang_getInstantiationLocation(end, &end_file, &end_line, &end_column, 0);
311    if (clang_equalLocations(start, end)) {
312      /* Insertion. */
313      if (start_file == file)
314        fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
315                clang_getCString(insertion_text), start_line, start_column);
316    } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
317      /* Removal. */
318      if (start_file == file && end_file == file) {
319        fprintf(out, "FIX-IT: Remove ");
320        PrintExtent(out, start_line, start_column, end_line, end_column);
321        fprintf(out, "\n");
322      }
323    } else {
324      /* Replacement. */
325      if (start_file == end_file) {
326        fprintf(out, "FIX-IT: Replace ");
327        PrintExtent(out, start_line, start_column, end_line, end_column);
328        fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
329      }
330      break;
331    }
332    clang_disposeString(insertion_text);
333  }
334}
335
336void PrintDiagnostics(CXTranslationUnit TU) {
337  int i, n = clang_getNumDiagnostics(TU);
338  for (i = 0; i != n; ++i) {
339    CXDiagnostic Diag = clang_getDiagnostic(TU, i);
340    PrintDiagnostic(Diag);
341    clang_disposeDiagnostic(Diag);
342  }
343}
344
345/******************************************************************************/
346/* Logic for testing traversal.                                               */
347/******************************************************************************/
348
349static const char *FileCheckPrefix = "CHECK";
350
351static void PrintCursorExtent(CXCursor C) {
352  CXSourceRange extent = clang_getCursorExtent(C);
353  CXFile begin_file, end_file;
354  unsigned begin_line, begin_column, end_line, end_column;
355
356  clang_getInstantiationLocation(clang_getRangeStart(extent),
357                                 &begin_file, &begin_line, &begin_column, 0);
358  clang_getInstantiationLocation(clang_getRangeEnd(extent),
359                                 &end_file, &end_line, &end_column, 0);
360  if (!begin_file || !end_file)
361    return;
362
363  printf(" Extent=");
364  PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
365}
366
367/* Data used by all of the visitors. */
368typedef struct  {
369  CXTranslationUnit TU;
370  enum CXCursorKind *Filter;
371} VisitorData;
372
373
374enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
375                                                CXCursor Parent,
376                                                CXClientData ClientData) {
377  VisitorData *Data = (VisitorData *)ClientData;
378  if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
379    CXSourceLocation Loc = clang_getCursorLocation(Cursor);
380    unsigned line, column;
381    clang_getInstantiationLocation(Loc, 0, &line, &column, 0);
382    printf("// %s: %s:%d:%d: ", FileCheckPrefix,
383           GetCursorSource(Cursor), line, column);
384    PrintCursor(Cursor);
385    PrintCursorExtent(Cursor);
386    printf("\n");
387    return CXChildVisit_Recurse;
388  }
389
390  return CXChildVisit_Continue;
391}
392
393static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
394                                                   CXCursor Parent,
395                                                   CXClientData ClientData) {
396  const char *startBuf, *endBuf;
397  unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
398  CXCursor Ref;
399  VisitorData *Data = (VisitorData *)ClientData;
400
401  if (Cursor.kind != CXCursor_FunctionDecl ||
402      !clang_isCursorDefinition(Cursor))
403    return CXChildVisit_Continue;
404
405  clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
406                                       &startLine, &startColumn,
407                                       &endLine, &endColumn);
408  /* Probe the entire body, looking for both decls and refs. */
409  curLine = startLine;
410  curColumn = startColumn;
411
412  while (startBuf < endBuf) {
413    CXSourceLocation Loc;
414    CXFile file;
415    CXString source;
416
417    if (*startBuf == '\n') {
418      startBuf++;
419      curLine++;
420      curColumn = 1;
421    } else if (*startBuf != '\t')
422      curColumn++;
423
424    Loc = clang_getCursorLocation(Cursor);
425    clang_getInstantiationLocation(Loc, &file, 0, 0, 0);
426
427    source = clang_getFileName(file);
428    if (clang_getCString(source)) {
429      CXSourceLocation RefLoc
430        = clang_getLocation(Data->TU, file, curLine, curColumn);
431      Ref = clang_getCursor(Data->TU, RefLoc);
432      if (Ref.kind == CXCursor_NoDeclFound) {
433        /* Nothing found here; that's fine. */
434      } else if (Ref.kind != CXCursor_FunctionDecl) {
435        printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
436               curLine, curColumn);
437        PrintCursor(Ref);
438        printf("\n");
439      }
440    }
441    clang_disposeString(source);
442    startBuf++;
443  }
444
445  return CXChildVisit_Continue;
446}
447
448/******************************************************************************/
449/* USR testing.                                                               */
450/******************************************************************************/
451
452enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
453                                   CXClientData ClientData) {
454  VisitorData *Data = (VisitorData *)ClientData;
455  if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
456    CXString USR = clang_getCursorUSR(C);
457    const char *cstr = clang_getCString(USR);
458    if (!cstr || cstr[0] == '\0') {
459      clang_disposeString(USR);
460      return CXChildVisit_Recurse;
461    }
462    printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
463
464    PrintCursorExtent(C);
465    printf("\n");
466    clang_disposeString(USR);
467
468    return CXChildVisit_Recurse;
469  }
470
471  return CXChildVisit_Continue;
472}
473
474/******************************************************************************/
475/* Inclusion stack testing.                                                   */
476/******************************************************************************/
477
478void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
479                      unsigned includeStackLen, CXClientData data) {
480
481  unsigned i;
482  CXString fname;
483
484  fname = clang_getFileName(includedFile);
485  printf("file: %s\nincluded by:\n", clang_getCString(fname));
486  clang_disposeString(fname);
487
488  for (i = 0; i < includeStackLen; ++i) {
489    CXFile includingFile;
490    unsigned line, column;
491    clang_getInstantiationLocation(includeStack[i], &includingFile, &line,
492                                   &column, 0);
493    fname = clang_getFileName(includingFile);
494    printf("  %s:%d:%d\n", clang_getCString(fname), line, column);
495    clang_disposeString(fname);
496  }
497  printf("\n");
498}
499
500void PrintInclusionStack(CXTranslationUnit TU) {
501  clang_getInclusions(TU, InclusionVisitor, NULL);
502}
503
504/******************************************************************************/
505/* Linkage testing.                                                           */
506/******************************************************************************/
507
508static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
509                                            CXClientData d) {
510  const char *linkage = 0;
511
512  if (clang_isInvalid(clang_getCursorKind(cursor)))
513    return CXChildVisit_Recurse;
514
515  switch (clang_getCursorLinkage(cursor)) {
516    case CXLinkage_Invalid: break;
517    case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
518    case CXLinkage_Internal: linkage = "Internal"; break;
519    case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
520    case CXLinkage_External: linkage = "External"; break;
521  }
522
523  if (linkage) {
524    PrintCursor(cursor);
525    printf("linkage=%s\n", linkage);
526  }
527
528  return CXChildVisit_Recurse;
529}
530
531/******************************************************************************/
532/* Typekind testing.                                                          */
533/******************************************************************************/
534
535static enum CXChildVisitResult PrintTypeKind(CXCursor cursor, CXCursor p,
536                                             CXClientData d) {
537
538  if (!clang_isInvalid(clang_getCursorKind(cursor))) {
539    CXType T = clang_getCursorType(cursor);
540    CXString S = clang_getTypeKindSpelling(T.kind);
541    PrintCursor(cursor);
542    printf(" typekind=%s", clang_getCString(S));
543    clang_disposeString(S);
544    /* Print the canonical type if it is different. */
545    {
546      CXType CT = clang_getCanonicalType(T);
547      if (!clang_equalTypes(T, CT)) {
548        CXString CS = clang_getTypeKindSpelling(CT.kind);
549        printf(" [canonical=%s]", clang_getCString(CS));
550        clang_disposeString(CS);
551      }
552    }
553    /* Print the return type if it exists. */
554    {
555      CXType RT = clang_getCursorResultType(cursor);
556      if (RT.kind != CXType_Invalid) {
557        CXString RS = clang_getTypeKindSpelling(RT.kind);
558        printf(" [result=%s]", clang_getCString(RS));
559        clang_disposeString(RS);
560      }
561    }
562    /* Print if this is a non-POD type. */
563    printf(" [isPOD=%d]", clang_isPODType(T));
564
565    printf("\n");
566  }
567  return CXChildVisit_Recurse;
568}
569
570
571/******************************************************************************/
572/* Loading ASTs/source.                                                       */
573/******************************************************************************/
574
575static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
576                             const char *filter, const char *prefix,
577                             CXCursorVisitor Visitor,
578                             PostVisitTU PV) {
579
580  if (prefix)
581    FileCheckPrefix = prefix;
582
583  if (Visitor) {
584    enum CXCursorKind K = CXCursor_NotImplemented;
585    enum CXCursorKind *ck = &K;
586    VisitorData Data;
587
588    /* Perform some simple filtering. */
589    if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
590    else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
591    else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
592    else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
593    else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
594    else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
595    else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
596    else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
597    else {
598      fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
599      return 1;
600    }
601
602    Data.TU = TU;
603    Data.Filter = ck;
604    clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
605  }
606
607  if (PV)
608    PV(TU);
609
610  PrintDiagnostics(TU);
611  clang_disposeTranslationUnit(TU);
612  return 0;
613}
614
615int perform_test_load_tu(const char *file, const char *filter,
616                         const char *prefix, CXCursorVisitor Visitor,
617                         PostVisitTU PV) {
618  CXIndex Idx;
619  CXTranslationUnit TU;
620  int result;
621  Idx = clang_createIndex(/* excludeDeclsFromPCH */
622                          !strcmp(filter, "local") ? 1 : 0,
623                          /* displayDiagnosics=*/1);
624
625  if (!CreateTranslationUnit(Idx, file, &TU)) {
626    clang_disposeIndex(Idx);
627    return 1;
628  }
629
630  result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV);
631  clang_disposeIndex(Idx);
632  return result;
633}
634
635int perform_test_load_source(int argc, const char **argv,
636                             const char *filter, CXCursorVisitor Visitor,
637                             PostVisitTU PV) {
638  const char *UseExternalASTs =
639    getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION");
640  CXIndex Idx;
641  CXTranslationUnit TU;
642  struct CXUnsavedFile *unsaved_files = 0;
643  int num_unsaved_files = 0;
644  int result;
645
646  Idx = clang_createIndex(/* excludeDeclsFromPCH */
647                          !strcmp(filter, "local") ? 1 : 0,
648                          /* displayDiagnosics=*/1);
649
650  if (UseExternalASTs && strlen(UseExternalASTs))
651    clang_setUseExternalASTGeneration(Idx, 1);
652
653  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
654    clang_disposeIndex(Idx);
655    return -1;
656  }
657
658  TU = clang_createTranslationUnitFromSourceFile(Idx, 0,
659                                                 argc - num_unsaved_files,
660                                                 argv + num_unsaved_files,
661                                                 num_unsaved_files,
662                                                 unsaved_files);
663  if (!TU) {
664    fprintf(stderr, "Unable to load translation unit!\n");
665    free_remapped_files(unsaved_files, num_unsaved_files);
666    clang_disposeIndex(Idx);
667    return 1;
668  }
669
670  result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
671  free_remapped_files(unsaved_files, num_unsaved_files);
672  clang_disposeIndex(Idx);
673  return result;
674}
675
676int perform_test_reparse_source(int argc, const char **argv, int trials,
677                                const char *filter, CXCursorVisitor Visitor,
678                                PostVisitTU PV) {
679  const char *UseExternalASTs =
680  getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION");
681  CXIndex Idx;
682  CXTranslationUnit TU;
683  struct CXUnsavedFile *unsaved_files = 0;
684  int num_unsaved_files = 0;
685  int result;
686  int trial;
687
688  Idx = clang_createIndex(/* excludeDeclsFromPCH */
689                          !strcmp(filter, "local") ? 1 : 0,
690                          /* displayDiagnosics=*/1);
691
692  if (UseExternalASTs && strlen(UseExternalASTs))
693    clang_setUseExternalASTGeneration(Idx, 1);
694
695  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
696    clang_disposeIndex(Idx);
697    return -1;
698  }
699
700  /* Load the initial translation unit -- we do this without honoring remapped
701   * files, so that we have a way to test results after changing the source. */
702  TU = clang_parseTranslationUnit(Idx, 0,
703                                  argv + num_unsaved_files,
704                                  argc - num_unsaved_files,
705                                  0, 0, getDefaultParsingOptions());
706  if (!TU) {
707    fprintf(stderr, "Unable to load translation unit!\n");
708    free_remapped_files(unsaved_files, num_unsaved_files);
709    clang_disposeIndex(Idx);
710    return 1;
711  }
712
713  for (trial = 0; trial < trials; ++trial) {
714    if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
715                                     clang_defaultReparseOptions(TU))) {
716      fprintf(stderr, "Unable to reparse translation unit!\n");
717      clang_disposeTranslationUnit(TU);
718      free_remapped_files(unsaved_files, num_unsaved_files);
719      clang_disposeIndex(Idx);
720      return -1;
721    }
722  }
723
724  result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
725  free_remapped_files(unsaved_files, num_unsaved_files);
726  clang_disposeIndex(Idx);
727  return result;
728}
729
730/******************************************************************************/
731/* Logic for testing clang_getCursor().                                       */
732/******************************************************************************/
733
734static void print_cursor_file_scan(CXCursor cursor,
735                                   unsigned start_line, unsigned start_col,
736                                   unsigned end_line, unsigned end_col,
737                                   const char *prefix) {
738  printf("// %s: ", FileCheckPrefix);
739  if (prefix)
740    printf("-%s", prefix);
741  PrintExtent(stdout, start_line, start_col, end_line, end_col);
742  printf(" ");
743  PrintCursor(cursor);
744  printf("\n");
745}
746
747static int perform_file_scan(const char *ast_file, const char *source_file,
748                             const char *prefix) {
749  CXIndex Idx;
750  CXTranslationUnit TU;
751  FILE *fp;
752  CXCursor prevCursor = clang_getNullCursor();
753  CXFile file;
754  unsigned line = 1, col = 1;
755  unsigned start_line = 1, start_col = 1;
756
757  if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
758                                /* displayDiagnosics=*/1))) {
759    fprintf(stderr, "Could not create Index\n");
760    return 1;
761  }
762
763  if (!CreateTranslationUnit(Idx, ast_file, &TU))
764    return 1;
765
766  if ((fp = fopen(source_file, "r")) == NULL) {
767    fprintf(stderr, "Could not open '%s'\n", source_file);
768    return 1;
769  }
770
771  file = clang_getFile(TU, source_file);
772  for (;;) {
773    CXCursor cursor;
774    int c = fgetc(fp);
775
776    if (c == '\n') {
777      ++line;
778      col = 1;
779    } else
780      ++col;
781
782    /* Check the cursor at this position, and dump the previous one if we have
783     * found something new.
784     */
785    cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
786    if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
787        prevCursor.kind != CXCursor_InvalidFile) {
788      print_cursor_file_scan(prevCursor, start_line, start_col,
789                             line, col, prefix);
790      start_line = line;
791      start_col = col;
792    }
793    if (c == EOF)
794      break;
795
796    prevCursor = cursor;
797  }
798
799  fclose(fp);
800  return 0;
801}
802
803/******************************************************************************/
804/* Logic for testing clang_codeComplete().                                    */
805/******************************************************************************/
806
807/* Parse file:line:column from the input string. Returns 0 on success, non-zero
808   on failure. If successful, the pointer *filename will contain newly-allocated
809   memory (that will be owned by the caller) to store the file name. */
810int parse_file_line_column(const char *input, char **filename, unsigned *line,
811                           unsigned *column, unsigned *second_line,
812                           unsigned *second_column) {
813  /* Find the second colon. */
814  const char *last_colon = strrchr(input, ':');
815  unsigned values[4], i;
816  unsigned num_values = (second_line && second_column)? 4 : 2;
817
818  char *endptr = 0;
819  if (!last_colon || last_colon == input) {
820    if (num_values == 4)
821      fprintf(stderr, "could not parse filename:line:column:line:column in "
822              "'%s'\n", input);
823    else
824      fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
825    return 1;
826  }
827
828  for (i = 0; i != num_values; ++i) {
829    const char *prev_colon;
830
831    /* Parse the next line or column. */
832    values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
833    if (*endptr != 0 && *endptr != ':') {
834      fprintf(stderr, "could not parse %s in '%s'\n",
835              (i % 2 ? "column" : "line"), input);
836      return 1;
837    }
838
839    if (i + 1 == num_values)
840      break;
841
842    /* Find the previous colon. */
843    prev_colon = last_colon - 1;
844    while (prev_colon != input && *prev_colon != ':')
845      --prev_colon;
846    if (prev_colon == input) {
847      fprintf(stderr, "could not parse %s in '%s'\n",
848              (i % 2 == 0? "column" : "line"), input);
849      return 1;
850    }
851
852    last_colon = prev_colon;
853  }
854
855  *line = values[0];
856  *column = values[1];
857
858  if (second_line && second_column) {
859    *second_line = values[2];
860    *second_column = values[3];
861  }
862
863  /* Copy the file name. */
864  *filename = (char*)malloc(last_colon - input + 1);
865  memcpy(*filename, input, last_colon - input);
866  (*filename)[last_colon - input] = 0;
867  return 0;
868}
869
870const char *
871clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
872  switch (Kind) {
873  case CXCompletionChunk_Optional: return "Optional";
874  case CXCompletionChunk_TypedText: return "TypedText";
875  case CXCompletionChunk_Text: return "Text";
876  case CXCompletionChunk_Placeholder: return "Placeholder";
877  case CXCompletionChunk_Informative: return "Informative";
878  case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
879  case CXCompletionChunk_LeftParen: return "LeftParen";
880  case CXCompletionChunk_RightParen: return "RightParen";
881  case CXCompletionChunk_LeftBracket: return "LeftBracket";
882  case CXCompletionChunk_RightBracket: return "RightBracket";
883  case CXCompletionChunk_LeftBrace: return "LeftBrace";
884  case CXCompletionChunk_RightBrace: return "RightBrace";
885  case CXCompletionChunk_LeftAngle: return "LeftAngle";
886  case CXCompletionChunk_RightAngle: return "RightAngle";
887  case CXCompletionChunk_Comma: return "Comma";
888  case CXCompletionChunk_ResultType: return "ResultType";
889  case CXCompletionChunk_Colon: return "Colon";
890  case CXCompletionChunk_SemiColon: return "SemiColon";
891  case CXCompletionChunk_Equal: return "Equal";
892  case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
893  case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
894  }
895
896  return "Unknown";
897}
898
899void print_completion_string(CXCompletionString completion_string, FILE *file) {
900  int I, N;
901
902  N = clang_getNumCompletionChunks(completion_string);
903  for (I = 0; I != N; ++I) {
904    CXString text;
905    const char *cstr;
906    enum CXCompletionChunkKind Kind
907      = clang_getCompletionChunkKind(completion_string, I);
908
909    if (Kind == CXCompletionChunk_Optional) {
910      fprintf(file, "{Optional ");
911      print_completion_string(
912                clang_getCompletionChunkCompletionString(completion_string, I),
913                              file);
914      fprintf(file, "}");
915      continue;
916    }
917
918    text = clang_getCompletionChunkText(completion_string, I);
919    cstr = clang_getCString(text);
920    fprintf(file, "{%s %s}",
921            clang_getCompletionChunkKindSpelling(Kind),
922            cstr ? cstr : "");
923    clang_disposeString(text);
924  }
925
926}
927
928void print_completion_result(CXCompletionResult *completion_result,
929                             CXClientData client_data) {
930  FILE *file = (FILE *)client_data;
931  CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
932
933  fprintf(file, "%s:", clang_getCString(ks));
934  clang_disposeString(ks);
935
936  print_completion_string(completion_result->CompletionString, file);
937  fprintf(file, " (%u)",
938          clang_getCompletionPriority(completion_result->CompletionString));
939  switch (clang_getCompletionAvailability(completion_result->CompletionString)){
940  case CXAvailability_Available:
941    break;
942
943  case CXAvailability_Deprecated:
944    fprintf(file, " (deprecated)");
945    break;
946
947  case CXAvailability_NotAvailable:
948    fprintf(file, " (unavailable)");
949    break;
950  }
951  fprintf(file, "\n");
952}
953
954int my_stricmp(const char *s1, const char *s2) {
955  while (*s1 && *s2) {
956    int c1 = tolower(*s1), c2 = tolower(*s2);
957    if (c1 < c2)
958      return -1;
959    else if (c1 > c2)
960      return 1;
961
962    ++s1;
963    ++s2;
964  }
965
966  if (*s1)
967    return 1;
968  else if (*s2)
969    return -1;
970  return 0;
971}
972
973int perform_code_completion(int argc, const char **argv, int timing_only) {
974  const char *input = argv[1];
975  char *filename = 0;
976  unsigned line;
977  unsigned column;
978  CXIndex CIdx;
979  int errorCode;
980  struct CXUnsavedFile *unsaved_files = 0;
981  int num_unsaved_files = 0;
982  CXCodeCompleteResults *results = 0;
983  CXTranslationUnit TU = 0;
984
985  if (timing_only)
986    input += strlen("-code-completion-timing=");
987  else
988    input += strlen("-code-completion-at=");
989
990  if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
991                                          0, 0)))
992    return errorCode;
993
994  if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
995    return -1;
996
997  CIdx = clang_createIndex(0, 1);
998  if (getenv("CINDEXTEST_EDITING")) {
999    unsigned I, Repeats = 5;
1000    TU = clang_parseTranslationUnit(CIdx, 0,
1001                                    argv + num_unsaved_files + 2,
1002                                    argc - num_unsaved_files - 2,
1003                                    0, 0, getDefaultParsingOptions());
1004    if (!TU) {
1005      fprintf(stderr, "Unable to load translation unit!\n");
1006      return 1;
1007    }
1008    for (I = 0; I != Repeats; ++I) {
1009      results = clang_codeCompleteAt(TU, filename, line, column,
1010                                     unsaved_files, num_unsaved_files,
1011                                     clang_defaultCodeCompleteOptions());
1012      if (!results) {
1013        fprintf(stderr, "Unable to perform code completion!\n");
1014        return 1;
1015      }
1016      if (I != Repeats-1)
1017        clang_disposeCodeCompleteResults(results);
1018    }
1019  } else
1020    results = clang_codeComplete(CIdx,
1021                                 argv[argc - 1], argc - num_unsaved_files - 3,
1022                                 argv + num_unsaved_files + 2,
1023                                 num_unsaved_files, unsaved_files,
1024                                 filename, line, column);
1025
1026  if (results) {
1027    unsigned i, n = results->NumResults;
1028    if (!timing_only) {
1029      /* Sort the code-completion results based on the typed text. */
1030      clang_sortCodeCompletionResults(results->Results, results->NumResults);
1031
1032      for (i = 0; i != n; ++i)
1033        print_completion_result(results->Results + i, stdout);
1034    }
1035    n = clang_codeCompleteGetNumDiagnostics(results);
1036    for (i = 0; i != n; ++i) {
1037      CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
1038      PrintDiagnostic(diag);
1039      clang_disposeDiagnostic(diag);
1040    }
1041    clang_disposeCodeCompleteResults(results);
1042  }
1043  clang_disposeTranslationUnit(TU);
1044  clang_disposeIndex(CIdx);
1045  free(filename);
1046
1047  free_remapped_files(unsaved_files, num_unsaved_files);
1048
1049  return 0;
1050}
1051
1052typedef struct {
1053  char *filename;
1054  unsigned line;
1055  unsigned column;
1056} CursorSourceLocation;
1057
1058int inspect_cursor_at(int argc, const char **argv) {
1059  CXIndex CIdx;
1060  int errorCode;
1061  struct CXUnsavedFile *unsaved_files = 0;
1062  int num_unsaved_files = 0;
1063  CXTranslationUnit TU;
1064  CXCursor Cursor;
1065  CursorSourceLocation *Locations = 0;
1066  unsigned NumLocations = 0, Loc;
1067
1068  /* Count the number of locations. */
1069  while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
1070    ++NumLocations;
1071
1072  /* Parse the locations. */
1073  assert(NumLocations > 0 && "Unable to count locations?");
1074  Locations = (CursorSourceLocation *)malloc(
1075                                  NumLocations * sizeof(CursorSourceLocation));
1076  for (Loc = 0; Loc < NumLocations; ++Loc) {
1077    const char *input = argv[Loc + 1] + strlen("-cursor-at=");
1078    if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1079                                            &Locations[Loc].line,
1080                                            &Locations[Loc].column, 0, 0)))
1081      return errorCode;
1082  }
1083
1084  if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
1085                           &num_unsaved_files))
1086    return -1;
1087
1088  CIdx = clang_createIndex(0, 1);
1089  TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
1090                                  argc - num_unsaved_files - 2 - NumLocations,
1091                                   argv + num_unsaved_files + 1 + NumLocations,
1092                                                 num_unsaved_files,
1093                                                 unsaved_files);
1094  if (!TU) {
1095    fprintf(stderr, "unable to parse input\n");
1096    return -1;
1097  }
1098
1099  for (Loc = 0; Loc < NumLocations; ++Loc) {
1100    CXFile file = clang_getFile(TU, Locations[Loc].filename);
1101    if (!file)
1102      continue;
1103
1104    Cursor = clang_getCursor(TU,
1105                             clang_getLocation(TU, file, Locations[Loc].line,
1106                                               Locations[Loc].column));
1107    PrintCursor(Cursor);
1108    printf("\n");
1109    free(Locations[Loc].filename);
1110  }
1111
1112  PrintDiagnostics(TU);
1113  clang_disposeTranslationUnit(TU);
1114  clang_disposeIndex(CIdx);
1115  free(Locations);
1116  free_remapped_files(unsaved_files, num_unsaved_files);
1117  return 0;
1118}
1119
1120int perform_token_annotation(int argc, const char **argv) {
1121  const char *input = argv[1];
1122  char *filename = 0;
1123  unsigned line, second_line;
1124  unsigned column, second_column;
1125  CXIndex CIdx;
1126  CXTranslationUnit TU = 0;
1127  int errorCode;
1128  struct CXUnsavedFile *unsaved_files = 0;
1129  int num_unsaved_files = 0;
1130  CXToken *tokens;
1131  unsigned num_tokens;
1132  CXSourceRange range;
1133  CXSourceLocation startLoc, endLoc;
1134  CXFile file = 0;
1135  CXCursor *cursors = 0;
1136  unsigned i;
1137
1138  input += strlen("-test-annotate-tokens=");
1139  if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
1140                                          &second_line, &second_column)))
1141    return errorCode;
1142
1143  if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1144    return -1;
1145
1146  CIdx = clang_createIndex(0, 1);
1147  TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
1148                                                 argc - num_unsaved_files - 3,
1149                                                 argv + num_unsaved_files + 2,
1150                                                 num_unsaved_files,
1151                                                 unsaved_files);
1152  if (!TU) {
1153    fprintf(stderr, "unable to parse input\n");
1154    clang_disposeIndex(CIdx);
1155    free(filename);
1156    free_remapped_files(unsaved_files, num_unsaved_files);
1157    return -1;
1158  }
1159  errorCode = 0;
1160
1161  file = clang_getFile(TU, filename);
1162  if (!file) {
1163    fprintf(stderr, "file %s is not in this translation unit\n", filename);
1164    errorCode = -1;
1165    goto teardown;
1166  }
1167
1168  startLoc = clang_getLocation(TU, file, line, column);
1169  if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
1170    fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
1171            column);
1172    errorCode = -1;
1173    goto teardown;
1174  }
1175
1176  endLoc = clang_getLocation(TU, file, second_line, second_column);
1177  if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
1178    fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
1179            second_line, second_column);
1180    errorCode = -1;
1181    goto teardown;
1182  }
1183
1184  range = clang_getRange(startLoc, endLoc);
1185  clang_tokenize(TU, range, &tokens, &num_tokens);
1186  cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
1187  clang_annotateTokens(TU, tokens, num_tokens, cursors);
1188  for (i = 0; i != num_tokens; ++i) {
1189    const char *kind = "<unknown>";
1190    CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
1191    CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
1192    unsigned start_line, start_column, end_line, end_column;
1193
1194    switch (clang_getTokenKind(tokens[i])) {
1195    case CXToken_Punctuation: kind = "Punctuation"; break;
1196    case CXToken_Keyword: kind = "Keyword"; break;
1197    case CXToken_Identifier: kind = "Identifier"; break;
1198    case CXToken_Literal: kind = "Literal"; break;
1199    case CXToken_Comment: kind = "Comment"; break;
1200    }
1201    clang_getInstantiationLocation(clang_getRangeStart(extent),
1202                                   0, &start_line, &start_column, 0);
1203    clang_getInstantiationLocation(clang_getRangeEnd(extent),
1204                                   0, &end_line, &end_column, 0);
1205    printf("%s: \"%s\" ", kind, clang_getCString(spelling));
1206    PrintExtent(stdout, start_line, start_column, end_line, end_column);
1207    if (!clang_isInvalid(cursors[i].kind)) {
1208      printf(" ");
1209      PrintCursor(cursors[i]);
1210    }
1211    printf("\n");
1212  }
1213  free(cursors);
1214
1215 teardown:
1216  PrintDiagnostics(TU);
1217  clang_disposeTranslationUnit(TU);
1218  clang_disposeIndex(CIdx);
1219  free(filename);
1220  free_remapped_files(unsaved_files, num_unsaved_files);
1221  return errorCode;
1222}
1223
1224/******************************************************************************/
1225/* USR printing.                                                              */
1226/******************************************************************************/
1227
1228static int insufficient_usr(const char *kind, const char *usage) {
1229  fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
1230  return 1;
1231}
1232
1233static unsigned isUSR(const char *s) {
1234  return s[0] == 'c' && s[1] == ':';
1235}
1236
1237static int not_usr(const char *s, const char *arg) {
1238  fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
1239  return 1;
1240}
1241
1242static void print_usr(CXString usr) {
1243  const char *s = clang_getCString(usr);
1244  printf("%s\n", s);
1245  clang_disposeString(usr);
1246}
1247
1248static void display_usrs() {
1249  fprintf(stderr, "-print-usrs options:\n"
1250        " ObjCCategory <class name> <category name>\n"
1251        " ObjCClass <class name>\n"
1252        " ObjCIvar <ivar name> <class USR>\n"
1253        " ObjCMethod <selector> [0=class method|1=instance method] "
1254            "<class USR>\n"
1255          " ObjCProperty <property name> <class USR>\n"
1256          " ObjCProtocol <protocol name>\n");
1257}
1258
1259int print_usrs(const char **I, const char **E) {
1260  while (I != E) {
1261    const char *kind = *I;
1262    unsigned len = strlen(kind);
1263    switch (len) {
1264      case 8:
1265        if (memcmp(kind, "ObjCIvar", 8) == 0) {
1266          if (I + 2 >= E)
1267            return insufficient_usr(kind, "<ivar name> <class USR>");
1268          if (!isUSR(I[2]))
1269            return not_usr("<class USR>", I[2]);
1270          else {
1271            CXString x;
1272            x.Spelling = I[2];
1273            x.MustFreeString = 0;
1274            print_usr(clang_constructUSR_ObjCIvar(I[1], x));
1275          }
1276
1277          I += 3;
1278          continue;
1279        }
1280        break;
1281      case 9:
1282        if (memcmp(kind, "ObjCClass", 9) == 0) {
1283          if (I + 1 >= E)
1284            return insufficient_usr(kind, "<class name>");
1285          print_usr(clang_constructUSR_ObjCClass(I[1]));
1286          I += 2;
1287          continue;
1288        }
1289        break;
1290      case 10:
1291        if (memcmp(kind, "ObjCMethod", 10) == 0) {
1292          if (I + 3 >= E)
1293            return insufficient_usr(kind, "<method selector> "
1294                "[0=class method|1=instance method] <class USR>");
1295          if (!isUSR(I[3]))
1296            return not_usr("<class USR>", I[3]);
1297          else {
1298            CXString x;
1299            x.Spelling = I[3];
1300            x.MustFreeString = 0;
1301            print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
1302          }
1303          I += 4;
1304          continue;
1305        }
1306        break;
1307      case 12:
1308        if (memcmp(kind, "ObjCCategory", 12) == 0) {
1309          if (I + 2 >= E)
1310            return insufficient_usr(kind, "<class name> <category name>");
1311          print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
1312          I += 3;
1313          continue;
1314        }
1315        if (memcmp(kind, "ObjCProtocol", 12) == 0) {
1316          if (I + 1 >= E)
1317            return insufficient_usr(kind, "<protocol name>");
1318          print_usr(clang_constructUSR_ObjCProtocol(I[1]));
1319          I += 2;
1320          continue;
1321        }
1322        if (memcmp(kind, "ObjCProperty", 12) == 0) {
1323          if (I + 2 >= E)
1324            return insufficient_usr(kind, "<property name> <class USR>");
1325          if (!isUSR(I[2]))
1326            return not_usr("<class USR>", I[2]);
1327          else {
1328            CXString x;
1329            x.Spelling = I[2];
1330            x.MustFreeString = 0;
1331            print_usr(clang_constructUSR_ObjCProperty(I[1], x));
1332          }
1333          I += 3;
1334          continue;
1335        }
1336        break;
1337      default:
1338        break;
1339    }
1340    break;
1341  }
1342
1343  if (I != E) {
1344    fprintf(stderr, "Invalid USR kind: %s\n", *I);
1345    display_usrs();
1346    return 1;
1347  }
1348  return 0;
1349}
1350
1351int print_usrs_file(const char *file_name) {
1352  char line[2048];
1353  const char *args[128];
1354  unsigned numChars = 0;
1355
1356  FILE *fp = fopen(file_name, "r");
1357  if (!fp) {
1358    fprintf(stderr, "error: cannot open '%s'\n", file_name);
1359    return 1;
1360  }
1361
1362  /* This code is not really all that safe, but it works fine for testing. */
1363  while (!feof(fp)) {
1364    char c = fgetc(fp);
1365    if (c == '\n') {
1366      unsigned i = 0;
1367      const char *s = 0;
1368
1369      if (numChars == 0)
1370        continue;
1371
1372      line[numChars] = '\0';
1373      numChars = 0;
1374
1375      if (line[0] == '/' && line[1] == '/')
1376        continue;
1377
1378      s = strtok(line, " ");
1379      while (s) {
1380        args[i] = s;
1381        ++i;
1382        s = strtok(0, " ");
1383      }
1384      if (print_usrs(&args[0], &args[i]))
1385        return 1;
1386    }
1387    else
1388      line[numChars++] = c;
1389  }
1390
1391  fclose(fp);
1392  return 0;
1393}
1394
1395/******************************************************************************/
1396/* Command line processing.                                                   */
1397/******************************************************************************/
1398int write_pch_file(const char *filename, int argc, const char *argv[]) {
1399  CXIndex Idx;
1400  CXTranslationUnit TU;
1401  struct CXUnsavedFile *unsaved_files = 0;
1402  int num_unsaved_files = 0;
1403
1404  Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnosics=*/1);
1405
1406  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1407    clang_disposeIndex(Idx);
1408    return -1;
1409  }
1410
1411  TU = clang_parseTranslationUnit(Idx, 0,
1412                                  argv + num_unsaved_files,
1413                                  argc - num_unsaved_files,
1414                                  unsaved_files,
1415                                  num_unsaved_files,
1416                                  CXTranslationUnit_Incomplete);
1417  if (!TU) {
1418    fprintf(stderr, "Unable to load translation unit!\n");
1419    free_remapped_files(unsaved_files, num_unsaved_files);
1420    clang_disposeIndex(Idx);
1421    return 1;
1422  }
1423
1424  if (clang_saveTranslationUnit(TU, filename, clang_defaultSaveOptions(TU)))
1425    fprintf(stderr, "Unable to write PCH file %s\n", filename);
1426  clang_disposeTranslationUnit(TU);
1427  free_remapped_files(unsaved_files, num_unsaved_files);
1428  clang_disposeIndex(Idx);
1429  return 0;
1430}
1431
1432/******************************************************************************/
1433/* Command line processing.                                                   */
1434/******************************************************************************/
1435
1436static CXCursorVisitor GetVisitor(const char *s) {
1437  if (s[0] == '\0')
1438    return FilteredPrintingVisitor;
1439  if (strcmp(s, "-usrs") == 0)
1440    return USRVisitor;
1441  return NULL;
1442}
1443
1444static void print_usage(void) {
1445  fprintf(stderr,
1446    "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
1447    "       c-index-test -code-completion-timing=<site> <compiler arguments>\n"
1448    "       c-index-test -cursor-at=<site> <compiler arguments>\n"
1449    "       c-index-test -test-file-scan <AST file> <source file> "
1450          "[FileCheck prefix]\n"
1451    "       c-index-test -test-load-tu <AST file> <symbol filter> "
1452          "[FileCheck prefix]\n"
1453    "       c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
1454           "[FileCheck prefix]\n"
1455    "       c-index-test -test-load-source <symbol filter> {<args>}*\n");
1456  fprintf(stderr,
1457    "       c-index-test -test-load-source-reparse <trials> <symbol filter> "
1458    "          {<args>}*\n"
1459    "       c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
1460    "       c-index-test -test-annotate-tokens=<range> {<args>}*\n"
1461    "       c-index-test -test-inclusion-stack-source {<args>}*\n"
1462    "       c-index-test -test-inclusion-stack-tu <AST file>\n"
1463    "       c-index-test -test-print-linkage-source {<args>}*\n"
1464    "       c-index-test -test-print-typekind {<args>}*\n"
1465    "       c-index-test -print-usr [<CursorKind> {<args>}]*\n");
1466  fprintf(stderr,
1467    "       c-index-test -print-usr-file <file>\n"
1468    "       c-index-test -write-pch <file> <compiler arguments>\n\n");
1469  fprintf(stderr,
1470    " <symbol filter> values:\n%s",
1471    "   all - load all symbols, including those from PCH\n"
1472    "   local - load all symbols except those in PCH\n"
1473    "   category - only load ObjC categories (non-PCH)\n"
1474    "   interface - only load ObjC interfaces (non-PCH)\n"
1475    "   protocol - only load ObjC protocols (non-PCH)\n"
1476    "   function - only load functions (non-PCH)\n"
1477    "   typedef - only load typdefs (non-PCH)\n"
1478    "   scan-function - scan function bodies (non-PCH)\n\n");
1479}
1480
1481/***/
1482
1483int cindextest_main(int argc, const char **argv) {
1484  clang_enableStackTraces();
1485  if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
1486    return perform_code_completion(argc, argv, 0);
1487  if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
1488    return perform_code_completion(argc, argv, 1);
1489  if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
1490    return inspect_cursor_at(argc, argv);
1491  else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
1492    CXCursorVisitor I = GetVisitor(argv[1] + 13);
1493    if (I)
1494      return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
1495                                  NULL);
1496  }
1497  else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
1498    CXCursorVisitor I = GetVisitor(argv[1] + 25);
1499    if (I) {
1500      int trials = atoi(argv[2]);
1501      return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
1502                                         NULL);
1503    }
1504  }
1505  else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
1506    CXCursorVisitor I = GetVisitor(argv[1] + 17);
1507    if (I)
1508      return perform_test_load_source(argc - 3, argv + 3, argv[2], I, NULL);
1509  }
1510  else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
1511    return perform_file_scan(argv[2], argv[3],
1512                             argc >= 5 ? argv[4] : 0);
1513  else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
1514    return perform_token_annotation(argc, argv);
1515  else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
1516    return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
1517                                    PrintInclusionStack);
1518  else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
1519    return perform_test_load_tu(argv[2], "all", NULL, NULL,
1520                                PrintInclusionStack);
1521  else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
1522    return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
1523                                    NULL);
1524  else if (argc > 2 && strcmp(argv[1], "-test-print-typekind") == 0)
1525    return perform_test_load_source(argc - 2, argv + 2, "all",
1526                                    PrintTypeKind, 0);
1527  else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
1528    if (argc > 2)
1529      return print_usrs(argv + 2, argv + argc);
1530    else {
1531      display_usrs();
1532      return 1;
1533    }
1534  }
1535  else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
1536    return print_usrs_file(argv[2]);
1537  else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
1538    return write_pch_file(argv[2], argc - 3, argv + 3);
1539
1540  print_usage();
1541  return 1;
1542}
1543
1544/***/
1545
1546/* We intentionally run in a separate thread to ensure we at least minimal
1547 * testing of a multithreaded environment (for example, having a reduced stack
1548 * size). */
1549
1550#include "llvm/Config/config.h"
1551#ifdef HAVE_PTHREAD_H
1552
1553#include <pthread.h>
1554
1555typedef struct thread_info {
1556  int argc;
1557  const char **argv;
1558  int result;
1559} thread_info;
1560void *thread_runner(void *client_data_v) {
1561  thread_info *client_data = client_data_v;
1562  client_data->result = cindextest_main(client_data->argc, client_data->argv);
1563  return 0;
1564}
1565
1566int main(int argc, const char **argv) {
1567  thread_info client_data;
1568  pthread_t thread;
1569  int res;
1570
1571  client_data.argc = argc;
1572  client_data.argv = argv;
1573  res = pthread_create(&thread, 0, thread_runner, &client_data);
1574  if (res != 0) {
1575    perror("thread creation failed");
1576    return 1;
1577  }
1578
1579  res = pthread_join(thread, 0);
1580  if (res != 0) {
1581    perror("thread join failed");
1582    return 1;
1583  }
1584
1585  return client_data.result;
1586}
1587
1588#else
1589
1590int main(int argc, const char **argv) {
1591  return cindextest_main(argc, argv);
1592}
1593
1594#endif
1595