CIndex.cpp revision 23bc11ff1874f8875426c9a8a29fe1e6894c3503
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
72a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
10eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch// This file implements the main API hooks in the Clang-C Source Indexing
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// library.
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
1490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CIndexer.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CXCursor.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CXSourceLocation.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CIndexDiagnostic.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Version.h"
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclVisitor.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/StmtVisitor.h"
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/TypeLocVisitor.h"
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Diagnostic.h"
2690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "clang/Frontend/ASTUnit.h"
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Frontend/CompilerInstance.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Frontend/FrontendDiagnostic.h"
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/Lexer.h"
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/PreprocessingRecord.h"
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/Preprocessor.h"
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/MemoryBuffer.h"
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/Timer.h"
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/System/Program.h"
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/System/Signals.h"
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Needed to define L_TMPNAM on some systems.
385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <cstdio>
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang;
415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang::cxcursor;
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang::cxstring;
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Crash Reporting.
462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
4790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef USE_CRASHTRACER
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Analysis/Support/SaveAndRestore.h"
505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Integrate with crash reporter.
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const char *__crashreporter_info__ = 0;
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)asm(".desc ___crashreporter_info__, 0x10");
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define NUM_CRASH_STRINGS 32
5490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static unsigned crashtracer_counter = 0;
555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
5690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
5790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static unsigned SetCrashTracerInfo(const char *str,
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                   llvm::SmallString<1024> &AggStr) {
612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned slot = 0;
6390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  while (crashtracer_strings[slot]) {
6490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    if (++slot == NUM_CRASH_STRINGS)
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      slot = 0;
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  crashtracer_strings[slot] = str;
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  crashtracer_counter_id[slot] = ++crashtracer_counter;
6990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
7090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // We need to create an aggregate string because multiple threads
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // may be in this method at one time.  The crash reporter string
7290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // will attempt to overapproximate the set of in-flight invocations
7390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // of this function.  Race conditions can still cause this goal
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // to not be achieved.
755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  {
7690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    llvm::raw_svector_ostream Out(AggStr);
772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
7890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  __crashreporter_info__ = agg_crashtracer_strings[slot] =  AggStr.c_str();
812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return slot;
822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static void ResetCrashTracerInfo(unsigned slot) {
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned max_slot = 0;
862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned max_value = 0;
872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (agg_crashtracer_strings[i] &&
922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        crashtracer_counter_id[i] > max_value) {
932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      max_slot = i;
9490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      max_value = crashtracer_counter_id[i];
952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  __crashreporter_info__ = agg_crashtracer_strings[max_slot];
9890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
9990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace {
1015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class ArgsCrashTracerInfo {
1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::SmallString<1024> CrashString;
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::SmallString<1024> AggregateString;
1045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned crashtracerSlot;
1055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)public:
1065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
1075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    : crashtracerSlot(0)
10890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  {
10990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    {
11090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      llvm::raw_svector_ostream Out(CrashString);
11190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Out << "ClangCIndex [" << getClangFullVersion() << "]"
11290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          << "[createTranslationUnitFromSourceFile]: clang";
11390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
11490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)           E=Args.end(); I!=E; ++I)
1152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Out << ' ' << *I;
1161320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    }
11790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
11890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                                         AggregateString);
1192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
12190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  ~ArgsCrashTracerInfo() {
12290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    ResetCrashTracerInfo(crashtracerSlot);
1232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)};
12590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
12690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#endif
1275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \brief The result of comparing two source ranges.
1295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)enum RangeComparisonResult {
1305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// \brief Either the ranges overlap or one of the ranges is invalid.
13190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  RangeOverlap,
13290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
13390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The first range ends before the second range starts.
1345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RangeBefore,
1355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// \brief The first range starts after the second range ends.
1375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RangeAfter
13890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)};
1395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \brief Compare two source ranges to determine their relative position in
14190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)/// the translation unit.
14290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static RangeComparisonResult RangeCompare(SourceManager &SM,
1435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                          SourceRange R1,
1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                          SourceRange R2) {
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(R1.isValid() && "First range is invalid?");
1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(R2.isValid() && "Second range is invalid?");
1475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (R1.getEnd() != R2.getBegin() &&
1485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
14990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return RangeBefore;
1505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (R2.getEnd() != R1.getBegin() &&
1515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
15290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return RangeAfter;
15390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return RangeOverlap;
1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \brief Determine if a source location falls within, before, or after a
1575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)///   a given source range.
1585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static RangeComparisonResult LocationCompare(SourceManager &SM,
1595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                             SourceLocation L, SourceRange R) {
1602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(R.isValid() && "First range is invalid?");
1612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(L.isValid() && "Second range is invalid?");
16290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (L == R.getBegin() || L == R.getEnd())
1632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return RangeOverlap;
1642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
1652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return RangeBefore;
16690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
16790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return RangeAfter;
16890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return RangeOverlap;
16990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
1701320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
17190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)/// \brief Translate a Clang source range into a CIndex source range.
17290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)///
1731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci/// Clang internally represents ranges where the end location points to the
174cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)/// start of the token at the end. However, for external clients it is more
17590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)/// useful to have a CXSourceRange be a proper half-open interval. This routine
17690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)/// does the appropriate translation.
1775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
17890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                                          const LangOptions &LangOpts,
17990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                                          const CharSourceRange &R) {
1805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // We want the last character in this location, so we will adjust the
1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // location accordingly.
18290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // FIXME: How do do this with a macro instantiation location?
18390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  SourceLocation EndLoc = R.getEnd();
1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
18590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
1862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    EndLoc = EndLoc.getFileLocWithOffset(Length);
18790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
18890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
1895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
19090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                           R.getBegin().getRawEncoding(),
19190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                           EndLoc.getRawEncoding() };
19290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return Result;
19390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
19490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
19590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//===----------------------------------------------------------------------===//
19690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// Cursor visitor.
19790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//===----------------------------------------------------------------------===//
1985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace {
20090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
20190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// Cursor visitor.
2025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
20390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                      public TypeLocVisitor<CursorVisitor, bool>,
20490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                      public StmtVisitor<CursorVisitor, bool>
20590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles){
20690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The translation unit we are traversing.
20790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  ASTUnit *TU;
20890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
20990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The parent cursor whose children we are traversing.
21090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CXCursor Parent;
21190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
21290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The declaration that serves at the parent of any statement or
2135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// expression nodes.
2145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Decl *StmtParent;
2155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
21690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The visitor function.
21790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CXCursorVisitor Visitor;
21890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
21990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief The opaque client data, to be passed along to the visitor.
22090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CXClientData ClientData;
22190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
22290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
22390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // to the visitor. Declarations with a PCH level greater than this value will
22490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // be suppressed.
22590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  unsigned MaxPCHLevel;
22690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
22790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \brief When valid, a source range to which the cursor should restrict
22890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// its search.
22990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  SourceRange RegionOfInterest;
23090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
2315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  using DeclVisitor<CursorVisitor, bool>::Visit;
23290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  using TypeLocVisitor<CursorVisitor, bool>::Visit;
23390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  using StmtVisitor<CursorVisitor, bool>::Visit;
2345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// \brief Determine whether this particular source range comes before, comes
23690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// after, or overlaps the region of interest.
2375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ///
23890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  /// \param R a half-open source range retrieved from the abstract syntax tree.
2395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RangeComparisonResult CompareRegionOfInterest(SourceRange R);
2405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  class SetParentRAII {
2425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CXCursor &Parent;
2435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Decl *&StmtParent;
24490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    CXCursor OldParent;
24590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
24690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  public:
2475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
2482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
24990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    {
2505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Parent = NewParent;
2515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (clang_isDeclaration(Parent.kind))
25290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        StmtParent = getCursorDecl(Parent);
2535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
2545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
25590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    ~SetParentRAII() {
25690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Parent = OldParent;
25790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      if (clang_isDeclaration(Parent.kind))
25890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        StmtParent = getCursorDecl(Parent);
259eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
26090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  };
2615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)public:
26390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
26490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                unsigned MaxPCHLevel,
26590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                SourceRange RegionOfInterest = SourceRange())
2665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    : TU(TU), Visitor(Visitor), ClientData(ClientData),
2675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
2685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  {
269    Parent.kind = CXCursor_NoDeclFound;
270    Parent.data[0] = 0;
271    Parent.data[1] = 0;
272    Parent.data[2] = 0;
273    StmtParent = 0;
274  }
275
276  bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
277
278  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
279    getPreprocessedEntities();
280
281  bool VisitChildren(CXCursor Parent);
282
283  // Declaration visitors
284  bool VisitAttributes(Decl *D);
285  bool VisitBlockDecl(BlockDecl *B);
286  bool VisitDeclContext(DeclContext *DC);
287  bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
288  bool VisitTypedefDecl(TypedefDecl *D);
289  bool VisitTagDecl(TagDecl *D);
290  bool VisitEnumConstantDecl(EnumConstantDecl *D);
291  bool VisitDeclaratorDecl(DeclaratorDecl *DD);
292  bool VisitFunctionDecl(FunctionDecl *ND);
293  bool VisitFieldDecl(FieldDecl *D);
294  bool VisitVarDecl(VarDecl *);
295  bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
296  bool VisitObjCContainerDecl(ObjCContainerDecl *D);
297  bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
298  bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
299  bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
300  bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
301  bool VisitObjCImplDecl(ObjCImplDecl *D);
302  bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
303  bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
304  // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
305  // etc.
306  // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307  bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308  bool VisitObjCClassDecl(ObjCClassDecl *D);
309  bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
310  bool VisitNamespaceDecl(NamespaceDecl *D);
311
312  // Type visitors
313  // FIXME: QualifiedTypeLoc doesn't provide any location information
314  bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
315  bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
316  bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317  bool VisitTagTypeLoc(TagTypeLoc TL);
318  // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
319  bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
320  bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
321  bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322  bool VisitPointerTypeLoc(PointerTypeLoc TL);
323  bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324  bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325  bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326  bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
327  bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
328  bool VisitArrayTypeLoc(ArrayTypeLoc TL);
329  // FIXME: Implement for TemplateSpecializationTypeLoc
330  // FIXME: Implement visitors here when the unimplemented TypeLocs get
331  // implemented
332  bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333  bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
334
335  // Statement visitors
336  bool VisitStmt(Stmt *S);
337  bool VisitDeclStmt(DeclStmt *S);
338  // FIXME: LabelStmt label?
339  bool VisitIfStmt(IfStmt *S);
340  bool VisitSwitchStmt(SwitchStmt *S);
341  bool VisitCaseStmt(CaseStmt *S);
342  bool VisitWhileStmt(WhileStmt *S);
343  bool VisitForStmt(ForStmt *S);
344//  bool VisitSwitchCase(SwitchCase *S);
345
346  // Expression visitors
347  // FIXME: DeclRefExpr with template arguments, nested-name-specifier
348  // FIXME: MemberExpr with template arguments, nested-name-specifier
349  bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
350  bool VisitBlockExpr(BlockExpr *B);
351  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
352  bool VisitExplicitCastExpr(ExplicitCastExpr *E);
353  bool VisitObjCMessageExpr(ObjCMessageExpr *E);
354  bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
355  bool VisitOffsetOfExpr(OffsetOfExpr *E);
356  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
357  // FIXME: AddrLabelExpr (once we have cursors for labels)
358  bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
359  bool VisitVAArgExpr(VAArgExpr *E);
360  // FIXME: InitListExpr (for the designators)
361  // FIXME: DesignatedInitExpr
362};
363
364} // end anonymous namespace
365
366static SourceRange getRawCursorExtent(CXCursor C);
367
368RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
369  return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
370}
371
372/// \brief Visit the given cursor and, if requested by the visitor,
373/// its children.
374///
375/// \param Cursor the cursor to visit.
376///
377/// \param CheckRegionOfInterest if true, then the caller already checked that
378/// this cursor is within the region of interest.
379///
380/// \returns true if the visitation should be aborted, false if it
381/// should continue.
382bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
383  if (clang_isInvalid(Cursor.kind))
384    return false;
385
386  if (clang_isDeclaration(Cursor.kind)) {
387    Decl *D = getCursorDecl(Cursor);
388    assert(D && "Invalid declaration cursor");
389    if (D->getPCHLevel() > MaxPCHLevel)
390      return false;
391
392    if (D->isImplicit())
393      return false;
394  }
395
396  // If we have a range of interest, and this cursor doesn't intersect with it,
397  // we're done.
398  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
399    SourceRange Range = getRawCursorExtent(Cursor);
400    if (Range.isInvalid() || CompareRegionOfInterest(Range))
401      return false;
402  }
403
404  switch (Visitor(Cursor, Parent, ClientData)) {
405  case CXChildVisit_Break:
406    return true;
407
408  case CXChildVisit_Continue:
409    return false;
410
411  case CXChildVisit_Recurse:
412    return VisitChildren(Cursor);
413  }
414
415  return false;
416}
417
418std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
419CursorVisitor::getPreprocessedEntities() {
420  PreprocessingRecord &PPRec
421    = *TU->getPreprocessor().getPreprocessingRecord();
422
423  bool OnlyLocalDecls
424    = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
425
426  // There is no region of interest; we have to walk everything.
427  if (RegionOfInterest.isInvalid())
428    return std::make_pair(PPRec.begin(OnlyLocalDecls),
429                          PPRec.end(OnlyLocalDecls));
430
431  // Find the file in which the region of interest lands.
432  SourceManager &SM = TU->getSourceManager();
433  std::pair<FileID, unsigned> Begin
434    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
435  std::pair<FileID, unsigned> End
436    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
437
438  // The region of interest spans files; we have to walk everything.
439  if (Begin.first != End.first)
440    return std::make_pair(PPRec.begin(OnlyLocalDecls),
441                          PPRec.end(OnlyLocalDecls));
442
443  ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
444    = TU->getPreprocessedEntitiesByFile();
445  if (ByFileMap.empty()) {
446    // Build the mapping from files to sets of preprocessed entities.
447    for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
448                                    EEnd = PPRec.end(OnlyLocalDecls);
449         E != EEnd; ++E) {
450      std::pair<FileID, unsigned> P
451        = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
452      ByFileMap[P.first].push_back(*E);
453    }
454  }
455
456  return std::make_pair(ByFileMap[Begin.first].begin(),
457                        ByFileMap[Begin.first].end());
458}
459
460/// \brief Visit the children of the given cursor.
461///
462/// \returns true if the visitation should be aborted, false if it
463/// should continue.
464bool CursorVisitor::VisitChildren(CXCursor Cursor) {
465  if (clang_isReference(Cursor.kind)) {
466    // By definition, references have no children.
467    return false;
468  }
469
470  // Set the Parent field to Cursor, then back to its old value once we're
471  // done.
472  SetParentRAII SetParent(Parent, StmtParent, Cursor);
473
474  if (clang_isDeclaration(Cursor.kind)) {
475    Decl *D = getCursorDecl(Cursor);
476    assert(D && "Invalid declaration cursor");
477    return VisitAttributes(D) || Visit(D);
478  }
479
480  if (clang_isStatement(Cursor.kind))
481    return Visit(getCursorStmt(Cursor));
482  if (clang_isExpression(Cursor.kind))
483    return Visit(getCursorExpr(Cursor));
484
485  if (clang_isTranslationUnit(Cursor.kind)) {
486    ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
487    if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
488        RegionOfInterest.isInvalid()) {
489      for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
490                                    TLEnd = CXXUnit->top_level_end();
491           TL != TLEnd; ++TL) {
492        if (Visit(MakeCXCursor(*TL, CXXUnit), true))
493          return true;
494      }
495    } else if (VisitDeclContext(
496                            CXXUnit->getASTContext().getTranslationUnitDecl()))
497      return true;
498
499    // Walk the preprocessing record.
500    if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
501      // FIXME: Once we have the ability to deserialize a preprocessing record,
502      // do so.
503      PreprocessingRecord::iterator E, EEnd;
504      for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
505        if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
506          if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
507            return true;
508
509          continue;
510        }
511
512        if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
513          if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
514            return true;
515
516          continue;
517        }
518      }
519    }
520    return false;
521  }
522
523  // Nothing to visit at the moment.
524  return false;
525}
526
527bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
528  if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
529    return true;
530
531  if (Stmt *Body = B->getBody())
532    return Visit(MakeCXCursor(Body, StmtParent, TU));
533
534  return false;
535}
536
537bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
538  for (DeclContext::decl_iterator
539       I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
540
541    Decl *D = *I;
542    if (D->getLexicalDeclContext() != DC)
543      continue;
544
545    CXCursor Cursor = MakeCXCursor(D, TU);
546
547    if (RegionOfInterest.isValid()) {
548      SourceRange Range = getRawCursorExtent(Cursor);
549      if (Range.isInvalid())
550        continue;
551
552      switch (CompareRegionOfInterest(Range)) {
553      case RangeBefore:
554        // This declaration comes before the region of interest; skip it.
555        continue;
556
557      case RangeAfter:
558        // This declaration comes after the region of interest; we're done.
559        return false;
560
561      case RangeOverlap:
562        // This declaration overlaps the region of interest; visit it.
563        break;
564      }
565    }
566
567    if (Visit(Cursor, true))
568      return true;
569  }
570
571  return false;
572}
573
574bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
575  llvm_unreachable("Translation units are visited directly by Visit()");
576  return false;
577}
578
579bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
580  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
581    return Visit(TSInfo->getTypeLoc());
582
583  return false;
584}
585
586bool CursorVisitor::VisitTagDecl(TagDecl *D) {
587  return VisitDeclContext(D);
588}
589
590bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
591  if (Expr *Init = D->getInitExpr())
592    return Visit(MakeCXCursor(Init, StmtParent, TU));
593  return false;
594}
595
596bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
597  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
598    if (Visit(TSInfo->getTypeLoc()))
599      return true;
600
601  return false;
602}
603
604bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
605  if (VisitDeclaratorDecl(ND))
606    return true;
607
608  if (ND->isThisDeclarationADefinition() &&
609      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
610    return true;
611
612  return false;
613}
614
615bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
616  if (VisitDeclaratorDecl(D))
617    return true;
618
619  if (Expr *BitWidth = D->getBitWidth())
620    return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
621
622  return false;
623}
624
625bool CursorVisitor::VisitVarDecl(VarDecl *D) {
626  if (VisitDeclaratorDecl(D))
627    return true;
628
629  if (Expr *Init = D->getInit())
630    return Visit(MakeCXCursor(Init, StmtParent, TU));
631
632  return false;
633}
634
635bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
636  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
637    if (Visit(TSInfo->getTypeLoc()))
638      return true;
639
640  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
641       PEnd = ND->param_end();
642       P != PEnd; ++P) {
643    if (Visit(MakeCXCursor(*P, TU)))
644      return true;
645  }
646
647  if (ND->isThisDeclarationADefinition() &&
648      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
649    return true;
650
651  return false;
652}
653
654bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
655  return VisitDeclContext(D);
656}
657
658bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
659  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
660                                   TU)))
661    return true;
662
663  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
664  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
665         E = ND->protocol_end(); I != E; ++I, ++PL)
666    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
667      return true;
668
669  return VisitObjCContainerDecl(ND);
670}
671
672bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
673  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
674  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
675       E = PID->protocol_end(); I != E; ++I, ++PL)
676    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
677      return true;
678
679  return VisitObjCContainerDecl(PID);
680}
681
682bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
683  if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
684    return true;
685
686  // FIXME: This implements a workaround with @property declarations also being
687  // installed in the DeclContext for the @interface.  Eventually this code
688  // should be removed.
689  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
690  if (!CDecl || !CDecl->IsClassExtension())
691    return false;
692
693  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
694  if (!ID)
695    return false;
696
697  IdentifierInfo *PropertyId = PD->getIdentifier();
698  ObjCPropertyDecl *prevDecl =
699    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
700
701  if (!prevDecl)
702    return false;
703
704  // Visit synthesized methods since they will be skipped when visiting
705  // the @interface.
706  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
707    if (MD->isSynthesized())
708      if (Visit(MakeCXCursor(MD, TU)))
709        return true;
710
711  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
712    if (MD->isSynthesized())
713      if (Visit(MakeCXCursor(MD, TU)))
714        return true;
715
716  return false;
717}
718
719bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
720  // Issue callbacks for super class.
721  if (D->getSuperClass() &&
722      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
723                                        D->getSuperClassLoc(),
724                                        TU)))
725    return true;
726
727  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
728  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
729         E = D->protocol_end(); I != E; ++I, ++PL)
730    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
731      return true;
732
733  return VisitObjCContainerDecl(D);
734}
735
736bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
737  return VisitObjCContainerDecl(D);
738}
739
740bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
741  // 'ID' could be null when dealing with invalid code.
742  if (ObjCInterfaceDecl *ID = D->getClassInterface())
743    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
744      return true;
745
746  return VisitObjCImplDecl(D);
747}
748
749bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
750#if 0
751  // Issue callbacks for super class.
752  // FIXME: No source location information!
753  if (D->getSuperClass() &&
754      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
755                                        D->getSuperClassLoc(),
756                                        TU)))
757    return true;
758#endif
759
760  return VisitObjCImplDecl(D);
761}
762
763bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
764  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
765  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
766                                                  E = D->protocol_end();
767       I != E; ++I, ++PL)
768    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
769      return true;
770
771  return false;
772}
773
774bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
775  for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
776    if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
777      return true;
778
779  return false;
780}
781
782bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
783  return VisitDeclContext(D);
784}
785
786bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
787  return VisitDeclContext(D);
788}
789
790bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
791  ASTContext &Context = TU->getASTContext();
792
793  // Some builtin types (such as Objective-C's "id", "sel", and
794  // "Class") have associated declarations. Create cursors for those.
795  QualType VisitType;
796  switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
797  case BuiltinType::Void:
798  case BuiltinType::Bool:
799  case BuiltinType::Char_U:
800  case BuiltinType::UChar:
801  case BuiltinType::Char16:
802  case BuiltinType::Char32:
803  case BuiltinType::UShort:
804  case BuiltinType::UInt:
805  case BuiltinType::ULong:
806  case BuiltinType::ULongLong:
807  case BuiltinType::UInt128:
808  case BuiltinType::Char_S:
809  case BuiltinType::SChar:
810  case BuiltinType::WChar:
811  case BuiltinType::Short:
812  case BuiltinType::Int:
813  case BuiltinType::Long:
814  case BuiltinType::LongLong:
815  case BuiltinType::Int128:
816  case BuiltinType::Float:
817  case BuiltinType::Double:
818  case BuiltinType::LongDouble:
819  case BuiltinType::NullPtr:
820  case BuiltinType::Overload:
821  case BuiltinType::Dependent:
822    break;
823
824  case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
825    break;
826
827  case BuiltinType::ObjCId:
828    VisitType = Context.getObjCIdType();
829    break;
830
831  case BuiltinType::ObjCClass:
832    VisitType = Context.getObjCClassType();
833    break;
834
835  case BuiltinType::ObjCSel:
836    VisitType = Context.getObjCSelType();
837    break;
838  }
839
840  if (!VisitType.isNull()) {
841    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
842      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
843                                     TU));
844  }
845
846  return false;
847}
848
849bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
850  return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
851}
852
853bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
854  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
855}
856
857bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
858  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
859}
860
861bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
862  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
863    return true;
864
865  return false;
866}
867
868bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
869  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
870    return true;
871
872  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
873    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
874                                        TU)))
875      return true;
876  }
877
878  return false;
879}
880
881bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
882  return Visit(TL.getPointeeLoc());
883}
884
885bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
886  return Visit(TL.getPointeeLoc());
887}
888
889bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
890  return Visit(TL.getPointeeLoc());
891}
892
893bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
894  return Visit(TL.getPointeeLoc());
895}
896
897bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
898  return Visit(TL.getPointeeLoc());
899}
900
901bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
902  return Visit(TL.getPointeeLoc());
903}
904
905bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
906  if (Visit(TL.getResultLoc()))
907    return true;
908
909  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
910    if (Decl *D = TL.getArg(I))
911      if (Visit(MakeCXCursor(D, TU)))
912        return true;
913
914  return false;
915}
916
917bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
918  if (Visit(TL.getElementLoc()))
919    return true;
920
921  if (Expr *Size = TL.getSizeExpr())
922    return Visit(MakeCXCursor(Size, StmtParent, TU));
923
924  return false;
925}
926
927bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
928  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
929}
930
931bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
932  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
933    return Visit(TSInfo->getTypeLoc());
934
935  return false;
936}
937
938bool CursorVisitor::VisitStmt(Stmt *S) {
939  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
940       Child != ChildEnd; ++Child) {
941    if (Stmt *C = *Child)
942      if (Visit(MakeCXCursor(C, StmtParent, TU)))
943        return true;
944  }
945
946  return false;
947}
948
949bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
950  // Specially handle CaseStmts because they can be nested, e.g.:
951  //
952  //    case 1:
953  //    case 2:
954  //
955  // In this case the second CaseStmt is the child of the first.  Walking
956  // these recursively can blow out the stack.
957  CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
958  while (true) {
959    // Set the Parent field to Cursor, then back to its old value once we're
960    //   done.
961    SetParentRAII SetParent(Parent, StmtParent, Cursor);
962
963    if (Stmt *LHS = S->getLHS())
964      if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
965        return true;
966    if (Stmt *RHS = S->getRHS())
967      if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
968        return true;
969    if (Stmt *SubStmt = S->getSubStmt()) {
970      if (!isa<CaseStmt>(SubStmt))
971        return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
972
973      // Specially handle 'CaseStmt' so that we don't blow out the stack.
974      CaseStmt *CS = cast<CaseStmt>(SubStmt);
975      Cursor = MakeCXCursor(CS, StmtParent, TU);
976      if (RegionOfInterest.isValid()) {
977        SourceRange Range = CS->getSourceRange();
978        if (Range.isInvalid() || CompareRegionOfInterest(Range))
979          return false;
980      }
981
982      switch (Visitor(Cursor, Parent, ClientData)) {
983        case CXChildVisit_Break: return true;
984        case CXChildVisit_Continue: return false;
985        case CXChildVisit_Recurse:
986          // Perform tail-recursion manually.
987          S = CS;
988          continue;
989      }
990    }
991    return false;
992  }
993}
994
995bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
996  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
997       D != DEnd; ++D) {
998    if (*D && Visit(MakeCXCursor(*D, TU)))
999      return true;
1000  }
1001
1002  return false;
1003}
1004
1005bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1006  if (VarDecl *Var = S->getConditionVariable()) {
1007    if (Visit(MakeCXCursor(Var, TU)))
1008      return true;
1009  }
1010
1011  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1012    return true;
1013  if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1014    return true;
1015  if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1016    return true;
1017
1018  return false;
1019}
1020
1021bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1022  if (VarDecl *Var = S->getConditionVariable()) {
1023    if (Visit(MakeCXCursor(Var, TU)))
1024      return true;
1025  }
1026
1027  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1028    return true;
1029  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1030    return true;
1031
1032  return false;
1033}
1034
1035bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1036  if (VarDecl *Var = S->getConditionVariable()) {
1037    if (Visit(MakeCXCursor(Var, TU)))
1038      return true;
1039  }
1040
1041  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1042    return true;
1043  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1044    return true;
1045
1046  return false;
1047}
1048
1049bool CursorVisitor::VisitForStmt(ForStmt *S) {
1050  if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1051    return true;
1052  if (VarDecl *Var = S->getConditionVariable()) {
1053    if (Visit(MakeCXCursor(Var, TU)))
1054      return true;
1055  }
1056
1057  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1058    return true;
1059  if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1060    return true;
1061  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1062    return true;
1063
1064  return false;
1065}
1066
1067bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1068  if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1069    return true;
1070
1071  if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1072    return true;
1073
1074  for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1075    if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1076      return true;
1077
1078  return false;
1079}
1080
1081bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1082  return Visit(B->getBlockDecl());
1083}
1084
1085bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1086  // FIXME: Visit fields as well?
1087  if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1088    return true;
1089
1090  return VisitExpr(E);
1091}
1092
1093bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1094  if (E->isArgumentType()) {
1095    if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1096      return Visit(TSInfo->getTypeLoc());
1097
1098    return false;
1099  }
1100
1101  return VisitExpr(E);
1102}
1103
1104bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1105  if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1106    if (Visit(TSInfo->getTypeLoc()))
1107      return true;
1108
1109  return VisitCastExpr(E);
1110}
1111
1112bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1113  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1114    if (Visit(TSInfo->getTypeLoc()))
1115      return true;
1116
1117  return VisitExpr(E);
1118}
1119
1120bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1121  return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1122         Visit(E->getArgTInfo2()->getTypeLoc());
1123}
1124
1125bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1126  if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1127    return true;
1128
1129  return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1130}
1131
1132bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1133  if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1134    if (Visit(TSInfo->getTypeLoc()))
1135      return true;
1136
1137  return VisitExpr(E);
1138}
1139
1140bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1141  return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1142}
1143
1144
1145bool CursorVisitor::VisitAttributes(Decl *D) {
1146  for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1147    if (Visit(MakeCXCursor(A, D, TU)))
1148        return true;
1149
1150  return false;
1151}
1152
1153extern "C" {
1154CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1155                          int displayDiagnostics) {
1156  CIndexer *CIdxr = new CIndexer();
1157  if (excludeDeclarationsFromPCH)
1158    CIdxr->setOnlyLocalDecls();
1159  if (displayDiagnostics)
1160    CIdxr->setDisplayDiagnostics();
1161  return CIdxr;
1162}
1163
1164void clang_disposeIndex(CXIndex CIdx) {
1165  if (CIdx)
1166    delete static_cast<CIndexer *>(CIdx);
1167  if (getenv("LIBCLANG_TIMING"))
1168    llvm::TimerGroup::printAll(llvm::errs());
1169}
1170
1171void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
1172  if (CIdx) {
1173    CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1174    CXXIdx->setUseExternalASTGeneration(value);
1175  }
1176}
1177
1178CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
1179                                              const char *ast_filename) {
1180  if (!CIdx)
1181    return 0;
1182
1183  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1184
1185  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1186  return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
1187                                  CXXIdx->getOnlyLocalDecls(),
1188                                  0, 0, true);
1189}
1190
1191unsigned clang_defaultEditingTranslationUnitOptions() {
1192  return CXTranslationUnit_PrecompiledPreamble;
1193}
1194
1195CXTranslationUnit
1196clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1197                                          const char *source_filename,
1198                                          int num_command_line_args,
1199                                          const char **command_line_args,
1200                                          unsigned num_unsaved_files,
1201                                          struct CXUnsavedFile *unsaved_files) {
1202  return clang_parseTranslationUnit(CIdx, source_filename,
1203                                    command_line_args, num_command_line_args,
1204                                    unsaved_files, num_unsaved_files,
1205                                 CXTranslationUnit_DetailedPreprocessingRecord);
1206}
1207
1208CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1209                                             const char *source_filename,
1210                                             const char **command_line_args,
1211                                             int num_command_line_args,
1212                                             struct CXUnsavedFile *unsaved_files,
1213                                             unsigned num_unsaved_files,
1214                                             unsigned options) {
1215  if (!CIdx)
1216    return 0;
1217
1218  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1219
1220  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
1221  bool CompleteTranslationUnit
1222    = ((options & CXTranslationUnit_Incomplete) == 0);
1223  bool CacheCodeCompetionResults
1224    = options & CXTranslationUnit_CacheCompletionResults;
1225
1226  // Configure the diagnostics.
1227  DiagnosticOptions DiagOpts;
1228  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1229  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1230
1231  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1232  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1233    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1234    const llvm::MemoryBuffer *Buffer
1235      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1236    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1237                                           Buffer));
1238  }
1239
1240  if (!CXXIdx->getUseExternalASTGeneration()) {
1241    llvm::SmallVector<const char *, 16> Args;
1242
1243    // The 'source_filename' argument is optional.  If the caller does not
1244    // specify it then it is assumed that the source file is specified
1245    // in the actual argument list.
1246    if (source_filename)
1247      Args.push_back(source_filename);
1248
1249    // Since the Clang C library is primarily used by batch tools dealing with
1250    // (often very broken) source code, where spell-checking can have a
1251    // significant negative impact on performance (particularly when
1252    // precompiled headers are involved), we disable it by default.
1253    // Note that we place this argument early in the list, so that it can be
1254    // overridden by the caller with "-fspell-checking".
1255    Args.push_back("-fno-spell-checking");
1256
1257    Args.insert(Args.end(), command_line_args,
1258                command_line_args + num_command_line_args);
1259
1260    // Do we need the detailed preprocessing record?
1261    if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1262      Args.push_back("-Xclang");
1263      Args.push_back("-detailed-preprocessing-record");
1264    }
1265
1266    unsigned NumErrors = Diags->getNumErrors();
1267
1268#ifdef USE_CRASHTRACER
1269    ArgsCrashTracerInfo ACTI(Args);
1270#endif
1271
1272    llvm::OwningPtr<ASTUnit> Unit(
1273      ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
1274                                   Diags,
1275                                   CXXIdx->getClangResourcesPath(),
1276                                   CXXIdx->getOnlyLocalDecls(),
1277                                   RemappedFiles.data(),
1278                                   RemappedFiles.size(),
1279                                   /*CaptureDiagnostics=*/true,
1280                                   PrecompilePreamble,
1281                                   CompleteTranslationUnit,
1282                                   CacheCodeCompetionResults));
1283
1284    if (NumErrors != Diags->getNumErrors()) {
1285      // Make sure to check that 'Unit' is non-NULL.
1286      if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
1287        for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1288                                        DEnd = Unit->stored_diag_end();
1289             D != DEnd; ++D) {
1290          CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
1291          CXString Msg = clang_formatDiagnostic(&Diag,
1292                                      clang_defaultDiagnosticDisplayOptions());
1293          fprintf(stderr, "%s\n", clang_getCString(Msg));
1294          clang_disposeString(Msg);
1295        }
1296#ifdef LLVM_ON_WIN32
1297        // On Windows, force a flush, since there may be multiple copies of
1298        // stderr and stdout in the file system, all with different buffers
1299        // but writing to the same device.
1300        fflush(stderr);
1301#endif
1302      }
1303    }
1304
1305    return Unit.take();
1306  }
1307
1308  // Build up the arguments for invoking 'clang'.
1309  std::vector<const char *> argv;
1310
1311  // First add the complete path to the 'clang' executable.
1312  llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
1313  argv.push_back(ClangPath.c_str());
1314
1315  // Add the '-emit-ast' option as our execution mode for 'clang'.
1316  argv.push_back("-emit-ast");
1317
1318  // The 'source_filename' argument is optional.  If the caller does not
1319  // specify it then it is assumed that the source file is specified
1320  // in the actual argument list.
1321  if (source_filename)
1322    argv.push_back(source_filename);
1323
1324  // Generate a temporary name for the AST file.
1325  argv.push_back("-o");
1326  char astTmpFile[L_tmpnam];
1327  argv.push_back(tmpnam(astTmpFile));
1328
1329  // Since the Clang C library is primarily used by batch tools dealing with
1330  // (often very broken) source code, where spell-checking can have a
1331  // significant negative impact on performance (particularly when
1332  // precompiled headers are involved), we disable it by default.
1333  // Note that we place this argument early in the list, so that it can be
1334  // overridden by the caller with "-fspell-checking".
1335  argv.push_back("-fno-spell-checking");
1336
1337  // Remap any unsaved files to temporary files.
1338  std::vector<llvm::sys::Path> TemporaryFiles;
1339  std::vector<std::string> RemapArgs;
1340  if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1341    return 0;
1342
1343  // The pointers into the elements of RemapArgs are stable because we
1344  // won't be adding anything to RemapArgs after this point.
1345  for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1346    argv.push_back(RemapArgs[i].c_str());
1347
1348  // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1349  for (int i = 0; i < num_command_line_args; ++i)
1350    if (const char *arg = command_line_args[i]) {
1351      if (strcmp(arg, "-o") == 0) {
1352        ++i; // Also skip the matching argument.
1353        continue;
1354      }
1355      if (strcmp(arg, "-emit-ast") == 0 ||
1356          strcmp(arg, "-c") == 0 ||
1357          strcmp(arg, "-fsyntax-only") == 0) {
1358        continue;
1359      }
1360
1361      // Keep the argument.
1362      argv.push_back(arg);
1363    }
1364
1365  // Generate a temporary name for the diagnostics file.
1366  char tmpFileResults[L_tmpnam];
1367  char *tmpResultsFileName = tmpnam(tmpFileResults);
1368  llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1369  TemporaryFiles.push_back(DiagnosticsFile);
1370  argv.push_back("-fdiagnostics-binary");
1371
1372  // Do we need the detailed preprocessing record?
1373  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1374    argv.push_back("-Xclang");
1375    argv.push_back("-detailed-preprocessing-record");
1376  }
1377
1378  // Add the null terminator.
1379  argv.push_back(NULL);
1380
1381  // Invoke 'clang'.
1382  llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1383                           // on Unix or NUL (Windows).
1384  std::string ErrMsg;
1385  const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1386                                         NULL };
1387  llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1388      /* redirects */ &Redirects[0],
1389      /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
1390
1391  if (!ErrMsg.empty()) {
1392    std::string AllArgs;
1393    for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1394         I != E; ++I) {
1395      AllArgs += ' ';
1396      if (*I)
1397        AllArgs += *I;
1398    }
1399
1400    Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
1401  }
1402
1403  ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
1404                                          CXXIdx->getOnlyLocalDecls(),
1405                                          RemappedFiles.data(),
1406                                          RemappedFiles.size(),
1407                                          /*CaptureDiagnostics=*/true);
1408  if (ATU) {
1409    LoadSerializedDiagnostics(DiagnosticsFile,
1410                              num_unsaved_files, unsaved_files,
1411                              ATU->getFileManager(),
1412                              ATU->getSourceManager(),
1413                              ATU->getStoredDiagnostics());
1414  } else if (CXXIdx->getDisplayDiagnostics()) {
1415    // We failed to load the ASTUnit, but we can still deserialize the
1416    // diagnostics and emit them.
1417    FileManager FileMgr;
1418    Diagnostic Diag;
1419    SourceManager SourceMgr(Diag);
1420    // FIXME: Faked LangOpts!
1421    LangOptions LangOpts;
1422    llvm::SmallVector<StoredDiagnostic, 4> Diags;
1423    LoadSerializedDiagnostics(DiagnosticsFile,
1424                              num_unsaved_files, unsaved_files,
1425                              FileMgr, SourceMgr, Diags);
1426    for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1427                                                       DEnd = Diags.end();
1428         D != DEnd; ++D) {
1429      CXStoredDiagnostic Diag(*D, LangOpts);
1430      CXString Msg = clang_formatDiagnostic(&Diag,
1431                                      clang_defaultDiagnosticDisplayOptions());
1432      fprintf(stderr, "%s\n", clang_getCString(Msg));
1433      clang_disposeString(Msg);
1434    }
1435
1436#ifdef LLVM_ON_WIN32
1437    // On Windows, force a flush, since there may be multiple copies of
1438    // stderr and stdout in the file system, all with different buffers
1439    // but writing to the same device.
1440    fflush(stderr);
1441#endif
1442  }
1443
1444  if (ATU) {
1445    // Make the translation unit responsible for destroying all temporary files.
1446    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1447      ATU->addTemporaryFile(TemporaryFiles[i]);
1448    ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1449  } else {
1450    // Destroy all of the temporary files now; they can't be referenced any
1451    // longer.
1452    llvm::sys::Path(astTmpFile).eraseFromDisk();
1453    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1454      TemporaryFiles[i].eraseFromDisk();
1455  }
1456
1457  return ATU;
1458}
1459
1460unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1461  return CXSaveTranslationUnit_None;
1462}
1463
1464int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1465                              unsigned options) {
1466  if (!TU)
1467    return 1;
1468
1469  return static_cast<ASTUnit *>(TU)->Save(FileName);
1470}
1471
1472void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
1473  if (CTUnit)
1474    delete static_cast<ASTUnit *>(CTUnit);
1475}
1476
1477unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1478  return CXReparse_None;
1479}
1480
1481int clang_reparseTranslationUnit(CXTranslationUnit TU,
1482                                 unsigned num_unsaved_files,
1483                                 struct CXUnsavedFile *unsaved_files,
1484                                 unsigned options) {
1485  if (!TU)
1486    return 1;
1487
1488  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1489  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1490    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1491    const llvm::MemoryBuffer *Buffer
1492      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1493    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1494                                           Buffer));
1495  }
1496
1497  return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1498                                             RemappedFiles.size())? 1 : 0;
1499}
1500
1501CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
1502  if (!CTUnit)
1503    return createCXString("");
1504
1505  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
1506  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
1507}
1508
1509CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
1510  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
1511  return Result;
1512}
1513
1514} // end: extern "C"
1515
1516//===----------------------------------------------------------------------===//
1517// CXSourceLocation and CXSourceRange Operations.
1518//===----------------------------------------------------------------------===//
1519
1520extern "C" {
1521CXSourceLocation clang_getNullLocation() {
1522  CXSourceLocation Result = { { 0, 0 }, 0 };
1523  return Result;
1524}
1525
1526unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1527  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1528          loc1.ptr_data[1] == loc2.ptr_data[1] &&
1529          loc1.int_data == loc2.int_data);
1530}
1531
1532CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1533                                   CXFile file,
1534                                   unsigned line,
1535                                   unsigned column) {
1536  if (!tu || !file)
1537    return clang_getNullLocation();
1538
1539  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1540  SourceLocation SLoc
1541    = CXXUnit->getSourceManager().getLocation(
1542                                        static_cast<const FileEntry *>(file),
1543                                              line, column);
1544
1545  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
1546}
1547
1548CXSourceRange clang_getNullRange() {
1549  CXSourceRange Result = { { 0, 0 }, 0, 0 };
1550  return Result;
1551}
1552
1553CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1554  if (begin.ptr_data[0] != end.ptr_data[0] ||
1555      begin.ptr_data[1] != end.ptr_data[1])
1556    return clang_getNullRange();
1557
1558  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1559                           begin.int_data, end.int_data };
1560  return Result;
1561}
1562
1563void clang_getInstantiationLocation(CXSourceLocation location,
1564                                    CXFile *file,
1565                                    unsigned *line,
1566                                    unsigned *column,
1567                                    unsigned *offset) {
1568  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1569
1570  if (!location.ptr_data[0] || Loc.isInvalid()) {
1571    if (file)
1572      *file = 0;
1573    if (line)
1574      *line = 0;
1575    if (column)
1576      *column = 0;
1577    if (offset)
1578      *offset = 0;
1579    return;
1580  }
1581
1582  const SourceManager &SM =
1583    *static_cast<const SourceManager*>(location.ptr_data[0]);
1584  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1585
1586  if (file)
1587    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1588  if (line)
1589    *line = SM.getInstantiationLineNumber(InstLoc);
1590  if (column)
1591    *column = SM.getInstantiationColumnNumber(InstLoc);
1592  if (offset)
1593    *offset = SM.getDecomposedLoc(InstLoc).second;
1594}
1595
1596CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1597  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1598                              range.begin_int_data };
1599  return Result;
1600}
1601
1602CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1603  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1604                              range.end_int_data };
1605  return Result;
1606}
1607
1608} // end: extern "C"
1609
1610//===----------------------------------------------------------------------===//
1611// CXFile Operations.
1612//===----------------------------------------------------------------------===//
1613
1614extern "C" {
1615CXString clang_getFileName(CXFile SFile) {
1616  if (!SFile)
1617    return createCXString(NULL);
1618
1619  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1620  return createCXString(FEnt->getName());
1621}
1622
1623time_t clang_getFileTime(CXFile SFile) {
1624  if (!SFile)
1625    return 0;
1626
1627  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1628  return FEnt->getModificationTime();
1629}
1630
1631CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1632  if (!tu)
1633    return 0;
1634
1635  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1636
1637  FileManager &FMgr = CXXUnit->getFileManager();
1638  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1639  return const_cast<FileEntry *>(File);
1640}
1641
1642} // end: extern "C"
1643
1644//===----------------------------------------------------------------------===//
1645// CXCursor Operations.
1646//===----------------------------------------------------------------------===//
1647
1648static Decl *getDeclFromExpr(Stmt *E) {
1649  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1650    return RefExpr->getDecl();
1651  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1652    return ME->getMemberDecl();
1653  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1654    return RE->getDecl();
1655
1656  if (CallExpr *CE = dyn_cast<CallExpr>(E))
1657    return getDeclFromExpr(CE->getCallee());
1658  if (CastExpr *CE = dyn_cast<CastExpr>(E))
1659    return getDeclFromExpr(CE->getSubExpr());
1660  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1661    return OME->getMethodDecl();
1662
1663  return 0;
1664}
1665
1666static SourceLocation getLocationFromExpr(Expr *E) {
1667  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1668    return /*FIXME:*/Msg->getLeftLoc();
1669  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1670    return DRE->getLocation();
1671  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1672    return Member->getMemberLoc();
1673  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1674    return Ivar->getLocation();
1675  return E->getLocStart();
1676}
1677
1678extern "C" {
1679
1680unsigned clang_visitChildren(CXCursor parent,
1681                             CXCursorVisitor visitor,
1682                             CXClientData client_data) {
1683  ASTUnit *CXXUnit = getCursorASTUnit(parent);
1684
1685  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1686                          CXXUnit->getMaxPCHLevel());
1687  return CursorVis.VisitChildren(parent);
1688}
1689
1690static CXString getDeclSpelling(Decl *D) {
1691  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1692  if (!ND)
1693    return createCXString("");
1694
1695  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1696    return createCXString(OMD->getSelector().getAsString());
1697
1698  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1699    // No, this isn't the same as the code below. getIdentifier() is non-virtual
1700    // and returns different names. NamedDecl returns the class name and
1701    // ObjCCategoryImplDecl returns the category name.
1702    return createCXString(CIMP->getIdentifier()->getNameStart());
1703
1704  llvm::SmallString<1024> S;
1705  llvm::raw_svector_ostream os(S);
1706  ND->printName(os);
1707
1708  return createCXString(os.str());
1709}
1710
1711CXString clang_getCursorSpelling(CXCursor C) {
1712  if (clang_isTranslationUnit(C.kind))
1713    return clang_getTranslationUnitSpelling(C.data[2]);
1714
1715  if (clang_isReference(C.kind)) {
1716    switch (C.kind) {
1717    case CXCursor_ObjCSuperClassRef: {
1718      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1719      return createCXString(Super->getIdentifier()->getNameStart());
1720    }
1721    case CXCursor_ObjCClassRef: {
1722      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1723      return createCXString(Class->getIdentifier()->getNameStart());
1724    }
1725    case CXCursor_ObjCProtocolRef: {
1726      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
1727      assert(OID && "getCursorSpelling(): Missing protocol decl");
1728      return createCXString(OID->getIdentifier()->getNameStart());
1729    }
1730    case CXCursor_TypeRef: {
1731      TypeDecl *Type = getCursorTypeRef(C).first;
1732      assert(Type && "Missing type decl");
1733
1734      return createCXString(getCursorContext(C).getTypeDeclType(Type).
1735                              getAsString());
1736    }
1737
1738    default:
1739      return createCXString("<not implemented>");
1740    }
1741  }
1742
1743  if (clang_isExpression(C.kind)) {
1744    Decl *D = getDeclFromExpr(getCursorExpr(C));
1745    if (D)
1746      return getDeclSpelling(D);
1747    return createCXString("");
1748  }
1749
1750  if (C.kind == CXCursor_MacroInstantiation)
1751    return createCXString(getCursorMacroInstantiation(C)->getName()
1752                                                           ->getNameStart());
1753
1754  if (C.kind == CXCursor_MacroDefinition)
1755    return createCXString(getCursorMacroDefinition(C)->getName()
1756                                                           ->getNameStart());
1757
1758  if (clang_isDeclaration(C.kind))
1759    return getDeclSpelling(getCursorDecl(C));
1760
1761  return createCXString("");
1762}
1763
1764CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
1765  switch (Kind) {
1766  case CXCursor_FunctionDecl:
1767      return createCXString("FunctionDecl");
1768  case CXCursor_TypedefDecl:
1769      return createCXString("TypedefDecl");
1770  case CXCursor_EnumDecl:
1771      return createCXString("EnumDecl");
1772  case CXCursor_EnumConstantDecl:
1773      return createCXString("EnumConstantDecl");
1774  case CXCursor_StructDecl:
1775      return createCXString("StructDecl");
1776  case CXCursor_UnionDecl:
1777      return createCXString("UnionDecl");
1778  case CXCursor_ClassDecl:
1779      return createCXString("ClassDecl");
1780  case CXCursor_FieldDecl:
1781      return createCXString("FieldDecl");
1782  case CXCursor_VarDecl:
1783      return createCXString("VarDecl");
1784  case CXCursor_ParmDecl:
1785      return createCXString("ParmDecl");
1786  case CXCursor_ObjCInterfaceDecl:
1787      return createCXString("ObjCInterfaceDecl");
1788  case CXCursor_ObjCCategoryDecl:
1789      return createCXString("ObjCCategoryDecl");
1790  case CXCursor_ObjCProtocolDecl:
1791      return createCXString("ObjCProtocolDecl");
1792  case CXCursor_ObjCPropertyDecl:
1793      return createCXString("ObjCPropertyDecl");
1794  case CXCursor_ObjCIvarDecl:
1795      return createCXString("ObjCIvarDecl");
1796  case CXCursor_ObjCInstanceMethodDecl:
1797      return createCXString("ObjCInstanceMethodDecl");
1798  case CXCursor_ObjCClassMethodDecl:
1799      return createCXString("ObjCClassMethodDecl");
1800  case CXCursor_ObjCImplementationDecl:
1801      return createCXString("ObjCImplementationDecl");
1802  case CXCursor_ObjCCategoryImplDecl:
1803      return createCXString("ObjCCategoryImplDecl");
1804  case CXCursor_CXXMethod:
1805      return createCXString("CXXMethod");
1806  case CXCursor_UnexposedDecl:
1807      return createCXString("UnexposedDecl");
1808  case CXCursor_ObjCSuperClassRef:
1809      return createCXString("ObjCSuperClassRef");
1810  case CXCursor_ObjCProtocolRef:
1811      return createCXString("ObjCProtocolRef");
1812  case CXCursor_ObjCClassRef:
1813      return createCXString("ObjCClassRef");
1814  case CXCursor_TypeRef:
1815      return createCXString("TypeRef");
1816  case CXCursor_UnexposedExpr:
1817      return createCXString("UnexposedExpr");
1818  case CXCursor_BlockExpr:
1819      return createCXString("BlockExpr");
1820  case CXCursor_DeclRefExpr:
1821      return createCXString("DeclRefExpr");
1822  case CXCursor_MemberRefExpr:
1823      return createCXString("MemberRefExpr");
1824  case CXCursor_CallExpr:
1825      return createCXString("CallExpr");
1826  case CXCursor_ObjCMessageExpr:
1827      return createCXString("ObjCMessageExpr");
1828  case CXCursor_UnexposedStmt:
1829      return createCXString("UnexposedStmt");
1830  case CXCursor_InvalidFile:
1831      return createCXString("InvalidFile");
1832  case CXCursor_InvalidCode:
1833    return createCXString("InvalidCode");
1834  case CXCursor_NoDeclFound:
1835      return createCXString("NoDeclFound");
1836  case CXCursor_NotImplemented:
1837      return createCXString("NotImplemented");
1838  case CXCursor_TranslationUnit:
1839      return createCXString("TranslationUnit");
1840  case CXCursor_UnexposedAttr:
1841      return createCXString("UnexposedAttr");
1842  case CXCursor_IBActionAttr:
1843      return createCXString("attribute(ibaction)");
1844  case CXCursor_IBOutletAttr:
1845     return createCXString("attribute(iboutlet)");
1846  case CXCursor_IBOutletCollectionAttr:
1847      return createCXString("attribute(iboutletcollection)");
1848  case CXCursor_PreprocessingDirective:
1849    return createCXString("preprocessing directive");
1850  case CXCursor_MacroDefinition:
1851    return createCXString("macro definition");
1852  case CXCursor_MacroInstantiation:
1853    return createCXString("macro instantiation");
1854  case CXCursor_Namespace:
1855    return createCXString("Namespace");
1856  case CXCursor_LinkageSpec:
1857    return createCXString("LinkageSpec");
1858  }
1859
1860  llvm_unreachable("Unhandled CXCursorKind");
1861  return createCXString(NULL);
1862}
1863
1864enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1865                                         CXCursor parent,
1866                                         CXClientData client_data) {
1867  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1868  *BestCursor = cursor;
1869  return CXChildVisit_Recurse;
1870}
1871
1872CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1873  if (!TU)
1874    return clang_getNullCursor();
1875
1876  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1877  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1878
1879  // Translate the given source location to make it point at the beginning of
1880  // the token under the cursor.
1881  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
1882
1883  // Guard against an invalid SourceLocation, or we may assert in one
1884  // of the following calls.
1885  if (SLoc.isInvalid())
1886    return clang_getNullCursor();
1887
1888  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1889                                    CXXUnit->getASTContext().getLangOptions());
1890
1891  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1892  if (SLoc.isValid()) {
1893    // FIXME: Would be great to have a "hint" cursor, then walk from that
1894    // hint cursor upward until we find a cursor whose source range encloses
1895    // the region of interest, rather than starting from the translation unit.
1896    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1897    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1898                            Decl::MaxPCHLevel, SourceLocation(SLoc));
1899    CursorVis.VisitChildren(Parent);
1900  }
1901  return Result;
1902}
1903
1904CXCursor clang_getNullCursor(void) {
1905  return MakeCXCursorInvalid(CXCursor_InvalidFile);
1906}
1907
1908unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
1909  return X == Y;
1910}
1911
1912unsigned clang_isInvalid(enum CXCursorKind K) {
1913  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1914}
1915
1916unsigned clang_isDeclaration(enum CXCursorKind K) {
1917  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1918}
1919
1920unsigned clang_isReference(enum CXCursorKind K) {
1921  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1922}
1923
1924unsigned clang_isExpression(enum CXCursorKind K) {
1925  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1926}
1927
1928unsigned clang_isStatement(enum CXCursorKind K) {
1929  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1930}
1931
1932unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1933  return K == CXCursor_TranslationUnit;
1934}
1935
1936unsigned clang_isPreprocessing(enum CXCursorKind K) {
1937  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1938}
1939
1940unsigned clang_isUnexposed(enum CXCursorKind K) {
1941  switch (K) {
1942    case CXCursor_UnexposedDecl:
1943    case CXCursor_UnexposedExpr:
1944    case CXCursor_UnexposedStmt:
1945    case CXCursor_UnexposedAttr:
1946      return true;
1947    default:
1948      return false;
1949  }
1950}
1951
1952CXCursorKind clang_getCursorKind(CXCursor C) {
1953  return C.kind;
1954}
1955
1956CXSourceLocation clang_getCursorLocation(CXCursor C) {
1957  if (clang_isReference(C.kind)) {
1958    switch (C.kind) {
1959    case CXCursor_ObjCSuperClassRef: {
1960      std::pair<ObjCInterfaceDecl *, SourceLocation> P
1961        = getCursorObjCSuperClassRef(C);
1962      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
1963    }
1964
1965    case CXCursor_ObjCProtocolRef: {
1966      std::pair<ObjCProtocolDecl *, SourceLocation> P
1967        = getCursorObjCProtocolRef(C);
1968      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
1969    }
1970
1971    case CXCursor_ObjCClassRef: {
1972      std::pair<ObjCInterfaceDecl *, SourceLocation> P
1973        = getCursorObjCClassRef(C);
1974      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
1975    }
1976
1977    case CXCursor_TypeRef: {
1978      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1979      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
1980    }
1981
1982    default:
1983      // FIXME: Need a way to enumerate all non-reference cases.
1984      llvm_unreachable("Missed a reference kind");
1985    }
1986  }
1987
1988  if (clang_isExpression(C.kind))
1989    return cxloc::translateSourceLocation(getCursorContext(C),
1990                                   getLocationFromExpr(getCursorExpr(C)));
1991
1992  if (C.kind == CXCursor_PreprocessingDirective) {
1993    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1994    return cxloc::translateSourceLocation(getCursorContext(C), L);
1995  }
1996
1997  if (C.kind == CXCursor_MacroInstantiation) {
1998    SourceLocation L
1999      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
2000    return cxloc::translateSourceLocation(getCursorContext(C), L);
2001  }
2002
2003  if (C.kind == CXCursor_MacroDefinition) {
2004    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2005    return cxloc::translateSourceLocation(getCursorContext(C), L);
2006  }
2007
2008  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
2009    return clang_getNullLocation();
2010
2011  Decl *D = getCursorDecl(C);
2012  SourceLocation Loc = D->getLocation();
2013  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2014    Loc = Class->getClassLoc();
2015  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
2016}
2017
2018} // end extern "C"
2019
2020static SourceRange getRawCursorExtent(CXCursor C) {
2021  if (clang_isReference(C.kind)) {
2022    switch (C.kind) {
2023    case CXCursor_ObjCSuperClassRef:
2024      return  getCursorObjCSuperClassRef(C).second;
2025
2026    case CXCursor_ObjCProtocolRef:
2027      return getCursorObjCProtocolRef(C).second;
2028
2029    case CXCursor_ObjCClassRef:
2030      return getCursorObjCClassRef(C).second;
2031
2032    case CXCursor_TypeRef:
2033      return getCursorTypeRef(C).second;
2034
2035    default:
2036      // FIXME: Need a way to enumerate all non-reference cases.
2037      llvm_unreachable("Missed a reference kind");
2038    }
2039  }
2040
2041  if (clang_isExpression(C.kind))
2042    return getCursorExpr(C)->getSourceRange();
2043
2044  if (clang_isStatement(C.kind))
2045    return getCursorStmt(C)->getSourceRange();
2046
2047  if (C.kind == CXCursor_PreprocessingDirective)
2048    return cxcursor::getCursorPreprocessingDirective(C);
2049
2050  if (C.kind == CXCursor_MacroInstantiation)
2051    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
2052
2053  if (C.kind == CXCursor_MacroDefinition)
2054    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
2055
2056  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2057    return getCursorDecl(C)->getSourceRange();
2058
2059  return SourceRange();
2060}
2061
2062extern "C" {
2063
2064CXSourceRange clang_getCursorExtent(CXCursor C) {
2065  SourceRange R = getRawCursorExtent(C);
2066  if (R.isInvalid())
2067    return clang_getNullRange();
2068
2069  return cxloc::translateSourceRange(getCursorContext(C), R);
2070}
2071
2072CXCursor clang_getCursorReferenced(CXCursor C) {
2073  if (clang_isInvalid(C.kind))
2074    return clang_getNullCursor();
2075
2076  ASTUnit *CXXUnit = getCursorASTUnit(C);
2077  if (clang_isDeclaration(C.kind))
2078    return C;
2079
2080  if (clang_isExpression(C.kind)) {
2081    Decl *D = getDeclFromExpr(getCursorExpr(C));
2082    if (D)
2083      return MakeCXCursor(D, CXXUnit);
2084    return clang_getNullCursor();
2085  }
2086
2087  if (C.kind == CXCursor_MacroInstantiation) {
2088    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2089      return MakeMacroDefinitionCursor(Def, CXXUnit);
2090  }
2091
2092  if (!clang_isReference(C.kind))
2093    return clang_getNullCursor();
2094
2095  switch (C.kind) {
2096    case CXCursor_ObjCSuperClassRef:
2097      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
2098
2099    case CXCursor_ObjCProtocolRef: {
2100      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
2101
2102    case CXCursor_ObjCClassRef:
2103      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
2104
2105    case CXCursor_TypeRef:
2106      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
2107
2108    default:
2109      // We would prefer to enumerate all non-reference cursor kinds here.
2110      llvm_unreachable("Unhandled reference cursor kind");
2111      break;
2112    }
2113  }
2114
2115  return clang_getNullCursor();
2116}
2117
2118CXCursor clang_getCursorDefinition(CXCursor C) {
2119  if (clang_isInvalid(C.kind))
2120    return clang_getNullCursor();
2121
2122  ASTUnit *CXXUnit = getCursorASTUnit(C);
2123
2124  bool WasReference = false;
2125  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
2126    C = clang_getCursorReferenced(C);
2127    WasReference = true;
2128  }
2129
2130  if (C.kind == CXCursor_MacroInstantiation)
2131    return clang_getCursorReferenced(C);
2132
2133  if (!clang_isDeclaration(C.kind))
2134    return clang_getNullCursor();
2135
2136  Decl *D = getCursorDecl(C);
2137  if (!D)
2138    return clang_getNullCursor();
2139
2140  switch (D->getKind()) {
2141  // Declaration kinds that don't really separate the notions of
2142  // declaration and definition.
2143  case Decl::Namespace:
2144  case Decl::Typedef:
2145  case Decl::TemplateTypeParm:
2146  case Decl::EnumConstant:
2147  case Decl::Field:
2148  case Decl::ObjCIvar:
2149  case Decl::ObjCAtDefsField:
2150  case Decl::ImplicitParam:
2151  case Decl::ParmVar:
2152  case Decl::NonTypeTemplateParm:
2153  case Decl::TemplateTemplateParm:
2154  case Decl::ObjCCategoryImpl:
2155  case Decl::ObjCImplementation:
2156  case Decl::AccessSpec:
2157  case Decl::LinkageSpec:
2158  case Decl::ObjCPropertyImpl:
2159  case Decl::FileScopeAsm:
2160  case Decl::StaticAssert:
2161  case Decl::Block:
2162    return C;
2163
2164  // Declaration kinds that don't make any sense here, but are
2165  // nonetheless harmless.
2166  case Decl::TranslationUnit:
2167    break;
2168
2169  // Declaration kinds for which the definition is not resolvable.
2170  case Decl::UnresolvedUsingTypename:
2171  case Decl::UnresolvedUsingValue:
2172    break;
2173
2174  case Decl::UsingDirective:
2175    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2176                        CXXUnit);
2177
2178  case Decl::NamespaceAlias:
2179    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
2180
2181  case Decl::Enum:
2182  case Decl::Record:
2183  case Decl::CXXRecord:
2184  case Decl::ClassTemplateSpecialization:
2185  case Decl::ClassTemplatePartialSpecialization:
2186    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
2187      return MakeCXCursor(Def, CXXUnit);
2188    return clang_getNullCursor();
2189
2190  case Decl::Function:
2191  case Decl::CXXMethod:
2192  case Decl::CXXConstructor:
2193  case Decl::CXXDestructor:
2194  case Decl::CXXConversion: {
2195    const FunctionDecl *Def = 0;
2196    if (cast<FunctionDecl>(D)->getBody(Def))
2197      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
2198    return clang_getNullCursor();
2199  }
2200
2201  case Decl::Var: {
2202    // Ask the variable if it has a definition.
2203    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2204      return MakeCXCursor(Def, CXXUnit);
2205    return clang_getNullCursor();
2206  }
2207
2208  case Decl::FunctionTemplate: {
2209    const FunctionDecl *Def = 0;
2210    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
2211      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
2212    return clang_getNullCursor();
2213  }
2214
2215  case Decl::ClassTemplate: {
2216    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
2217                                                            ->getDefinition())
2218      return MakeCXCursor(
2219                         cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
2220                          CXXUnit);
2221    return clang_getNullCursor();
2222  }
2223
2224  case Decl::Using: {
2225    UsingDecl *Using = cast<UsingDecl>(D);
2226    CXCursor Def = clang_getNullCursor();
2227    for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2228                                 SEnd = Using->shadow_end();
2229         S != SEnd; ++S) {
2230      if (Def != clang_getNullCursor()) {
2231        // FIXME: We have no way to return multiple results.
2232        return clang_getNullCursor();
2233      }
2234
2235      Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
2236                                                   CXXUnit));
2237    }
2238
2239    return Def;
2240  }
2241
2242  case Decl::UsingShadow:
2243    return clang_getCursorDefinition(
2244                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
2245                                    CXXUnit));
2246
2247  case Decl::ObjCMethod: {
2248    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2249    if (Method->isThisDeclarationADefinition())
2250      return C;
2251
2252    // Dig out the method definition in the associated
2253    // @implementation, if we have it.
2254    // FIXME: The ASTs should make finding the definition easier.
2255    if (ObjCInterfaceDecl *Class
2256                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2257      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2258        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2259                                                  Method->isInstanceMethod()))
2260          if (Def->isThisDeclarationADefinition())
2261            return MakeCXCursor(Def, CXXUnit);
2262
2263    return clang_getNullCursor();
2264  }
2265
2266  case Decl::ObjCCategory:
2267    if (ObjCCategoryImplDecl *Impl
2268                               = cast<ObjCCategoryDecl>(D)->getImplementation())
2269      return MakeCXCursor(Impl, CXXUnit);
2270    return clang_getNullCursor();
2271
2272  case Decl::ObjCProtocol:
2273    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2274      return C;
2275    return clang_getNullCursor();
2276
2277  case Decl::ObjCInterface:
2278    // There are two notions of a "definition" for an Objective-C
2279    // class: the interface and its implementation. When we resolved a
2280    // reference to an Objective-C class, produce the @interface as
2281    // the definition; when we were provided with the interface,
2282    // produce the @implementation as the definition.
2283    if (WasReference) {
2284      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2285        return C;
2286    } else if (ObjCImplementationDecl *Impl
2287                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
2288      return MakeCXCursor(Impl, CXXUnit);
2289    return clang_getNullCursor();
2290
2291  case Decl::ObjCProperty:
2292    // FIXME: We don't really know where to find the
2293    // ObjCPropertyImplDecls that implement this property.
2294    return clang_getNullCursor();
2295
2296  case Decl::ObjCCompatibleAlias:
2297    if (ObjCInterfaceDecl *Class
2298          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2299      if (!Class->isForwardDecl())
2300        return MakeCXCursor(Class, CXXUnit);
2301
2302    return clang_getNullCursor();
2303
2304  case Decl::ObjCForwardProtocol: {
2305    ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2306    if (Forward->protocol_size() == 1)
2307      return clang_getCursorDefinition(
2308                                     MakeCXCursor(*Forward->protocol_begin(),
2309                                                  CXXUnit));
2310
2311    // FIXME: Cannot return multiple definitions.
2312    return clang_getNullCursor();
2313  }
2314
2315  case Decl::ObjCClass: {
2316    ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2317    if (Class->size() == 1) {
2318      ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2319      if (!IFace->isForwardDecl())
2320        return MakeCXCursor(IFace, CXXUnit);
2321      return clang_getNullCursor();
2322    }
2323
2324    // FIXME: Cannot return multiple definitions.
2325    return clang_getNullCursor();
2326  }
2327
2328  case Decl::Friend:
2329    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
2330      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2331    return clang_getNullCursor();
2332
2333  case Decl::FriendTemplate:
2334    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
2335      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2336    return clang_getNullCursor();
2337  }
2338
2339  return clang_getNullCursor();
2340}
2341
2342unsigned clang_isCursorDefinition(CXCursor C) {
2343  if (!clang_isDeclaration(C.kind))
2344    return 0;
2345
2346  return clang_getCursorDefinition(C) == C;
2347}
2348
2349void clang_getDefinitionSpellingAndExtent(CXCursor C,
2350                                          const char **startBuf,
2351                                          const char **endBuf,
2352                                          unsigned *startLine,
2353                                          unsigned *startColumn,
2354                                          unsigned *endLine,
2355                                          unsigned *endColumn) {
2356  assert(getCursorDecl(C) && "CXCursor has null decl");
2357  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
2358  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2359  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
2360
2361  SourceManager &SM = FD->getASTContext().getSourceManager();
2362  *startBuf = SM.getCharacterData(Body->getLBracLoc());
2363  *endBuf = SM.getCharacterData(Body->getRBracLoc());
2364  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2365  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2366  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2367  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2368}
2369
2370void clang_enableStackTraces(void) {
2371  llvm::sys::PrintStackTraceOnErrorSignal();
2372}
2373
2374} // end: extern "C"
2375
2376//===----------------------------------------------------------------------===//
2377// Token-based Operations.
2378//===----------------------------------------------------------------------===//
2379
2380/* CXToken layout:
2381 *   int_data[0]: a CXTokenKind
2382 *   int_data[1]: starting token location
2383 *   int_data[2]: token length
2384 *   int_data[3]: reserved
2385 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
2386 *   otherwise unused.
2387 */
2388extern "C" {
2389
2390CXTokenKind clang_getTokenKind(CXToken CXTok) {
2391  return static_cast<CXTokenKind>(CXTok.int_data[0]);
2392}
2393
2394CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2395  switch (clang_getTokenKind(CXTok)) {
2396  case CXToken_Identifier:
2397  case CXToken_Keyword:
2398    // We know we have an IdentifierInfo*, so use that.
2399    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2400                            ->getNameStart());
2401
2402  case CXToken_Literal: {
2403    // We have stashed the starting pointer in the ptr_data field. Use it.
2404    const char *Text = static_cast<const char *>(CXTok.ptr_data);
2405    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
2406  }
2407
2408  case CXToken_Punctuation:
2409  case CXToken_Comment:
2410    break;
2411  }
2412
2413  // We have to find the starting buffer pointer the hard way, by
2414  // deconstructing the source location.
2415  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2416  if (!CXXUnit)
2417    return createCXString("");
2418
2419  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2420  std::pair<FileID, unsigned> LocInfo
2421    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
2422  bool Invalid = false;
2423  llvm::StringRef Buffer
2424    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2425  if (Invalid)
2426    return createCXString("");
2427
2428  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
2429}
2430
2431CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2432  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2433  if (!CXXUnit)
2434    return clang_getNullLocation();
2435
2436  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2437                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2438}
2439
2440CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2441  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2442  if (!CXXUnit)
2443    return clang_getNullRange();
2444
2445  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
2446                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2447}
2448
2449void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2450                    CXToken **Tokens, unsigned *NumTokens) {
2451  if (Tokens)
2452    *Tokens = 0;
2453  if (NumTokens)
2454    *NumTokens = 0;
2455
2456  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2457  if (!CXXUnit || !Tokens || !NumTokens)
2458    return;
2459
2460  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2461
2462  SourceRange R = cxloc::translateCXSourceRange(Range);
2463  if (R.isInvalid())
2464    return;
2465
2466  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2467  std::pair<FileID, unsigned> BeginLocInfo
2468    = SourceMgr.getDecomposedLoc(R.getBegin());
2469  std::pair<FileID, unsigned> EndLocInfo
2470    = SourceMgr.getDecomposedLoc(R.getEnd());
2471
2472  // Cannot tokenize across files.
2473  if (BeginLocInfo.first != EndLocInfo.first)
2474    return;
2475
2476  // Create a lexer
2477  bool Invalid = false;
2478  llvm::StringRef Buffer
2479    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
2480  if (Invalid)
2481    return;
2482
2483  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2484            CXXUnit->getASTContext().getLangOptions(),
2485            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
2486  Lex.SetCommentRetentionState(true);
2487
2488  // Lex tokens until we hit the end of the range.
2489  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
2490  llvm::SmallVector<CXToken, 32> CXTokens;
2491  Token Tok;
2492  do {
2493    // Lex the next token
2494    Lex.LexFromRawLexer(Tok);
2495    if (Tok.is(tok::eof))
2496      break;
2497
2498    // Initialize the CXToken.
2499    CXToken CXTok;
2500
2501    //   - Common fields
2502    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2503    CXTok.int_data[2] = Tok.getLength();
2504    CXTok.int_data[3] = 0;
2505
2506    //   - Kind-specific fields
2507    if (Tok.isLiteral()) {
2508      CXTok.int_data[0] = CXToken_Literal;
2509      CXTok.ptr_data = (void *)Tok.getLiteralData();
2510    } else if (Tok.is(tok::identifier)) {
2511      // Lookup the identifier to determine whether we have a keyword.
2512      std::pair<FileID, unsigned> LocInfo
2513        = SourceMgr.getDecomposedLoc(Tok.getLocation());
2514      bool Invalid = false;
2515      llvm::StringRef Buf
2516        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2517      if (Invalid)
2518        return;
2519
2520      const char *StartPos = Buf.data() + LocInfo.second;
2521      IdentifierInfo *II
2522        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2523
2524      if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2525        CXTok.int_data[0] = CXToken_Keyword;
2526      }
2527      else {
2528        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2529                                CXToken_Identifier
2530                              : CXToken_Keyword;
2531      }
2532      CXTok.ptr_data = II;
2533    } else if (Tok.is(tok::comment)) {
2534      CXTok.int_data[0] = CXToken_Comment;
2535      CXTok.ptr_data = 0;
2536    } else {
2537      CXTok.int_data[0] = CXToken_Punctuation;
2538      CXTok.ptr_data = 0;
2539    }
2540    CXTokens.push_back(CXTok);
2541  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2542
2543  if (CXTokens.empty())
2544    return;
2545
2546  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2547  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2548  *NumTokens = CXTokens.size();
2549}
2550
2551void clang_disposeTokens(CXTranslationUnit TU,
2552                         CXToken *Tokens, unsigned NumTokens) {
2553  free(Tokens);
2554}
2555
2556} // end: extern "C"
2557
2558//===----------------------------------------------------------------------===//
2559// Token annotation APIs.
2560//===----------------------------------------------------------------------===//
2561
2562typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2563static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2564                                                     CXCursor parent,
2565                                                     CXClientData client_data);
2566namespace {
2567class AnnotateTokensWorker {
2568  AnnotateTokensData &Annotated;
2569  CXToken *Tokens;
2570  CXCursor *Cursors;
2571  unsigned NumTokens;
2572  unsigned TokIdx;
2573  CursorVisitor AnnotateVis;
2574  SourceManager &SrcMgr;
2575
2576  bool MoreTokens() const { return TokIdx < NumTokens; }
2577  unsigned NextToken() const { return TokIdx; }
2578  void AdvanceToken() { ++TokIdx; }
2579  SourceLocation GetTokenLoc(unsigned tokI) {
2580    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2581  }
2582
2583public:
2584  AnnotateTokensWorker(AnnotateTokensData &annotated,
2585                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2586                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
2587    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
2588      NumTokens(numTokens), TokIdx(0),
2589      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2590                  Decl::MaxPCHLevel, RegionOfInterest),
2591      SrcMgr(CXXUnit->getSourceManager()) {}
2592
2593  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
2594  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
2595  void AnnotateTokens(CXCursor parent);
2596};
2597}
2598
2599void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2600  // Walk the AST within the region of interest, annotating tokens
2601  // along the way.
2602  VisitChildren(parent);
2603
2604  for (unsigned I = 0 ; I < TokIdx ; ++I) {
2605    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2606    if (Pos != Annotated.end())
2607      Cursors[I] = Pos->second;
2608  }
2609
2610  // Finish up annotating any tokens left.
2611  if (!MoreTokens())
2612    return;
2613
2614  const CXCursor &C = clang_getNullCursor();
2615  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2616    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2617    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
2618  }
2619}
2620
2621enum CXChildVisitResult
2622AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
2623  CXSourceLocation Loc = clang_getCursorLocation(cursor);
2624  // We can always annotate a preprocessing directive/macro instantiation.
2625  if (clang_isPreprocessing(cursor.kind)) {
2626    Annotated[Loc.int_data] = cursor;
2627    return CXChildVisit_Recurse;
2628  }
2629
2630  SourceRange cursorRange = getRawCursorExtent(cursor);
2631
2632  if (cursorRange.isInvalid())
2633    return CXChildVisit_Continue;
2634
2635  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2636
2637  // Adjust the annotated range based specific declarations.
2638  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2639  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2640    Decl *D = cxcursor::getCursorDecl(cursor);
2641    // Don't visit synthesized ObjC methods, since they have no syntatic
2642    // representation in the source.
2643    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2644      if (MD->isSynthesized())
2645        return CXChildVisit_Continue;
2646    }
2647    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
2648      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2649        TypeLoc TL = TI->getTypeLoc();
2650        SourceLocation TLoc = TL.getSourceRange().getBegin();
2651        if (TLoc.isValid() &&
2652            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
2653          cursorRange.setBegin(TLoc);
2654      }
2655    }
2656  }
2657
2658  // If the location of the cursor occurs within a macro instantiation, record
2659  // the spelling location of the cursor in our annotation map.  We can then
2660  // paper over the token labelings during a post-processing step to try and
2661  // get cursor mappings for tokens that are the *arguments* of a macro
2662  // instantiation.
2663  if (L.isMacroID()) {
2664    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2665    // Only invalidate the old annotation if it isn't part of a preprocessing
2666    // directive.  Here we assume that the default construction of CXCursor
2667    // results in CXCursor.kind being an initialized value (i.e., 0).  If
2668    // this isn't the case, we can fix by doing lookup + insertion.
2669
2670    CXCursor &oldC = Annotated[rawEncoding];
2671    if (!clang_isPreprocessing(oldC.kind))
2672      oldC = cursor;
2673  }
2674
2675  const enum CXCursorKind K = clang_getCursorKind(parent);
2676  const CXCursor updateC =
2677    (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2678     L.isMacroID())
2679    ? clang_getNullCursor() : parent;
2680
2681  while (MoreTokens()) {
2682    const unsigned I = NextToken();
2683    SourceLocation TokLoc = GetTokenLoc(I);
2684    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2685      case RangeBefore:
2686        Cursors[I] = updateC;
2687        AdvanceToken();
2688        continue;
2689      case RangeAfter:
2690      case RangeOverlap:
2691        break;
2692    }
2693    break;
2694  }
2695
2696  // Visit children to get their cursor information.
2697  const unsigned BeforeChildren = NextToken();
2698  VisitChildren(cursor);
2699  const unsigned AfterChildren = NextToken();
2700
2701  // Adjust 'Last' to the last token within the extent of the cursor.
2702  while (MoreTokens()) {
2703    const unsigned I = NextToken();
2704    SourceLocation TokLoc = GetTokenLoc(I);
2705    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2706      case RangeBefore:
2707        assert(0 && "Infeasible");
2708      case RangeAfter:
2709        break;
2710      case RangeOverlap:
2711        Cursors[I] = updateC;
2712        AdvanceToken();
2713        continue;
2714    }
2715    break;
2716  }
2717  const unsigned Last = NextToken();
2718
2719  // Scan the tokens that are at the beginning of the cursor, but are not
2720  // capture by the child cursors.
2721
2722  // For AST elements within macros, rely on a post-annotate pass to
2723  // to correctly annotate the tokens with cursors.  Otherwise we can
2724  // get confusing results of having tokens that map to cursors that really
2725  // are expanded by an instantiation.
2726  if (L.isMacroID())
2727    cursor = clang_getNullCursor();
2728
2729  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2730    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2731      break;
2732    Cursors[I] = cursor;
2733  }
2734  // Scan the tokens that are at the end of the cursor, but are not captured
2735  // but the child cursors.
2736  for (unsigned I = AfterChildren; I != Last; ++I)
2737    Cursors[I] = cursor;
2738
2739  TokIdx = Last;
2740  return CXChildVisit_Continue;
2741}
2742
2743static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2744                                                     CXCursor parent,
2745                                                     CXClientData client_data) {
2746  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2747}
2748
2749extern "C" {
2750
2751void clang_annotateTokens(CXTranslationUnit TU,
2752                          CXToken *Tokens, unsigned NumTokens,
2753                          CXCursor *Cursors) {
2754
2755  if (NumTokens == 0 || !Tokens || !Cursors)
2756    return;
2757
2758  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2759  if (!CXXUnit) {
2760    // Any token we don't specifically annotate will have a NULL cursor.
2761    const CXCursor &C = clang_getNullCursor();
2762    for (unsigned I = 0; I != NumTokens; ++I)
2763      Cursors[I] = C;
2764    return;
2765  }
2766
2767  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2768
2769  // Determine the region of interest, which contains all of the tokens.
2770  SourceRange RegionOfInterest;
2771  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2772                                        clang_getTokenLocation(TU, Tokens[0])));
2773  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2774                                clang_getTokenLocation(TU,
2775                                                       Tokens[NumTokens - 1])));
2776
2777  // A mapping from the source locations found when re-lexing or traversing the
2778  // region of interest to the corresponding cursors.
2779  AnnotateTokensData Annotated;
2780
2781  // Relex the tokens within the source range to look for preprocessing
2782  // directives.
2783  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2784  std::pair<FileID, unsigned> BeginLocInfo
2785    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2786  std::pair<FileID, unsigned> EndLocInfo
2787    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2788
2789  llvm::StringRef Buffer;
2790  bool Invalid = false;
2791  if (BeginLocInfo.first == EndLocInfo.first &&
2792      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2793      !Invalid) {
2794    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2795              CXXUnit->getASTContext().getLangOptions(),
2796              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2797              Buffer.end());
2798    Lex.SetCommentRetentionState(true);
2799
2800    // Lex tokens in raw mode until we hit the end of the range, to avoid
2801    // entering #includes or expanding macros.
2802    while (true) {
2803      Token Tok;
2804      Lex.LexFromRawLexer(Tok);
2805
2806    reprocess:
2807      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2808        // We have found a preprocessing directive. Gobble it up so that we
2809        // don't see it while preprocessing these tokens later, but keep track of
2810        // all of the token locations inside this preprocessing directive so that
2811        // we can annotate them appropriately.
2812        //
2813        // FIXME: Some simple tests here could identify macro definitions and
2814        // #undefs, to provide specific cursor kinds for those.
2815        std::vector<SourceLocation> Locations;
2816        do {
2817          Locations.push_back(Tok.getLocation());
2818          Lex.LexFromRawLexer(Tok);
2819        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2820
2821        using namespace cxcursor;
2822        CXCursor Cursor
2823          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2824                                                         Locations.back()),
2825                                           CXXUnit);
2826        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2827          Annotated[Locations[I].getRawEncoding()] = Cursor;
2828        }
2829
2830        if (Tok.isAtStartOfLine())
2831          goto reprocess;
2832
2833        continue;
2834      }
2835
2836      if (Tok.is(tok::eof))
2837        break;
2838    }
2839  }
2840
2841  // Annotate all of the source locations in the region of interest that map to
2842  // a specific cursor.
2843  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2844                         CXXUnit, RegionOfInterest);
2845  W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
2846}
2847} // end: extern "C"
2848
2849//===----------------------------------------------------------------------===//
2850// Operations for querying linkage of a cursor.
2851//===----------------------------------------------------------------------===//
2852
2853extern "C" {
2854CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
2855  if (!clang_isDeclaration(cursor.kind))
2856    return CXLinkage_Invalid;
2857
2858  Decl *D = cxcursor::getCursorDecl(cursor);
2859  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2860    switch (ND->getLinkage()) {
2861      case NoLinkage: return CXLinkage_NoLinkage;
2862      case InternalLinkage: return CXLinkage_Internal;
2863      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2864      case ExternalLinkage: return CXLinkage_External;
2865    };
2866
2867  return CXLinkage_Invalid;
2868}
2869} // end: extern "C"
2870
2871//===----------------------------------------------------------------------===//
2872// Operations for querying language of a cursor.
2873//===----------------------------------------------------------------------===//
2874
2875static CXLanguageKind getDeclLanguage(const Decl *D) {
2876  switch (D->getKind()) {
2877    default:
2878      break;
2879    case Decl::ImplicitParam:
2880    case Decl::ObjCAtDefsField:
2881    case Decl::ObjCCategory:
2882    case Decl::ObjCCategoryImpl:
2883    case Decl::ObjCClass:
2884    case Decl::ObjCCompatibleAlias:
2885    case Decl::ObjCForwardProtocol:
2886    case Decl::ObjCImplementation:
2887    case Decl::ObjCInterface:
2888    case Decl::ObjCIvar:
2889    case Decl::ObjCMethod:
2890    case Decl::ObjCProperty:
2891    case Decl::ObjCPropertyImpl:
2892    case Decl::ObjCProtocol:
2893      return CXLanguage_ObjC;
2894    case Decl::CXXConstructor:
2895    case Decl::CXXConversion:
2896    case Decl::CXXDestructor:
2897    case Decl::CXXMethod:
2898    case Decl::CXXRecord:
2899    case Decl::ClassTemplate:
2900    case Decl::ClassTemplatePartialSpecialization:
2901    case Decl::ClassTemplateSpecialization:
2902    case Decl::Friend:
2903    case Decl::FriendTemplate:
2904    case Decl::FunctionTemplate:
2905    case Decl::LinkageSpec:
2906    case Decl::Namespace:
2907    case Decl::NamespaceAlias:
2908    case Decl::NonTypeTemplateParm:
2909    case Decl::StaticAssert:
2910    case Decl::TemplateTemplateParm:
2911    case Decl::TemplateTypeParm:
2912    case Decl::UnresolvedUsingTypename:
2913    case Decl::UnresolvedUsingValue:
2914    case Decl::Using:
2915    case Decl::UsingDirective:
2916    case Decl::UsingShadow:
2917      return CXLanguage_CPlusPlus;
2918  }
2919
2920  return CXLanguage_C;
2921}
2922
2923extern "C" {
2924CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2925  if (clang_isDeclaration(cursor.kind))
2926    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2927
2928  return CXLanguage_Invalid;
2929}
2930} // end: extern "C"
2931
2932
2933//===----------------------------------------------------------------------===//
2934// C++ AST instrospection.
2935//===----------------------------------------------------------------------===//
2936
2937extern "C" {
2938unsigned clang_CXXMethod_isStatic(CXCursor C) {
2939  if (!clang_isDeclaration(C.kind))
2940    return 0;
2941  CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2942  return (D && D->isStatic()) ? 1 : 0;
2943}
2944
2945} // end: extern "C"
2946
2947//===----------------------------------------------------------------------===//
2948// CXString Operations.
2949//===----------------------------------------------------------------------===//
2950
2951extern "C" {
2952const char *clang_getCString(CXString string) {
2953  return string.Spelling;
2954}
2955
2956void clang_disposeString(CXString string) {
2957  if (string.MustFreeString && string.Spelling)
2958    free((void*)string.Spelling);
2959}
2960
2961} // end: extern "C"
2962
2963namespace clang { namespace cxstring {
2964CXString createCXString(const char *String, bool DupString){
2965  CXString Str;
2966  if (DupString) {
2967    Str.Spelling = strdup(String);
2968    Str.MustFreeString = 1;
2969  } else {
2970    Str.Spelling = String;
2971    Str.MustFreeString = 0;
2972  }
2973  return Str;
2974}
2975
2976CXString createCXString(llvm::StringRef String, bool DupString) {
2977  CXString Result;
2978  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2979    char *Spelling = (char *)malloc(String.size() + 1);
2980    memmove(Spelling, String.data(), String.size());
2981    Spelling[String.size()] = 0;
2982    Result.Spelling = Spelling;
2983    Result.MustFreeString = 1;
2984  } else {
2985    Result.Spelling = String.data();
2986    Result.MustFreeString = 0;
2987  }
2988  return Result;
2989}
2990}}
2991
2992//===----------------------------------------------------------------------===//
2993// Misc. utility functions.
2994//===----------------------------------------------------------------------===//
2995
2996extern "C" {
2997
2998CXString clang_getClangVersion() {
2999  return createCXString(getClangFullVersion());
3000}
3001
3002} // end: extern "C"
3003