CIndex.cpp revision db84e7a44dce24c3a8e4e0fc84434c00fc2da168
116c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
216c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//
316c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//                     The LLVM Compiler Infrastructure
416c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//
516c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek// This file is distributed under the University of Illinois Open Source
616c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek// License. See LICENSE.TXT for details.
716c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//
816c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//===----------------------------------------------------------------------===//
916c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//
102e331b938b38057e333fab0ba841130ea8467794Douglas Gregor// This file implements the main API hooks in the Clang-C Source Indexing
112e331b938b38057e333fab0ba841130ea8467794Douglas Gregor// library.
122e331b938b38057e333fab0ba841130ea8467794Douglas Gregor//
1316c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek//===----------------------------------------------------------------------===//
1416c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek
1516c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "CIndexer.h"
160a90d32523bfe5fa63e11b648686c9699f786d15Ted Kremenek#include "CIndexDiagnostic.h"
1716c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "CLog.h"
18ed122735639d83c10f18c28c7fd117bfcd0f62cbTed Kremenek#include "CXComment.h"
197eaa8ae8692c5cd3eed8cb334fe5346470522091Douglas Gregor#include "CXCursor.h"
2016c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "CXSourceLocation.h"
216931900f43cea558c6974075256c07728dbfecc6Douglas Gregor#include "CXString.h"
22283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor#include "CXTranslationUnit.h"
23aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis#include "CXType.h"
24283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor#include "CursorVisitor.h"
251f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor#include "SimpleFormatContext.h"
26aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis#include "clang/AST/StmtVisitor.h"
27007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek#include "clang/Basic/Diagnostic.h"
28edc8aa68ef91aeea686c5aadf64ef902c38318ddTed Kremenek#include "clang/Basic/Version.h"
2916c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "clang/Frontend/ASTUnit.h"
3016c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "clang/Frontend/CompilerInstance.h"
311f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor#include "clang/Frontend/FrontendDiagnostic.h"
3216c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "clang/Lex/HeaderSearch.h"
335bfb8c128c2ac8eb4032afc180cdc400a0f953caDouglas Gregor#include "clang/Lex/Lexer.h"
345bfb8c128c2ac8eb4032afc180cdc400a0f953caDouglas Gregor#include "clang/Lex/PreprocessingRecord.h"
35aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis#include "clang/Lex/Preprocessor.h"
365bfb8c128c2ac8eb4032afc180cdc400a0f953caDouglas Gregor#include "llvm/ADT/Optional.h"
3716c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "llvm/ADT/STLExtras.h"
3816c440a377b7ec8b722a2e2c7c864f75c95bd305Ted Kremenek#include "llvm/ADT/StringSwitch.h"
39e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Config/config.h"
40e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/Compiler.h"
41e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/CrashRecoveryContext.h"
42e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/Format.h"
43387475d0c18aaeb022108de9d33b6c9fb7998843Sean Hunt#include "llvm/Support/MemoryBuffer.h"
44387475d0c18aaeb022108de9d33b6c9fb7998843Sean Hunt#include "llvm/Support/Mutex.h"
45387475d0c18aaeb022108de9d33b6c9fb7998843Sean Hunt#include "llvm/Support/PrettyStackTrace.h"
466639e9255489ad8e10278d5658fdd4b3c0e1e4cdArgyrios Kyrtzidis#include "llvm/Support/Program.h"
476639e9255489ad8e10278d5658fdd4b3c0e1e4cdArgyrios Kyrtzidis#include "llvm/Support/SaveAndRestore.h"
48e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/Signals.h"
49e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/Threading.h"
50e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/Timer.h"
51e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#include "llvm/Support/raw_ostream.h"
52e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek
53a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek#if HAVE_PTHREAD_H
54a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek#include <pthread.h>
55e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenek#endif
56aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
57e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenekusing namespace clang;
58e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenekusing namespace clang::cxcursor;
59e77f443dbca8cdc23e5aa94a2653367e4a7cbe47Ted Kremenekusing namespace clang::cxstring;
60a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenekusing namespace clang::cxtu;
61aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisusing namespace clang::cxindex;
62007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek
6354d67caeee4fdce81f07163832f1163d5f2af5d2Daniel DunbarCXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
64aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (!TU)
65aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return 0;
66aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  CXTranslationUnit D = new CXTranslationUnitImpl();
67aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->CIdx = CIdx;
68aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->TUData = TU;
69aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->StringPool = createCXStringPool();
70aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->Diagnostics = 0;
71aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->OverridenCursorsPool = createOverridenCXCursorsPool();
72aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->FormatContext = 0;
73aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  D->FormatInMemoryUniqueId = 0;
74aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return D;
75aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
76aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
77aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidiscxtu::CXTUOwner::~CXTUOwner() {
78aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (TU)
79aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    clang_disposeTranslationUnit(TU);
80aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
81aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
82aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis/// \brief Compare two source ranges to determine their relative position in
83aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis/// the translation unit.
84aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisstatic RangeComparisonResult RangeCompare(SourceManager &SM,
85aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis                                          SourceRange R1,
865bfb8c128c2ac8eb4032afc180cdc400a0f953caDouglas Gregor                                          SourceRange R2) {
87edc8aa68ef91aeea686c5aadf64ef902c38318ddTed Kremenek  assert(R1.isValid() && "First range is invalid?");
88edc8aa68ef91aeea686c5aadf64ef902c38318ddTed Kremenek  assert(R2.isValid() && "Second range is invalid?");
89aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (R1.getEnd() != R2.getBegin() &&
90aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
9154d67caeee4fdce81f07163832f1163d5f2af5d2Daniel Dunbar    return RangeBefore;
9297b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  if (R2.getEnd() != R1.getBegin() &&
9397b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
9497b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    return RangeAfter;
9597b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  return RangeOverlap;
9697b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor}
9742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
9897b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor/// \brief Determine if a source location falls within, before, or after a
9942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor///   a given source range.
10042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorstatic RangeComparisonResult LocationCompare(SourceManager &SM,
10142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                             SourceLocation L, SourceRange R) {
10297b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  assert(R.isValid() && "First range is invalid?");
10342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  assert(L.isValid() && "Second range is invalid?");
10442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (L == R.getBegin() || L == R.getEnd())
10542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return RangeOverlap;
10642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
10742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return RangeBefore;
10842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
10942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return RangeAfter;
11042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return RangeOverlap;
11142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
11242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
11342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// \brief Translate a Clang source range into a CIndex source range.
11442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor///
11542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// Clang internally represents ranges where the end location points to the
11642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// start of the token at the end. However, for external clients it is more
11742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// useful to have a CXSourceRange be a proper half-open interval. This routine
11842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// does the appropriate translation.
11942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas GregorCXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
12042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                          const LangOptions &LangOpts,
12142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                          const CharSourceRange &R) {
12242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // We want the last character in this location, so we will adjust the
12342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // location accordingly.
12442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceLocation EndLoc = R.getEnd();
12542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
12642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    EndLoc = SM.getExpansionRange(EndLoc).second;
12742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (R.isTokenRange() && !EndLoc.isInvalid()) {
12842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
12942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                                SM, LangOpts);
13097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    EndLoc = EndLoc.getLocWithOffset(Length);
13142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
13242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
13342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  CXSourceRange Result = {
13442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    { &SM, &LangOpts },
13542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    R.getBegin().getRawEncoding(),
13642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    EndLoc.getRawEncoding()
13742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  };
13842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return Result;
13942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
14042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
14142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor//===----------------------------------------------------------------------===//
14242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor// Cursor visitor.
14342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor//===----------------------------------------------------------------------===//
14442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
14542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorstatic SourceRange getRawCursorExtent(CXCursor C);
14642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorstatic SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
14742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
14842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
14942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas GregorRangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
15042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
15142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
15242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
15342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// \brief Visit the given cursor and, if requested by the visitor,
15442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// its children.
15542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor///
15642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// \param Cursor the cursor to visit.
15742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor///
15842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// \param CheckedRegionOfInterest if true, then the caller already checked
15942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// that this cursor is within the region of interest.
16042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor///
16142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// \returns true if the visitation should be aborted, false if it
16242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor/// should continue.
16342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorbool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
16442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (clang_isInvalid(Cursor.kind))
16542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return false;
16642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
16742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (clang_isDeclaration(Cursor.kind)) {
16842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    const Decl *D = getCursorDecl(Cursor);
16942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (!D) {
17042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      assert(0 && "Invalid declaration cursor");
17142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return true; // abort.
17242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    }
17342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
17497b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    // Ignore implicit declarations, unless it's an objc method because
17542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    // currently we should report implicit methods for properties when indexing.
17642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
17742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return false;
17897b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  }
17942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
18042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // If we have a range of interest, and this cursor doesn't intersect with it,
18142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // we're done.
18242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
18342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceRange Range = getRawCursorExtent(Cursor);
18442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (Range.isInvalid() || CompareRegionOfInterest(Range))
18542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return false;
18642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
18742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
18842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  switch (Visitor(Cursor, Parent, ClientData)) {
18942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  case CXChildVisit_Break:
19028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley    return true;
19142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
19242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  case CXChildVisit_Continue:
19342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return false;
19428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
19542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  case CXChildVisit_Recurse: {
19642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    bool ret = VisitChildren(Cursor);
19742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (PostChildrenVisitor)
19828bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley      if (PostChildrenVisitor(Cursor, ClientData))
19942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor        return true;
20042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return ret;
20142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
20242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
20342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
204276b061970939293f1abaf694bd3ef05b2cbda79Eli Friedman  llvm_unreachable("Invalid CXChildVisitResult!");
20542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
20642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
20742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorstatic bool visitPreprocessedEntitiesInRange(SourceRange R,
20842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                             PreprocessingRecord &PPRec,
20942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                             CursorVisitor &Visitor) {
21042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
21142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  FileID FID;
21242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
21342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (!Visitor.shouldVisitIncludedEntities()) {
21442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    // If the begin/end of the range lie in the same FileID, do the optimization
21542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    // where we skip preprocessed entities that do not come from the same FileID.
21642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
21742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
21803e80030515c800d1ab44125b9052dfffd1bd04cDouglas Gregor      FID = FileID();
21942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
22042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
22142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
22242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Entities = PPRec.getPreprocessedEntitiesInRange(R);
22342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
22442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                           PPRec, FID);
22542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
22642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
22742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorvoid CursorVisitor::visitFileRegion() {
22842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (RegionOfInterest.isInvalid())
22942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return;
23042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
23142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
23242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceManager &SM = Unit->getSourceManager();
23397b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
23497b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  std::pair<FileID, unsigned>
23542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
23642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
23736897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
23836897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor  if (End.first != Begin.first) {
23942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    // If the end does not reside in the same file, try to recover by
24042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    // picking the end of the file of begin location.
24142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    End.first = Begin.first;
24242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    End.second = SM.getFileIDSize(Begin.first);
24342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
24442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
24542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  assert(Begin.first == End.first);
24642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (Begin.second > End.second)
24742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return;
24842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
24942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  FileID File = Begin.first;
25042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  unsigned Offset = Begin.second;
25142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  unsigned Length = End.second - Begin.second;
25242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
25342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (!VisitDeclsOnly && !VisitPreprocessorLast)
25442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (visitPreprocessedEntitiesInRegion())
25542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return; // visitation break.
25642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
25742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  visitDeclsFromFileRegion(File, Offset, Length);
25842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
25942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (!VisitDeclsOnly && VisitPreprocessorLast)
26042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    visitPreprocessedEntitiesInRegion();
26142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
26242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
26342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorstatic bool isInLexicalContext(Decl *D, DeclContext *DC) {
26442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (!DC)
26542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return false;
26642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
26742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  for (DeclContext *DeclDC = D->getLexicalDeclContext();
26842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor         DeclDC; DeclDC = DeclDC->getLexicalParent()) {
26942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (DeclDC == DC)
27042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return true;
2718ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor  }
27242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return false;
27342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
27442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
27542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorvoid CursorVisitor::visitDeclsFromFileRegion(FileID File,
27642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                             unsigned Offset, unsigned Length) {
27742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
27842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceManager &SM = Unit->getSourceManager();
27942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceRange Range = RegionOfInterest;
28042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
28142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SmallVector<Decl *, 16> Decls;
28242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  Unit->findFileRegionDecls(File, Offset, Length, Decls);
28342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
28442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // If we didn't find any file level decls for the file, try looking at the
28542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // file that it was included from.
28642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
28797b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    bool Invalid = false;
28842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
28942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (Invalid)
29042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return;
29142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
29242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceLocation Outer;
29342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (SLEntry.isFile())
29442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      Outer = SLEntry.getFile().getIncludeLoc();
29597b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    else
29642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      Outer = SLEntry.getExpansion().getExpansionLocStart();
29742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (Outer.isInvalid())
29842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return;
29942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
30042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
30142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Length = 0;
30242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Unit->findFileRegionDecls(File, Offset, Length, Decls);
30342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
30442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
30542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  assert(!Decls.empty());
30642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
30742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  bool VisitedAtLeastOnce = false;
30842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  DeclContext *CurDC = 0;
30942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
31042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
31142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Decl *D = *DIt;
31242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (D->getSourceRange().isInvalid())
31342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      continue;
31442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
315f111d935722ed488144600cea5ed03a6b5069e8fPeter Collingbourne    if (isInLexicalContext(D, CurDC))
31642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      continue;
31742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
31842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    CurDC = dyn_cast<DeclContext>(D);
31942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
32042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (TagDecl *TD = dyn_cast<TagDecl>(D))
32142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      if (!TD->isFreeStanding())
32242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor        continue;
32342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
32442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
32542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (CompRes == RangeBefore)
32642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      continue;
32742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (CompRes == RangeAfter)
32842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      break;
32942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
33042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    assert(CompRes == RangeOverlap);
33142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    VisitedAtLeastOnce = true;
33242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
33342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (isa<ObjCContainerDecl>(D)) {
33442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      FileDI_current = &DIt;
33542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      FileDE_current = DE;
33642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    } else {
33742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      FileDI_current = 0;
33842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    }
33997b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
34042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
34142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      break;
34242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
34342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
34442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (VisitedAtLeastOnce)
34542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return;
34642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
34742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // No Decls overlapped with the range. Move up the lexical context until there
34842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // is a context that contains the range or we reach the translation unit
34942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  // level.
35042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
35142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                         : (*(DIt-1))->getLexicalDeclContext();
35242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
35342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  while (DC && !DC->isTranslationUnit()) {
35442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    Decl *D = cast<Decl>(DC);
35542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceRange CurDeclRange = D->getSourceRange();
35642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (CurDeclRange.isInvalid())
35742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      break;
35842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
35942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
36042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
36142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      break;
36242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    }
36342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
36442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    DC = D->getLexicalDeclContext();
36542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  }
36642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
36742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
36842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregorbool CursorVisitor::visitPreprocessedEntitiesInRegion() {
36942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (!AU->getPreprocessor().getPreprocessingRecord())
37042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return false;
37142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
37242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  PreprocessingRecord &PPRec
37342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    = *AU->getPreprocessor().getPreprocessingRecord();
37442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  SourceManager &SM = AU->getSourceManager();
37542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
37642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (RegionOfInterest.isValid()) {
37742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
37842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceLocation B = MappedRange.getBegin();
37942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    SourceLocation E = MappedRange.getEnd();
38042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
38142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    if (AU->isInPreambleFileID(B)) {
38242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      if (SM.isLoadedSourceLocation(E))
38342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
38442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                                 PPRec, *this);
38542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
38642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      // Beginning of range lies in the preamble but it also extends beyond
387f85e193739c953358c865005855253af4f68a497John McCall      // it into the main file. Split the range into 2 parts, one covering
38842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      // the preamble and another covering the main file. This allows subsequent
38942b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      // calls to visitPreprocessedEntitiesInRange to accept a source range that
39042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      // lies in the same FileID, allowing it to skip preprocessed entities that
39142b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      // do not come from the same FileID.
39242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      bool breaked =
39342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor        visitPreprocessedEntitiesInRange(
39442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                   SourceRange(B, AU->getEndOfPreambleFileID()),
395be230c36e32142cbdcdbe9c97511d097beeecbabDouglas Gregor                                          PPRec, *this);
39642b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      if (breaked) return true;
39742b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor      return visitPreprocessedEntitiesInRange(
39842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                    SourceRange(AU->getStartOfMainFileID(), E),
399ee8aff06f6a96214731de17b2cb6df407c6c1820Douglas Gregor                                        PPRec, *this);
40042b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    }
40197b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
40242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
40397b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  }
40442b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
40542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  bool OnlyLocalDecls
40691a5755ad73c5dc1dfb167e448fdd74e75a6df56John McCall    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
407c7793c73ba8a343de3f2552d984851985a46f159Douglas Gregor
40842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  if (OnlyLocalDecls)
40997b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
41097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor                                     PPRec);
41197b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
41242b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
41342b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor}
41497b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
41542b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregortemplate<typename InputIterator>
41697b9872d5775446cb8aca1380e437649fe848d91Douglas Gregorbool CursorVisitor::visitPreprocessedEntities(InputIterator First,
41797b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor                                              InputIterator Last,
41842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor                                              PreprocessingRecord &PPRec,
41997b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor                                              FileID FID) {
42097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  for (; First != Last; ++First) {
42197b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
42297b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor      continue;
42397b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
42497b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    PreprocessedEntity *PPE = *First;
425e08ce650a2b02410eddd1f60a4aa6b3d4be71e73Peter Collingbourne    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
42697b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor      if (Visit(MakeMacroExpansionCursor(ME, TU)))
42797b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor        return true;
42842b2984771a7fd1b17c78bbb2c59fed3db2f1960Douglas Gregor
42997b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor      continue;
43097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    }
43197b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
43297b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
43397b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
434aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis        return true;
435aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
436aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      continue;
437aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    }
438aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
439aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
440aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
441aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis        return true;
442aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
443aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      continue;
444aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    }
445aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  }
446aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
44797b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor  return false;
44897b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor}
449aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
45097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor/// \brief Visit the children of the given cursor.
45197b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor///
45297b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor/// \returns true if the visitation should be aborted, false if it
4532e331b938b38057e333fab0ba841130ea8467794Douglas Gregor/// should continue.
454b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregorbool CursorVisitor::VisitChildren(CXCursor Cursor) {
455a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  if (clang_isReference(Cursor.kind) &&
45654d67caeee4fdce81f07163832f1163d5f2af5d2Daniel Dunbar      Cursor.kind != CXCursor_CXXBaseSpecifier) {
4572e331b938b38057e333fab0ba841130ea8467794Douglas Gregor    // By definition, references have no children.
458aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return false;
4592e331b938b38057e333fab0ba841130ea8467794Douglas Gregor  }
4602e331b938b38057e333fab0ba841130ea8467794Douglas Gregor
4612e331b938b38057e333fab0ba841130ea8467794Douglas Gregor  // Set the Parent field to Cursor, then back to its old value once we're
4622e331b938b38057e333fab0ba841130ea8467794Douglas Gregor  // done.
4632e331b938b38057e333fab0ba841130ea8467794Douglas Gregor  SetParentRAII SetParent(Parent, StmtParent, Cursor);
4642e331b938b38057e333fab0ba841130ea8467794Douglas Gregor
4652e331b938b38057e333fab0ba841130ea8467794Douglas Gregor  if (clang_isDeclaration(Cursor.kind)) {
4662e331b938b38057e333fab0ba841130ea8467794Douglas Gregor    Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
4672e331b938b38057e333fab0ba841130ea8467794Douglas Gregor    if (!D)
4682e331b938b38057e333fab0ba841130ea8467794Douglas Gregor      return false;
4692e331b938b38057e333fab0ba841130ea8467794Douglas Gregor
47078db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor    return VisitAttributes(D) || Visit(D);
471b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregor  }
472a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek
47354d67caeee4fdce81f07163832f1163d5f2af5d2Daniel Dunbar  if (clang_isStatement(Cursor.kind)) {
47478db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor    if (Stmt *S = getCursorStmt(Cursor))
475aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      return Visit(S);
47678db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor
47778db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor    return false;
47878db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor  }
47978db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor
48078db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor  if (clang_isExpression(Cursor.kind)) {
48178db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor    if (Expr *E = getCursorExpr(Cursor))
48278db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor      return Visit(E);
48378db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor
48478db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor    return false;
48578db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor  }
48678db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor
4871adb082a709f7b588f03672999294e061234b2cfDouglas Gregor  if (clang_isTranslationUnit(Cursor.kind)) {
488b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregor    CXTranslationUnit tu = getCursorTU(Cursor);
489a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
490ebfa339321f8a4df9d5011e591a615d5765107d5Ted Kremenek
491ebfa339321f8a4df9d5011e591a615d5765107d5Ted Kremenek    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
492ebfa339321f8a4df9d5011e591a615d5765107d5Ted Kremenek    for (unsigned I = 0; I != 2; ++I) {
493ebfa339321f8a4df9d5011e591a615d5765107d5Ted Kremenek      if (VisitOrder[I]) {
4941adb082a709f7b588f03672999294e061234b2cfDouglas Gregor        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
495aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis            RegionOfInterest.isInvalid()) {
4961adb082a709f7b588f03672999294e061234b2cfDouglas Gregor          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
4971adb082a709f7b588f03672999294e061234b2cfDouglas Gregor                                        TLEnd = CXXUnit->top_level_end();
4981adb082a709f7b588f03672999294e061234b2cfDouglas Gregor               TL != TLEnd; ++TL) {
4991adb082a709f7b588f03672999294e061234b2cfDouglas Gregor            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
5001adb082a709f7b588f03672999294e061234b2cfDouglas Gregor              return true;
5011adb082a709f7b588f03672999294e061234b2cfDouglas Gregor          }
5021adb082a709f7b588f03672999294e061234b2cfDouglas Gregor        } else if (VisitDeclContext(
5031adb082a709f7b588f03672999294e061234b2cfDouglas Gregor                                CXXUnit->getASTContext().getTranslationUnitDecl()))
5041adb082a709f7b588f03672999294e061234b2cfDouglas Gregor          return true;
5051adb082a709f7b588f03672999294e061234b2cfDouglas Gregor        continue;
5061adb082a709f7b588f03672999294e061234b2cfDouglas Gregor      }
5077d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor
508a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek      // Walk the preprocessing record.
50954d67caeee4fdce81f07163832f1163d5f2af5d2Daniel Dunbar      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
5107d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor        visitPreprocessedEntitiesInRegion();
511aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    }
5127d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor
5137d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor    return false;
5147d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor  }
5157d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor
5167d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
5177d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor    if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
5187d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
5197d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor        return Visit(BaseTSInfo->getTypeLoc());
5207d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor      }
5217d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor    }
5227d0d40e58807f73e06ff5eb637a48e9f978b0e2aDouglas Gregor  }
5230b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor
524a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
525a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    IBOutletCollectionAttr *A =
5260b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
5270b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
528aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
5290b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor                                                    A->getInterfaceLoc(), TU));
5300b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  }
5310b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor
5320b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  // If pointing inside a macro definition, check if the token is an identifier
5330b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  // that was ever defined as a macro. In such a case, create a "pseudo" macro
5340b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  // expansion cursor for that token.
5350b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  SourceLocation BeginLoc = RegionOfInterest.getBegin();
5360b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor  if (Cursor.kind == CXCursor_MacroDefinition &&
5370b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor      BeginLoc == RegionOfInterest.getEnd()) {
5380b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor    SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
5390b36e614aa19df72885d5e0de996f7fbb9874ec3Douglas Gregor    const MacroInfo *MI =
5406931900f43cea558c6974075256c07728dbfecc6Douglas Gregor        getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
541a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    if (MacroDefinition *MacroDef =
5426931900f43cea558c6974075256c07728dbfecc6Douglas Gregor          checkForMacroInMacroDefinition(MI, Loc, TU))
5436931900f43cea558c6974075256c07728dbfecc6Douglas Gregor      return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
5446931900f43cea558c6974075256c07728dbfecc6Douglas Gregor  }
5456931900f43cea558c6974075256c07728dbfecc6Douglas Gregor
546aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // Nothing to visit at the moment.
5476931900f43cea558c6974075256c07728dbfecc6Douglas Gregor  return false;
5486931900f43cea558c6974075256c07728dbfecc6Douglas Gregor}
5496931900f43cea558c6974075256c07728dbfecc6Douglas Gregor
5506931900f43cea558c6974075256c07728dbfecc6Douglas Gregorbool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
5516931900f43cea558c6974075256c07728dbfecc6Douglas Gregor  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
5526931900f43cea558c6974075256c07728dbfecc6Douglas Gregor    if (Visit(TSInfo->getTypeLoc()))
5536931900f43cea558c6974075256c07728dbfecc6Douglas Gregor        return true;
5546931900f43cea558c6974075256c07728dbfecc6Douglas Gregor
5556931900f43cea558c6974075256c07728dbfecc6Douglas Gregor  if (Stmt *Body = B->getBody())
5566931900f43cea558c6974075256c07728dbfecc6Douglas Gregor    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
5576931900f43cea558c6974075256c07728dbfecc6Douglas Gregor
558a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor  return false;
559a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek}
560a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor
561a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregorllvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
562a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor  if (RegionOfInterest.isValid()) {
563aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
564a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor    if (Range.isInvalid())
565a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor      return llvm::Optional<bool>();
566a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor
567a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor    switch (CompareRegionOfInterest(Range)) {
568a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor    case RangeBefore:
569a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor      // This declaration comes before the region of interest; skip it.
570a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor      return llvm::Optional<bool>();
571a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor
572a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor    case RangeAfter:
573a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor      // This declaration comes after the region of interest; we're done.
574a67e03fdf1ae8a1f92463a307d0b6281f1161f40Douglas Gregor      return false;
575a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek
576a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    case RangeOverlap:
577aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      // This declaration overlaps the region of interest; visit it.
5783064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek      break;
5793064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek    }
5803064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek  }
5813064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek  return true;
5823064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek}
5833064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek
5843064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenekbool CursorVisitor::VisitDeclContext(DeclContext *DC) {
5853064ef9e604d19a0cfd0d8e3ed3055bfd83f88fdTed Kremenek  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
5869f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor
587a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  // FIXME: Eventually remove.  This part of a hack to support proper
588aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // iteration over all Decls contained lexically within an ObjC container.
5899f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
5909f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
5919f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor
5929f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor  for ( ; I != E; ++I) {
5939f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor    Decl *D = *I;
5949f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor    if (D->getLexicalDeclContext() != DC)
5959f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor      continue;
5969f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
5979f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor
598ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    // Ignore synthesized ivars here, otherwise if we have something like:
5999f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor    //   @synthesize prop = _prop;
6004807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor    // and '_prop' is not declared, we will encounter a '_prop' ivar before
6014807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor    // encountering the 'prop' synthesize declaration and we will think that
602ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    // we passed the region-of-interest.
603ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
6044807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor      if (ivarD->getSynthesize())
6054807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor        continue;
606a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    }
607a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek
608aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
609572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor    // declarations is a mismatch with the compiler semantics.
610572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor    if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
611572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor      ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
612572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor      if (!ID->isThisDeclarationADefinition())
613572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor        Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
614572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor
615572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor    } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
616572feb2a190b5e8b04fb06c4ac50ee0f61e93ff0Douglas Gregor      ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
6179e5bb85ac899eeab7c21b5ff9030c3da6ff4837bChandler Carruth      if (!PD->isThisDeclarationADefinition())
6189e5bb85ac899eeab7c21b5ff9030c3da6ff4837bChandler Carruth        Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
619aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    }
6204807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor
6214807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
6224807231938d8aff28de09f78f301f9ba5845e5e4Douglas Gregor    if (!V.hasValue())
6239e5bb85ac899eeab7c21b5ff9030c3da6ff4837bChandler Carruth      continue;
6249b2a0ac970a077bdc0bf08c6c682f80ad733c892Chandler Carruth    if (!V.getValue())
6259e5bb85ac899eeab7c21b5ff9030c3da6ff4837bChandler Carruth      return false;
6269f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor    if (Visit(Cursor, true))
6279f1e3ff3b3095967e2b92b57a53524e2d6bb141cDouglas Gregor      return true;
628ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor  }
629a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  return false;
630aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
631ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor
632ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregorbool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
633ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor  llvm_unreachable("Translation units are visited directly by Visit()");
634ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor}
635ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor
636ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregorbool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
637ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
638ecdcb883cbc6bb4a2445dc6f02d58d9bdb54a0edDouglas Gregor    return Visit(TSInfo->getTypeLoc());
63936897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
640a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  return false;
64136897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor}
64236897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
64336897b05ca2886e287f01802614bc10cbadcec22Douglas Gregorbool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
644aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
64536897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor    return Visit(TSInfo->getTypeLoc());
64636897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
64736897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor  return false;
64836897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor}
64936897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
65036897b05ca2886e287f01802614bc10cbadcec22Douglas Gregorbool CursorVisitor::VisitTagDecl(TagDecl *D) {
65136897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor  return VisitDeclContext(D);
65236897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor}
65336897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor
65436897b05ca2886e287f01802614bc10cbadcec22Douglas Gregorbool CursorVisitor::VisitClassTemplateSpecializationDecl(
65536897b05ca2886e287f01802614bc10cbadcec22Douglas Gregor                                          ClassTemplateSpecializationDecl *D) {
6561f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  bool ShouldVisitBody = false;
657a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  switch (D->getSpecializationKind()) {
6581f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  case TSK_Undeclared:
6591f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  case TSK_ImplicitInstantiation:
6601f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    // Nothing to visit
6611f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    return false;
662aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
6631f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  case TSK_ExplicitInstantiationDeclaration:
6641f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  case TSK_ExplicitInstantiationDefinition:
6651f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    break;
6661f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
6671f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  case TSK_ExplicitSpecialization:
6681f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    ShouldVisitBody = true;
6691f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    break;
670a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  }
6711f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
6721f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  // Visit the template arguments used in the specialization.
6731f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
6741f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    TypeLoc TL = SpecType->getTypeLoc();
675aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    if (TemplateSpecializationTypeLoc *TSTLoc
6761f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
6771f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
6781f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
6791f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor          return true;
6801f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    }
6811f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  }
6821f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
683a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  if (ShouldVisitBody && VisitCXXRecordDecl(D))
6841f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    return true;
6851f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
6861f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  return false;
6871f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor}
688aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
6891f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregorbool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
6901f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor                                   ClassTemplatePartialSpecializationDecl *D) {
6911f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  // FIXME: Visit the "outer" template parameter lists on the TagDecl
6921f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  // before visiting these template parameters.
6931f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  if (VisitTemplateParameters(D->getTemplateParameters()))
6941f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    return true;
6951f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
6961f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  // Visit the partial specialization arguments.
6971f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
6981f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
6991f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
7001f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor      return true;
7011f60d9ea523fc321d811fe880ba9a1ec74fa8f9bDouglas Gregor
702283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  return VisitCXXRecordDecl(D);
703283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor}
704283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor
705283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregorbool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
706283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  // Visit the default argument.
707283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
708283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
709283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor      if (Visit(DefArg->getTypeLoc()))
710283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor        return true;
71178db0cdd49ec24034a5b2a4210fcda03a0919a81Douglas Gregor
7121adb082a709f7b588f03672999294e061234b2cfDouglas Gregor  return false;
7131adb082a709f7b588f03672999294e061234b2cfDouglas Gregor}
7142e331b938b38057e333fab0ba841130ea8467794Douglas Gregor
7152e331b938b38057e333fab0ba841130ea8467794Douglas Gregorbool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
716283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  if (Expr *Init = D->getInitExpr())
717283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
718283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  return false;
71995f33555a6d51b6537a9ed3968c3d1c2e4991b51Ted Kremenek}
72095f33555a6d51b6537a9ed3968c3d1c2e4991b51Ted Kremenek
72195f33555a6d51b6537a9ed3968c3d1c2e4991b51Ted Kremenekbool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
72295f33555a6d51b6537a9ed3968c3d1c2e4991b51Ted Kremenek  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
7238ccac3de1335f1cfd7cea56ba1cefcf0b724ce3fArgyrios Kyrtzidis    if (Visit(TSInfo->getTypeLoc()))
7248ccac3de1335f1cfd7cea56ba1cefcf0b724ce3fArgyrios Kyrtzidis      return true;
7258ccac3de1335f1cfd7cea56ba1cefcf0b724ce3fArgyrios Kyrtzidis
7268ccac3de1335f1cfd7cea56ba1cefcf0b724ce3fArgyrios Kyrtzidis  // Visit the nested-name-specifier, if present.
727f46034af49435a4d1a0085a4738343122aeb6521Douglas Gregor  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
728b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregor    if (VisitNestedNameSpecifierLoc(QualifierLoc))
729b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregor      return true;
73097b9872d5775446cb8aca1380e437649fe848d91Douglas Gregor
731b2cd48756119f4d8d2a865b4b3e0e8efd02e26a0Douglas Gregor  return false;
732a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek}
733a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek
734a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek/// \brief Compare two base or member initializers based on their source order.
735a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenekstatic int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
736a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek  CXXCtorInitializer const * const *X
737a60ed47da13393796d8552b9fdca12abbb3eea42Ted Kremenek    = static_cast<CXXCtorInitializer const * const *>(Xp);
738283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  CXXCtorInitializer const * const *Y
739283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor    = static_cast<CXXCtorInitializer const * const *>(Yp);
740b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
741b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
742b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    return -1;
743b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
744b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    return 1;
745b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  else
746b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    return 0;
747b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis}
748b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
749b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidisbool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
750b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
751b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // Visit the function declaration's syntactic components in the order
752b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // written. This requires a bit of work.
753b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
754b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
755b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
756b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // If we have a function declared directly (without the use of a typedef),
757b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // visit just the return type. Otherwise, just visit the function's type
758b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // now.
759b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
760b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        (!FTL && Visit(TL)))
761b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      return true;
762b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
763b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // Visit the nested-name-specifier, if present.
764b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
765b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      if (VisitNestedNameSpecifierLoc(QualifierLoc))
766b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        return true;
767b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
768b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // Visit the declaration name.
769b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if (VisitDeclarationNameInfo(ND->getNameInfo()))
770b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      return true;
771b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
772b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // FIXME: Visit explicitly-specified template arguments!
773b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
774b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // Visit the function parameters, if we have a function type.
775b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if (FTL && VisitFunctionTypeLoc(*FTL, true))
776b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      return true;
777b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
778b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    // FIXME: Attributes?
779b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  }
780b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
781b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
782b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
783b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      // Find the initializers that were written in the source.
784b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
785b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
786b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis                                          IEnd = Constructor->init_end();
787b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis           I != IEnd; ++I) {
788b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        if (!(*I)->isWritten())
789b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis          continue;
790b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
791b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        WrittenInits.push_back(*I);
792b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      }
793b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
794b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      // Sort the initializers in source order
795b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
796b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis                           &CompareCXXCtorInitializers);
797b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
798b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      // Visit the initializers in source order
799b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
800b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        CXXCtorInitializer *Init = WrittenInits[I];
801b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        if (Init->isAnyMemberInitializer()) {
802b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
803b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis                                        Init->getMemberLocation(), TU)))
804b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis            return true;
805b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
806b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis          if (Visit(TInfo->getTypeLoc()))
807b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis            return true;
808b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        }
809b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
810b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        // Visit the initializer value.
811b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis        if (Expr *Initializer = Init->getInit())
812b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
813b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis            return true;
814b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      }
815b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    }
816b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
817b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
818b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis      return true;
819b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  }
820b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
821b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  return false;
822b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis}
823b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis
824b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidisbool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
825b11be041e4f05519a2eabf6a99429ba6110f1ca9Argyrios Kyrtzidis  if (VisitDeclaratorDecl(D))
826aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
827aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
828aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (Expr *BitWidth = D->getBitWidth())
829aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
830aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
831aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return false;
832aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
833aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
834aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitVarDecl(VarDecl *D) {
835aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (VisitDeclaratorDecl(D))
836aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
837aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
838aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (Expr *Init = D->getInit())
839aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
840aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
841aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return false;
842aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
843aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
844aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
845aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (VisitDeclaratorDecl(D))
846aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
847aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
848aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
849aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    if (Expr *DefArg = D->getDefaultArgument())
850aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
851aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
852aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return false;
853aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
854aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
855aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
856aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
857aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // before visiting these template parameters.
858aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (VisitTemplateParameters(D->getTemplateParameters()))
859aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
860aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
861aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return VisitFunctionDecl(D->getTemplatedDecl());
862aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
863aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
864aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
865aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // FIXME: Visit the "outer" template parameter lists on the TagDecl
866aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  // before visiting these template parameters.
867aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (VisitTemplateParameters(D->getTemplateParameters()))
868aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
869aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
870aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return VisitCXXRecordDecl(D->getTemplatedDecl());
871aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
872aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
873aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
874aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (VisitTemplateParameters(D->getTemplateParameters()))
875aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
876aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
877aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
878aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      VisitTemplateArgumentLoc(D->getDefaultArgument()))
879aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
880aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
881aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return false;
882aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
883aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
884aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisbool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
885aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
886aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    if (Visit(TSInfo->getTypeLoc()))
887aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      return true;
888aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
889aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
890aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis       PEnd = ND->param_end();
891aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis       P != PEnd; ++P) {
892aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
893aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      return true;
894aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  }
895aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
896aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  if (ND->isThisDeclarationADefinition() &&
897aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
898aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis    return true;
899aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
900aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis  return false;
901aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis}
902aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis
903aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidistemplate <typename DeclIt>
904aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidisstatic void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
905aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis                                      SourceManager &SM, SourceLocation EndLoc,
906aed123ec3cc37e457fe20a6158fdadf8849ad916Argyrios Kyrtzidis                                      SmallVectorImpl<Decl *> &Decls) {
907283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  DeclIt next = *DI_current;
908283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor  while (++next != DE_current) {
909283cae37b03047c14ef918503bc46b08405c3b69Douglas Gregor    Decl *D_next = *next;
9102e331b938b38057e333fab0ba841130ea8467794Douglas Gregor    if (!D_next)
911007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek      break;
912007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek    SourceLocation L = D_next->getLocStart();
913007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek    if (!L.isValid())
914007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek      break;
915007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
916007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek      *DI_current = next;
917007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek      Decls.push_back(D_next);
918007a7c9d8dcdb2e9cd94b6075108bfc4c90e6ccdTed Kremenek      continue;
919eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    }
920b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis    break;
921b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis  }
922b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis}
923fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis
924fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidisnamespace {
925fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis  struct ContainerDeclsSort {
926fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis    SourceManager &SM;
927fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
928fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis    bool operator()(Decl *A, Decl *B) {
929b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis      SourceLocation L_A = A->getLocStart();
930b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis      SourceLocation L_B = B->getLocStart();
931b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis      assert(L_A.isValid() && L_B.isValid());
932b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis      return SM.isBeforeInTranslationUnit(L_A, L_B);
933fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis    }
934fa865df489fe68668c554dece36c68b4ce03920fArgyrios Kyrtzidis  };
935b0d6eaa6b646c18c49923aefc76973801f561701Argyrios Kyrtzidis}
936eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
937eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenekbool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
938eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
939eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // an @implementation can lexically contain Decls that are not properly
940eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // nested in the AST.  When we identify such cases, we need to retrofit
941eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // this nesting here.
942eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  if (!DI_current && !FileDI_current)
943eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    return VisitDeclContext(D);
944eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
945eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // Scan the Decls that immediately come after the container
946eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // in the current DeclContext.  If any fall within the
947eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // container's lexical region, stash them into a vector
948da6fb69873079a0193ed8c9fa1d1b859d4f87b95Ted Kremenek  // for later processing.
949eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  SmallVector<Decl *, 24> DeclsInContainer;
950eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  SourceLocation EndLoc = D->getSourceRange().getEnd();
951eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  SourceManager &SM = AU->getSourceManager();
952eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  if (EndLoc.isValid()) {
953eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    if (DI_current) {
954eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
955eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek                                DeclsInContainer);
956eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    } else {
957eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
958eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek                                DeclsInContainer);
959eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    }
960eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  }
961eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
962eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // The common case.
963eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  if (DeclsInContainer.empty())
964eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    return VisitDeclContext(D);
965eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
966eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // Get all the Decls in the DeclContext, and sort them with the
967eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // additional ones we've collected.  Then visit them.
968eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
969eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek       I!=E; ++I) {
970eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    Decl *subDecl = *I;
971eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
972eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek        subDecl->getLocStart().isInvalid())
973eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      continue;
974eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    DeclsInContainer.push_back(subDecl);
975eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  }
976eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
977eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // Now sort the Decls so that they appear in lexical order.
978eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
979eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek            ContainerDeclsSort(SM));
980eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
981eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  // Now visit the decls.
982eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
983eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek         E = DeclsInContainer.end(); I != E; ++I) {
984e8b3de090b9de3c27c5d381e767217ddb849d5d8Anders Carlsson    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
985eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
986eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    if (!V.hasValue())
987eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      continue;
988eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    if (!V.getValue())
989eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      return false;
990eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek    if (Visit(Cursor, true))
991eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek      return true;
992eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  }
993eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  return false;
994eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek}
995eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek
996eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenekbool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
997eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
9988fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor                                   TU)))
9998fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    return true;
10008fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10018fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
10028fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
10038fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor         E = ND->protocol_end(); I != E; ++I, ++PL)
10048fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
10058fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor      return true;
10068fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10078fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  return VisitObjCContainerDecl(ND);
10088fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor}
10098fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10108fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregorbool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
10118fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  if (!PID->isThisDeclarationADefinition())
10128fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
10138fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10148fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
10158fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
10168fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor       E = PID->protocol_end(); I != E; ++I, ++PL)
10178fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
10188fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor      return true;
10198fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10208fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  return VisitObjCContainerDecl(PID);
10218fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor}
10228fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10238fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregorbool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
10248fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1025eaf4fbab08b2636103b2da08412e33baff15ad2aDouglas Gregor    return true;
10268fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
10278fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // FIXME: This implements a workaround with @property declarations also being
10288fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // installed in the DeclContext for the @interface.  Eventually this code
10298fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // should be removed.
10308fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
10318fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  if (!CDecl || !CDecl->IsClassExtension())
10328fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    return false;
10338fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
1034eca099bdb0178d408d4f717c2e9627e0d0e673c6Ted Kremenek  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1035  if (!ID)
1036    return false;
1037
1038  IdentifierInfo *PropertyId = PD->getIdentifier();
1039  ObjCPropertyDecl *prevDecl =
1040    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1041
1042  if (!prevDecl)
1043    return false;
1044
1045  // Visit synthesized methods since they will be skipped when visiting
1046  // the @interface.
1047  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1048    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1049      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1050        return true;
1051
1052  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1053    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1054      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1055        return true;
1056
1057  return false;
1058}
1059
1060bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1061  if (!D->isThisDeclarationADefinition()) {
1062    // Forward declaration is treated like a reference.
1063    return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1064  }
1065
1066  // Issue callbacks for super class.
1067  if (D->getSuperClass() &&
1068      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1069                                        D->getSuperClassLoc(),
1070                                        TU)))
1071    return true;
1072
1073  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1074  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1075         E = D->protocol_end(); I != E; ++I, ++PL)
1076    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1077      return true;
1078
1079  return VisitObjCContainerDecl(D);
1080}
1081
1082bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1083  return VisitObjCContainerDecl(D);
1084}
1085
1086bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1087  // 'ID' could be null when dealing with invalid code.
1088  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1089    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1090      return true;
1091
1092  return VisitObjCImplDecl(D);
1093}
1094
1095bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1096#if 0
1097  // Issue callbacks for super class.
1098  // FIXME: No source location information!
1099  if (D->getSuperClass() &&
1100      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1101                                        D->getSuperClassLoc(),
1102                                        TU)))
1103    return true;
1104#endif
1105
1106  return VisitObjCImplDecl(D);
1107}
1108
1109bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1110  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1111    if (PD->isIvarNameSpecified())
1112      return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1113
1114  return false;
1115}
1116
1117bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1118  return VisitDeclContext(D);
1119}
1120
1121bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1122  // Visit nested-name-specifier.
1123  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1124    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1125      return true;
1126
1127  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1128                                      D->getTargetNameLoc(), TU));
1129}
1130
1131bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1132  // Visit nested-name-specifier.
1133  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1134    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1135      return true;
1136  }
1137
1138  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1139    return true;
1140
1141  return VisitDeclarationNameInfo(D->getNameInfo());
1142}
1143
1144bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1145  // Visit nested-name-specifier.
1146  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1147    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1148      return true;
1149
1150  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1151                                      D->getIdentLocation(), TU));
1152}
1153
1154bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1155  // Visit nested-name-specifier.
1156  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1157    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1158      return true;
1159  }
1160
1161  return VisitDeclarationNameInfo(D->getNameInfo());
1162}
1163
1164bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1165                                               UnresolvedUsingTypenameDecl *D) {
1166  // Visit nested-name-specifier.
1167  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1168    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1169      return true;
1170
1171  return false;
1172}
1173
1174bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1175  switch (Name.getName().getNameKind()) {
1176  case clang::DeclarationName::Identifier:
1177  case clang::DeclarationName::CXXLiteralOperatorName:
1178  case clang::DeclarationName::CXXOperatorName:
1179  case clang::DeclarationName::CXXUsingDirective:
1180    return false;
1181
1182  case clang::DeclarationName::CXXConstructorName:
1183  case clang::DeclarationName::CXXDestructorName:
1184  case clang::DeclarationName::CXXConversionFunctionName:
1185    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1186      return Visit(TSInfo->getTypeLoc());
1187    return false;
1188
1189  case clang::DeclarationName::ObjCZeroArgSelector:
1190  case clang::DeclarationName::ObjCOneArgSelector:
1191  case clang::DeclarationName::ObjCMultiArgSelector:
1192    // FIXME: Per-identifier location info?
1193    return false;
1194  }
1195
1196  llvm_unreachable("Invalid DeclarationName::Kind!");
1197}
1198
1199bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1200                                             SourceRange Range) {
1201  // FIXME: This whole routine is a hack to work around the lack of proper
1202  // source information in nested-name-specifiers (PR5791). Since we do have
1203  // a beginning source location, we can visit the first component of the
1204  // nested-name-specifier, if it's a single-token component.
1205  if (!NNS)
1206    return false;
1207
1208  // Get the first component in the nested-name-specifier.
1209  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1210    NNS = Prefix;
1211
1212  switch (NNS->getKind()) {
1213  case NestedNameSpecifier::Namespace:
1214    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1215                                        TU));
1216
1217  case NestedNameSpecifier::NamespaceAlias:
1218    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1219                                        Range.getBegin(), TU));
1220
1221  case NestedNameSpecifier::TypeSpec: {
1222    // If the type has a form where we know that the beginning of the source
1223    // range matches up with a reference cursor. Visit the appropriate reference
1224    // cursor.
1225    const Type *T = NNS->getAsType();
1226    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1227      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1228    if (const TagType *Tag = dyn_cast<TagType>(T))
1229      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1230    if (const TemplateSpecializationType *TST
1231                                      = dyn_cast<TemplateSpecializationType>(T))
1232      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1233    break;
1234  }
1235
1236  case NestedNameSpecifier::TypeSpecWithTemplate:
1237  case NestedNameSpecifier::Global:
1238  case NestedNameSpecifier::Identifier:
1239    break;
1240  }
1241
1242  return false;
1243}
1244
1245bool
1246CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1247  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1248  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1249    Qualifiers.push_back(Qualifier);
1250
1251  while (!Qualifiers.empty()) {
1252    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1253    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1254    switch (NNS->getKind()) {
1255    case NestedNameSpecifier::Namespace:
1256      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1257                                       Q.getLocalBeginLoc(),
1258                                       TU)))
1259        return true;
1260
1261      break;
1262
1263    case NestedNameSpecifier::NamespaceAlias:
1264      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1265                                       Q.getLocalBeginLoc(),
1266                                       TU)))
1267        return true;
1268
1269      break;
1270
1271    case NestedNameSpecifier::TypeSpec:
1272    case NestedNameSpecifier::TypeSpecWithTemplate:
1273      if (Visit(Q.getTypeLoc()))
1274        return true;
1275
1276      break;
1277
1278    case NestedNameSpecifier::Global:
1279    case NestedNameSpecifier::Identifier:
1280      break;
1281    }
1282  }
1283
1284  return false;
1285}
1286
1287bool CursorVisitor::VisitTemplateParameters(
1288                                          const TemplateParameterList *Params) {
1289  if (!Params)
1290    return false;
1291
1292  for (TemplateParameterList::const_iterator P = Params->begin(),
1293                                          PEnd = Params->end();
1294       P != PEnd; ++P) {
1295    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1296      return true;
1297  }
1298
1299  return false;
1300}
1301
1302bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1303  switch (Name.getKind()) {
1304  case TemplateName::Template:
1305    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1306
1307  case TemplateName::OverloadedTemplate:
1308    // Visit the overloaded template set.
1309    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1310      return true;
1311
1312    return false;
1313
1314  case TemplateName::DependentTemplate:
1315    // FIXME: Visit nested-name-specifier.
1316    return false;
1317
1318  case TemplateName::QualifiedTemplate:
1319    // FIXME: Visit nested-name-specifier.
1320    return Visit(MakeCursorTemplateRef(
1321                                  Name.getAsQualifiedTemplateName()->getDecl(),
1322                                       Loc, TU));
1323
1324  case TemplateName::SubstTemplateTemplateParm:
1325    return Visit(MakeCursorTemplateRef(
1326                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1327                                       Loc, TU));
1328
1329  case TemplateName::SubstTemplateTemplateParmPack:
1330    return Visit(MakeCursorTemplateRef(
1331                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1332                                       Loc, TU));
1333  }
1334
1335  llvm_unreachable("Invalid TemplateName::Kind!");
1336}
1337
1338bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1339  switch (TAL.getArgument().getKind()) {
1340  case TemplateArgument::Null:
1341  case TemplateArgument::Integral:
1342  case TemplateArgument::Pack:
1343    return false;
1344
1345  case TemplateArgument::Type:
1346    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1347      return Visit(TSInfo->getTypeLoc());
1348    return false;
1349
1350  case TemplateArgument::Declaration:
1351    if (Expr *E = TAL.getSourceDeclExpression())
1352      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1353    return false;
1354
1355  case TemplateArgument::NullPtr:
1356    if (Expr *E = TAL.getSourceNullPtrExpression())
1357      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1358    return false;
1359
1360  case TemplateArgument::Expression:
1361    if (Expr *E = TAL.getSourceExpression())
1362      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1363    return false;
1364
1365  case TemplateArgument::Template:
1366  case TemplateArgument::TemplateExpansion:
1367    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1368      return true;
1369
1370    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1371                             TAL.getTemplateNameLoc());
1372  }
1373
1374  llvm_unreachable("Invalid TemplateArgument::Kind!");
1375}
1376
1377bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1378  return VisitDeclContext(D);
1379}
1380
1381bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1382  return Visit(TL.getUnqualifiedLoc());
1383}
1384
1385bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1386  ASTContext &Context = AU->getASTContext();
1387
1388  // Some builtin types (such as Objective-C's "id", "sel", and
1389  // "Class") have associated declarations. Create cursors for those.
1390  QualType VisitType;
1391  switch (TL.getTypePtr()->getKind()) {
1392
1393  case BuiltinType::Void:
1394  case BuiltinType::NullPtr:
1395  case BuiltinType::Dependent:
1396  case BuiltinType::OCLImage1d:
1397  case BuiltinType::OCLImage1dArray:
1398  case BuiltinType::OCLImage1dBuffer:
1399  case BuiltinType::OCLImage2d:
1400  case BuiltinType::OCLImage2dArray:
1401  case BuiltinType::OCLImage3d:
1402  case BuiltinType::OCLEvent:
1403#define BUILTIN_TYPE(Id, SingletonId)
1404#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1405#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1406#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1407#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1408#include "clang/AST/BuiltinTypes.def"
1409    break;
1410
1411  case BuiltinType::ObjCId:
1412    VisitType = Context.getObjCIdType();
1413    break;
1414
1415  case BuiltinType::ObjCClass:
1416    VisitType = Context.getObjCClassType();
1417    break;
1418
1419  case BuiltinType::ObjCSel:
1420    VisitType = Context.getObjCSelType();
1421    break;
1422  }
1423
1424  if (!VisitType.isNull()) {
1425    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1426      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1427                                     TU));
1428  }
1429
1430  return false;
1431}
1432
1433bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1434  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1435}
1436
1437bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1438  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1439}
1440
1441bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1442  if (TL.isDefinition())
1443    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1444
1445  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1446}
1447
1448bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1449  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1450}
1451
1452bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1453  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1454    return true;
1455
1456  return false;
1457}
1458
1459bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1460  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1461    return true;
1462
1463  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1464    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1465                                        TU)))
1466      return true;
1467  }
1468
1469  return false;
1470}
1471
1472bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1473  return Visit(TL.getPointeeLoc());
1474}
1475
1476bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1477  return Visit(TL.getInnerLoc());
1478}
1479
1480bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1481  return Visit(TL.getPointeeLoc());
1482}
1483
1484bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1485  return Visit(TL.getPointeeLoc());
1486}
1487
1488bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1489  return Visit(TL.getPointeeLoc());
1490}
1491
1492bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1493  return Visit(TL.getPointeeLoc());
1494}
1495
1496bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1497  return Visit(TL.getPointeeLoc());
1498}
1499
1500bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1501  return Visit(TL.getModifiedLoc());
1502}
1503
1504bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1505                                         bool SkipResultType) {
1506  if (!SkipResultType && Visit(TL.getResultLoc()))
1507    return true;
1508
1509  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1510    if (Decl *D = TL.getArg(I))
1511      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1512        return true;
1513
1514  return false;
1515}
1516
1517bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1518  if (Visit(TL.getElementLoc()))
1519    return true;
1520
1521  if (Expr *Size = TL.getSizeExpr())
1522    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1523
1524  return false;
1525}
1526
1527bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1528                                             TemplateSpecializationTypeLoc TL) {
1529  // Visit the template name.
1530  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1531                        TL.getTemplateNameLoc()))
1532    return true;
1533
1534  // Visit the template arguments.
1535  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1536    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1537      return true;
1538
1539  return false;
1540}
1541
1542bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1543  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1544}
1545
1546bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1547  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1548    return Visit(TSInfo->getTypeLoc());
1549
1550  return false;
1551}
1552
1553bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1554  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1555    return Visit(TSInfo->getTypeLoc());
1556
1557  return false;
1558}
1559
1560bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1561  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1562    return true;
1563
1564  return false;
1565}
1566
1567bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1568                                    DependentTemplateSpecializationTypeLoc TL) {
1569  // Visit the nested-name-specifier, if there is one.
1570  if (TL.getQualifierLoc() &&
1571      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1572    return true;
1573
1574  // Visit the template arguments.
1575  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1576    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1577      return true;
1578
1579  return false;
1580}
1581
1582bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1583  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1584    return true;
1585
1586  return Visit(TL.getNamedTypeLoc());
1587}
1588
1589bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1590  return Visit(TL.getPatternLoc());
1591}
1592
1593bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1594  if (Expr *E = TL.getUnderlyingExpr())
1595    return Visit(MakeCXCursor(E, StmtParent, TU));
1596
1597  return false;
1598}
1599
1600bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1601  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1602}
1603
1604bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1605  return Visit(TL.getValueLoc());
1606}
1607
1608#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1609bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1610  return Visit##PARENT##Loc(TL); \
1611}
1612
1613DEFAULT_TYPELOC_IMPL(Complex, Type)
1614DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1615DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1616DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1617DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1618DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1619DEFAULT_TYPELOC_IMPL(Vector, Type)
1620DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1621DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1622DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1623DEFAULT_TYPELOC_IMPL(Record, TagType)
1624DEFAULT_TYPELOC_IMPL(Enum, TagType)
1625DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1626DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1627DEFAULT_TYPELOC_IMPL(Auto, Type)
1628
1629bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1630  // Visit the nested-name-specifier, if present.
1631  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1632    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1633      return true;
1634
1635  if (D->isCompleteDefinition()) {
1636    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1637         E = D->bases_end(); I != E; ++I) {
1638      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1639        return true;
1640    }
1641  }
1642
1643  return VisitTagDecl(D);
1644}
1645
1646bool CursorVisitor::VisitAttributes(Decl *D) {
1647  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1648       i != e; ++i)
1649    if (Visit(MakeCXCursor(*i, D, TU)))
1650        return true;
1651
1652  return false;
1653}
1654
1655//===----------------------------------------------------------------------===//
1656// Data-recursive visitor methods.
1657//===----------------------------------------------------------------------===//
1658
1659namespace {
1660#define DEF_JOB(NAME, DATA, KIND)\
1661class NAME : public VisitorJob {\
1662public:\
1663  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1664  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1665  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1666};
1667
1668DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1669DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1670DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1671DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1672DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1673        ExplicitTemplateArgsVisitKind)
1674DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1675DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1676DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1677#undef DEF_JOB
1678
1679class DeclVisit : public VisitorJob {
1680public:
1681  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1682    VisitorJob(parent, VisitorJob::DeclVisitKind,
1683               d, isFirst ? (void*) 1 : (void*) 0) {}
1684  static bool classof(const VisitorJob *VJ) {
1685    return VJ->getKind() == DeclVisitKind;
1686  }
1687  Decl *get() const { return static_cast<Decl*>(data[0]); }
1688  bool isFirst() const { return data[1] ? true : false; }
1689};
1690class TypeLocVisit : public VisitorJob {
1691public:
1692  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1693    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1694               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1695
1696  static bool classof(const VisitorJob *VJ) {
1697    return VJ->getKind() == TypeLocVisitKind;
1698  }
1699
1700  TypeLoc get() const {
1701    QualType T = QualType::getFromOpaquePtr(data[0]);
1702    return TypeLoc(T, data[1]);
1703  }
1704};
1705
1706class LabelRefVisit : public VisitorJob {
1707public:
1708  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1709    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1710                 labelLoc.getPtrEncoding()) {}
1711
1712  static bool classof(const VisitorJob *VJ) {
1713    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1714  }
1715  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1716  SourceLocation getLoc() const {
1717    return SourceLocation::getFromPtrEncoding(data[1]); }
1718};
1719
1720class NestedNameSpecifierLocVisit : public VisitorJob {
1721public:
1722  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1723    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1724                 Qualifier.getNestedNameSpecifier(),
1725                 Qualifier.getOpaqueData()) { }
1726
1727  static bool classof(const VisitorJob *VJ) {
1728    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1729  }
1730
1731  NestedNameSpecifierLoc get() const {
1732    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1733                                  data[1]);
1734  }
1735};
1736
1737class DeclarationNameInfoVisit : public VisitorJob {
1738public:
1739  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1740    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1741  static bool classof(const VisitorJob *VJ) {
1742    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1743  }
1744  DeclarationNameInfo get() const {
1745    Stmt *S = static_cast<Stmt*>(data[0]);
1746    switch (S->getStmtClass()) {
1747    default:
1748      llvm_unreachable("Unhandled Stmt");
1749    case clang::Stmt::MSDependentExistsStmtClass:
1750      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1751    case Stmt::CXXDependentScopeMemberExprClass:
1752      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1753    case Stmt::DependentScopeDeclRefExprClass:
1754      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1755    }
1756  }
1757};
1758class MemberRefVisit : public VisitorJob {
1759public:
1760  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1761    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1762                 L.getPtrEncoding()) {}
1763  static bool classof(const VisitorJob *VJ) {
1764    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1765  }
1766  FieldDecl *get() const {
1767    return static_cast<FieldDecl*>(data[0]);
1768  }
1769  SourceLocation getLoc() const {
1770    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1771  }
1772};
1773class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1774  VisitorWorkList &WL;
1775  CXCursor Parent;
1776public:
1777  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1778    : WL(wl), Parent(parent) {}
1779
1780  void VisitAddrLabelExpr(AddrLabelExpr *E);
1781  void VisitBlockExpr(BlockExpr *B);
1782  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1783  void VisitCompoundStmt(CompoundStmt *S);
1784  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1785  void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1786  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1787  void VisitCXXNewExpr(CXXNewExpr *E);
1788  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1789  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1790  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1791  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1792  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1793  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1794  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1795  void VisitCXXCatchStmt(CXXCatchStmt *S);
1796  void VisitDeclRefExpr(DeclRefExpr *D);
1797  void VisitDeclStmt(DeclStmt *S);
1798  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1799  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1800  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1801  void VisitForStmt(ForStmt *FS);
1802  void VisitGotoStmt(GotoStmt *GS);
1803  void VisitIfStmt(IfStmt *If);
1804  void VisitInitListExpr(InitListExpr *IE);
1805  void VisitMemberExpr(MemberExpr *M);
1806  void VisitOffsetOfExpr(OffsetOfExpr *E);
1807  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1808  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1809  void VisitOverloadExpr(OverloadExpr *E);
1810  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1811  void VisitStmt(Stmt *S);
1812  void VisitSwitchStmt(SwitchStmt *S);
1813  void VisitWhileStmt(WhileStmt *W);
1814  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1815  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1816  void VisitTypeTraitExpr(TypeTraitExpr *E);
1817  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1818  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1819  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1820  void VisitVAArgExpr(VAArgExpr *E);
1821  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1822  void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1823  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1824  void VisitLambdaExpr(LambdaExpr *E);
1825
1826private:
1827  void AddDeclarationNameInfo(Stmt *S);
1828  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1829  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1830  void AddMemberRef(FieldDecl *D, SourceLocation L);
1831  void AddStmt(Stmt *S);
1832  void AddDecl(Decl *D, bool isFirst = true);
1833  void AddTypeLoc(TypeSourceInfo *TI);
1834  void EnqueueChildren(Stmt *S);
1835};
1836} // end anonyous namespace
1837
1838void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1839  // 'S' should always be non-null, since it comes from the
1840  // statement we are visiting.
1841  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1842}
1843
1844void
1845EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1846  if (Qualifier)
1847    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1848}
1849
1850void EnqueueVisitor::AddStmt(Stmt *S) {
1851  if (S)
1852    WL.push_back(StmtVisit(S, Parent));
1853}
1854void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1855  if (D)
1856    WL.push_back(DeclVisit(D, Parent, isFirst));
1857}
1858void EnqueueVisitor::
1859  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1860  if (A)
1861    WL.push_back(ExplicitTemplateArgsVisit(
1862                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1863}
1864void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1865  if (D)
1866    WL.push_back(MemberRefVisit(D, L, Parent));
1867}
1868void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1869  if (TI)
1870    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1871 }
1872void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1873  unsigned size = WL.size();
1874  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1875    AddStmt(*Child);
1876  }
1877  if (size == WL.size())
1878    return;
1879  // Now reverse the entries we just added.  This will match the DFS
1880  // ordering performed by the worklist.
1881  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1882  std::reverse(I, E);
1883}
1884void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1885  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1886}
1887void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1888  AddDecl(B->getBlockDecl());
1889}
1890void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1891  EnqueueChildren(E);
1892  AddTypeLoc(E->getTypeSourceInfo());
1893}
1894void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1895  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1896        E = S->body_rend(); I != E; ++I) {
1897    AddStmt(*I);
1898  }
1899}
1900void EnqueueVisitor::
1901VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1902  AddStmt(S->getSubStmt());
1903  AddDeclarationNameInfo(S);
1904  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1905    AddNestedNameSpecifierLoc(QualifierLoc);
1906}
1907
1908void EnqueueVisitor::
1909VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1910  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1911  AddDeclarationNameInfo(E);
1912  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1913    AddNestedNameSpecifierLoc(QualifierLoc);
1914  if (!E->isImplicitAccess())
1915    AddStmt(E->getBase());
1916}
1917void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1918  // Enqueue the initializer , if any.
1919  AddStmt(E->getInitializer());
1920  // Enqueue the array size, if any.
1921  AddStmt(E->getArraySize());
1922  // Enqueue the allocated type.
1923  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1924  // Enqueue the placement arguments.
1925  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1926    AddStmt(E->getPlacementArg(I-1));
1927}
1928void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1929  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1930    AddStmt(CE->getArg(I-1));
1931  AddStmt(CE->getCallee());
1932  AddStmt(CE->getArg(0));
1933}
1934void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1935  // Visit the name of the type being destroyed.
1936  AddTypeLoc(E->getDestroyedTypeInfo());
1937  // Visit the scope type that looks disturbingly like the nested-name-specifier
1938  // but isn't.
1939  AddTypeLoc(E->getScopeTypeInfo());
1940  // Visit the nested-name-specifier.
1941  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1942    AddNestedNameSpecifierLoc(QualifierLoc);
1943  // Visit base expression.
1944  AddStmt(E->getBase());
1945}
1946void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1947  AddTypeLoc(E->getTypeSourceInfo());
1948}
1949void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1950  EnqueueChildren(E);
1951  AddTypeLoc(E->getTypeSourceInfo());
1952}
1953void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1954  EnqueueChildren(E);
1955  if (E->isTypeOperand())
1956    AddTypeLoc(E->getTypeOperandSourceInfo());
1957}
1958
1959void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1960                                                     *E) {
1961  EnqueueChildren(E);
1962  AddTypeLoc(E->getTypeSourceInfo());
1963}
1964void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1965  EnqueueChildren(E);
1966  if (E->isTypeOperand())
1967    AddTypeLoc(E->getTypeOperandSourceInfo());
1968}
1969
1970void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1971  EnqueueChildren(S);
1972  AddDecl(S->getExceptionDecl());
1973}
1974
1975void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1976  if (DR->hasExplicitTemplateArgs()) {
1977    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1978  }
1979  WL.push_back(DeclRefExprParts(DR, Parent));
1980}
1981void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1982  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1983  AddDeclarationNameInfo(E);
1984  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1985}
1986void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1987  unsigned size = WL.size();
1988  bool isFirst = true;
1989  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1990       D != DEnd; ++D) {
1991    AddDecl(*D, isFirst);
1992    isFirst = false;
1993  }
1994  if (size == WL.size())
1995    return;
1996  // Now reverse the entries we just added.  This will match the DFS
1997  // ordering performed by the worklist.
1998  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1999  std::reverse(I, E);
2000}
2001void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
2002  AddStmt(E->getInit());
2003  typedef DesignatedInitExpr::Designator Designator;
2004  for (DesignatedInitExpr::reverse_designators_iterator
2005         D = E->designators_rbegin(), DEnd = E->designators_rend();
2006         D != DEnd; ++D) {
2007    if (D->isFieldDesignator()) {
2008      if (FieldDecl *Field = D->getField())
2009        AddMemberRef(Field, D->getFieldLoc());
2010      continue;
2011    }
2012    if (D->isArrayDesignator()) {
2013      AddStmt(E->getArrayIndex(*D));
2014      continue;
2015    }
2016    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2017    AddStmt(E->getArrayRangeEnd(*D));
2018    AddStmt(E->getArrayRangeStart(*D));
2019  }
2020}
2021void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2022  EnqueueChildren(E);
2023  AddTypeLoc(E->getTypeInfoAsWritten());
2024}
2025void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2026  AddStmt(FS->getBody());
2027  AddStmt(FS->getInc());
2028  AddStmt(FS->getCond());
2029  AddDecl(FS->getConditionVariable());
2030  AddStmt(FS->getInit());
2031}
2032void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2033  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2034}
2035void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2036  AddStmt(If->getElse());
2037  AddStmt(If->getThen());
2038  AddStmt(If->getCond());
2039  AddDecl(If->getConditionVariable());
2040}
2041void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2042  // We care about the syntactic form of the initializer list, only.
2043  if (InitListExpr *Syntactic = IE->getSyntacticForm())
2044    IE = Syntactic;
2045  EnqueueChildren(IE);
2046}
2047void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
2048  WL.push_back(MemberExprParts(M, Parent));
2049
2050  // If the base of the member access expression is an implicit 'this', don't
2051  // visit it.
2052  // FIXME: If we ever want to show these implicit accesses, this will be
2053  // unfortunate. However, clang_getCursor() relies on this behavior.
2054  if (!M->isImplicitAccess())
2055    AddStmt(M->getBase());
2056}
2057void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2058  AddTypeLoc(E->getEncodedTypeSourceInfo());
2059}
2060void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2061  EnqueueChildren(M);
2062  AddTypeLoc(M->getClassReceiverTypeInfo());
2063}
2064void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2065  // Visit the components of the offsetof expression.
2066  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2067    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2068    const OffsetOfNode &Node = E->getComponent(I-1);
2069    switch (Node.getKind()) {
2070    case OffsetOfNode::Array:
2071      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2072      break;
2073    case OffsetOfNode::Field:
2074      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2075      break;
2076    case OffsetOfNode::Identifier:
2077    case OffsetOfNode::Base:
2078      continue;
2079    }
2080  }
2081  // Visit the type into which we're computing the offset.
2082  AddTypeLoc(E->getTypeSourceInfo());
2083}
2084void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2085  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2086  WL.push_back(OverloadExprParts(E, Parent));
2087}
2088void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2089                                              UnaryExprOrTypeTraitExpr *E) {
2090  EnqueueChildren(E);
2091  if (E->isArgumentType())
2092    AddTypeLoc(E->getArgumentTypeInfo());
2093}
2094void EnqueueVisitor::VisitStmt(Stmt *S) {
2095  EnqueueChildren(S);
2096}
2097void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2098  AddStmt(S->getBody());
2099  AddStmt(S->getCond());
2100  AddDecl(S->getConditionVariable());
2101}
2102
2103void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2104  AddStmt(W->getBody());
2105  AddStmt(W->getCond());
2106  AddDecl(W->getConditionVariable());
2107}
2108
2109void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2110  AddTypeLoc(E->getQueriedTypeSourceInfo());
2111}
2112
2113void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2114  AddTypeLoc(E->getRhsTypeSourceInfo());
2115  AddTypeLoc(E->getLhsTypeSourceInfo());
2116}
2117
2118void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2119  for (unsigned I = E->getNumArgs(); I > 0; --I)
2120    AddTypeLoc(E->getArg(I-1));
2121}
2122
2123void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2124  AddTypeLoc(E->getQueriedTypeSourceInfo());
2125}
2126
2127void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2128  EnqueueChildren(E);
2129}
2130
2131void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2132  VisitOverloadExpr(U);
2133  if (!U->isImplicitAccess())
2134    AddStmt(U->getBase());
2135}
2136void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2137  AddStmt(E->getSubExpr());
2138  AddTypeLoc(E->getWrittenTypeInfo());
2139}
2140void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2141  WL.push_back(SizeOfPackExprParts(E, Parent));
2142}
2143void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2144  // If the opaque value has a source expression, just transparently
2145  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2146  if (Expr *SourceExpr = E->getSourceExpr())
2147    return Visit(SourceExpr);
2148}
2149void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2150  AddStmt(E->getBody());
2151  WL.push_back(LambdaExprParts(E, Parent));
2152}
2153void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2154  // Treat the expression like its syntactic form.
2155  Visit(E->getSyntacticForm());
2156}
2157
2158void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2159  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2160}
2161
2162bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2163  if (RegionOfInterest.isValid()) {
2164    SourceRange Range = getRawCursorExtent(C);
2165    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2166      return false;
2167  }
2168  return true;
2169}
2170
2171bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2172  while (!WL.empty()) {
2173    // Dequeue the worklist item.
2174    VisitorJob LI = WL.back();
2175    WL.pop_back();
2176
2177    // Set the Parent field, then back to its old value once we're done.
2178    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2179
2180    switch (LI.getKind()) {
2181      case VisitorJob::DeclVisitKind: {
2182        Decl *D = cast<DeclVisit>(&LI)->get();
2183        if (!D)
2184          continue;
2185
2186        // For now, perform default visitation for Decls.
2187        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2188                               cast<DeclVisit>(&LI)->isFirst())))
2189            return true;
2190
2191        continue;
2192      }
2193      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2194        const ASTTemplateArgumentListInfo *ArgList =
2195          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2196        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2197               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2198               Arg != ArgEnd; ++Arg) {
2199          if (VisitTemplateArgumentLoc(*Arg))
2200            return true;
2201        }
2202        continue;
2203      }
2204      case VisitorJob::TypeLocVisitKind: {
2205        // Perform default visitation for TypeLocs.
2206        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2207          return true;
2208        continue;
2209      }
2210      case VisitorJob::LabelRefVisitKind: {
2211        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2212        if (LabelStmt *stmt = LS->getStmt()) {
2213          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2214                                       TU))) {
2215            return true;
2216          }
2217        }
2218        continue;
2219      }
2220
2221      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2222        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2223        if (VisitNestedNameSpecifierLoc(V->get()))
2224          return true;
2225        continue;
2226      }
2227
2228      case VisitorJob::DeclarationNameInfoVisitKind: {
2229        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2230                                     ->get()))
2231          return true;
2232        continue;
2233      }
2234      case VisitorJob::MemberRefVisitKind: {
2235        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2236        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2237          return true;
2238        continue;
2239      }
2240      case VisitorJob::StmtVisitKind: {
2241        Stmt *S = cast<StmtVisit>(&LI)->get();
2242        if (!S)
2243          continue;
2244
2245        // Update the current cursor.
2246        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2247        if (!IsInRegionOfInterest(Cursor))
2248          continue;
2249        switch (Visitor(Cursor, Parent, ClientData)) {
2250          case CXChildVisit_Break: return true;
2251          case CXChildVisit_Continue: break;
2252          case CXChildVisit_Recurse:
2253            if (PostChildrenVisitor)
2254              WL.push_back(PostChildrenVisit(0, Cursor));
2255            EnqueueWorkList(WL, S);
2256            break;
2257        }
2258        continue;
2259      }
2260      case VisitorJob::MemberExprPartsKind: {
2261        // Handle the other pieces in the MemberExpr besides the base.
2262        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2263
2264        // Visit the nested-name-specifier
2265        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2266          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2267            return true;
2268
2269        // Visit the declaration name.
2270        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2271          return true;
2272
2273        // Visit the explicitly-specified template arguments, if any.
2274        if (M->hasExplicitTemplateArgs()) {
2275          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2276               *ArgEnd = Arg + M->getNumTemplateArgs();
2277               Arg != ArgEnd; ++Arg) {
2278            if (VisitTemplateArgumentLoc(*Arg))
2279              return true;
2280          }
2281        }
2282        continue;
2283      }
2284      case VisitorJob::DeclRefExprPartsKind: {
2285        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2286        // Visit nested-name-specifier, if present.
2287        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2288          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2289            return true;
2290        // Visit declaration name.
2291        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2292          return true;
2293        continue;
2294      }
2295      case VisitorJob::OverloadExprPartsKind: {
2296        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2297        // Visit the nested-name-specifier.
2298        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2299          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2300            return true;
2301        // Visit the declaration name.
2302        if (VisitDeclarationNameInfo(O->getNameInfo()))
2303          return true;
2304        // Visit the overloaded declaration reference.
2305        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2306          return true;
2307        continue;
2308      }
2309      case VisitorJob::SizeOfPackExprPartsKind: {
2310        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2311        NamedDecl *Pack = E->getPack();
2312        if (isa<TemplateTypeParmDecl>(Pack)) {
2313          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2314                                      E->getPackLoc(), TU)))
2315            return true;
2316
2317          continue;
2318        }
2319
2320        if (isa<TemplateTemplateParmDecl>(Pack)) {
2321          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2322                                          E->getPackLoc(), TU)))
2323            return true;
2324
2325          continue;
2326        }
2327
2328        // Non-type template parameter packs and function parameter packs are
2329        // treated like DeclRefExpr cursors.
2330        continue;
2331      }
2332
2333      case VisitorJob::LambdaExprPartsKind: {
2334        // Visit captures.
2335        LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2336        for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2337                                       CEnd = E->explicit_capture_end();
2338             C != CEnd; ++C) {
2339          if (C->capturesThis())
2340            continue;
2341
2342          if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2343                                          C->getLocation(),
2344                                          TU)))
2345            return true;
2346        }
2347
2348        // Visit parameters and return type, if present.
2349        if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2350          TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2351          if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2352            // Visit the whole type.
2353            if (Visit(TL))
2354              return true;
2355          } else if (isa<FunctionProtoTypeLoc>(TL)) {
2356            FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2357            if (E->hasExplicitParameters()) {
2358              // Visit parameters.
2359              for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2360                if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2361                  return true;
2362            } else {
2363              // Visit result type.
2364              if (Visit(Proto.getResultLoc()))
2365                return true;
2366            }
2367          }
2368        }
2369        break;
2370      }
2371
2372      case VisitorJob::PostChildrenVisitKind:
2373        if (PostChildrenVisitor(Parent, ClientData))
2374          return true;
2375        break;
2376    }
2377  }
2378  return false;
2379}
2380
2381bool CursorVisitor::Visit(Stmt *S) {
2382  VisitorWorkList *WL = 0;
2383  if (!WorkListFreeList.empty()) {
2384    WL = WorkListFreeList.back();
2385    WL->clear();
2386    WorkListFreeList.pop_back();
2387  }
2388  else {
2389    WL = new VisitorWorkList();
2390    WorkListCache.push_back(WL);
2391  }
2392  EnqueueWorkList(*WL, S);
2393  bool result = RunVisitorWorkList(*WL);
2394  WorkListFreeList.push_back(WL);
2395  return result;
2396}
2397
2398namespace {
2399typedef SmallVector<SourceRange, 4> RefNamePieces;
2400RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2401                          const DeclarationNameInfo &NI,
2402                          const SourceRange &QLoc,
2403                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2404  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2405  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2406  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2407
2408  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2409
2410  RefNamePieces Pieces;
2411
2412  if (WantQualifier && QLoc.isValid())
2413    Pieces.push_back(QLoc);
2414
2415  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2416    Pieces.push_back(NI.getLoc());
2417
2418  if (WantTemplateArgs && TemplateArgs)
2419    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2420                                 TemplateArgs->RAngleLoc));
2421
2422  if (Kind == DeclarationName::CXXOperatorName) {
2423    Pieces.push_back(SourceLocation::getFromRawEncoding(
2424                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2425    Pieces.push_back(SourceLocation::getFromRawEncoding(
2426                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2427  }
2428
2429  if (WantSinglePiece) {
2430    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2431    Pieces.clear();
2432    Pieces.push_back(R);
2433  }
2434
2435  return Pieces;
2436}
2437}
2438
2439//===----------------------------------------------------------------------===//
2440// Misc. API hooks.
2441//===----------------------------------------------------------------------===//
2442
2443static llvm::sys::Mutex EnableMultithreadingMutex;
2444static bool EnabledMultithreading;
2445
2446static void fatal_error_handler(void *user_data, const std::string& reason) {
2447  // Write the result out to stderr avoiding errs() because raw_ostreams can
2448  // call report_fatal_error.
2449  fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2450  ::abort();
2451}
2452
2453extern "C" {
2454CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2455                          int displayDiagnostics) {
2456  // Disable pretty stack trace functionality, which will otherwise be a very
2457  // poor citizen of the world and set up all sorts of signal handlers.
2458  llvm::DisablePrettyStackTrace = true;
2459
2460  // We use crash recovery to make some of our APIs more reliable, implicitly
2461  // enable it.
2462  llvm::CrashRecoveryContext::Enable();
2463
2464  // Enable support for multithreading in LLVM.
2465  {
2466    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2467    if (!EnabledMultithreading) {
2468      llvm::install_fatal_error_handler(fatal_error_handler, 0);
2469      llvm::llvm_start_multithreaded();
2470      EnabledMultithreading = true;
2471    }
2472  }
2473
2474  CIndexer *CIdxr = new CIndexer();
2475  if (excludeDeclarationsFromPCH)
2476    CIdxr->setOnlyLocalDecls();
2477  if (displayDiagnostics)
2478    CIdxr->setDisplayDiagnostics();
2479
2480  if (getenv("LIBCLANG_BGPRIO_INDEX"))
2481    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2482                               CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2483  if (getenv("LIBCLANG_BGPRIO_EDIT"))
2484    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2485                               CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2486
2487  return CIdxr;
2488}
2489
2490void clang_disposeIndex(CXIndex CIdx) {
2491  if (CIdx)
2492    delete static_cast<CIndexer *>(CIdx);
2493}
2494
2495void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2496  if (CIdx)
2497    static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2498}
2499
2500unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2501  if (CIdx)
2502    return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2503  return 0;
2504}
2505
2506void clang_toggleCrashRecovery(unsigned isEnabled) {
2507  if (isEnabled)
2508    llvm::CrashRecoveryContext::Enable();
2509  else
2510    llvm::CrashRecoveryContext::Disable();
2511}
2512
2513CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2514                                              const char *ast_filename) {
2515  if (!CIdx)
2516    return 0;
2517
2518  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2519  FileSystemOptions FileSystemOpts;
2520
2521  IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2522  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2523                                  CXXIdx->getOnlyLocalDecls(),
2524                                  0, 0,
2525                                  /*CaptureDiagnostics=*/true,
2526                                  /*AllowPCHWithCompilerErrors=*/true,
2527                                  /*UserFilesAreVolatile=*/true);
2528  return MakeCXTranslationUnit(CXXIdx, TU);
2529}
2530
2531unsigned clang_defaultEditingTranslationUnitOptions() {
2532  return CXTranslationUnit_PrecompiledPreamble |
2533         CXTranslationUnit_CacheCompletionResults;
2534}
2535
2536CXTranslationUnit
2537clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2538                                          const char *source_filename,
2539                                          int num_command_line_args,
2540                                          const char * const *command_line_args,
2541                                          unsigned num_unsaved_files,
2542                                          struct CXUnsavedFile *unsaved_files) {
2543  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2544  return clang_parseTranslationUnit(CIdx, source_filename,
2545                                    command_line_args, num_command_line_args,
2546                                    unsaved_files, num_unsaved_files,
2547                                    Options);
2548}
2549
2550struct ParseTranslationUnitInfo {
2551  CXIndex CIdx;
2552  const char *source_filename;
2553  const char *const *command_line_args;
2554  int num_command_line_args;
2555  struct CXUnsavedFile *unsaved_files;
2556  unsigned num_unsaved_files;
2557  unsigned options;
2558  CXTranslationUnit result;
2559};
2560static void clang_parseTranslationUnit_Impl(void *UserData) {
2561  ParseTranslationUnitInfo *PTUI =
2562    static_cast<ParseTranslationUnitInfo*>(UserData);
2563  CXIndex CIdx = PTUI->CIdx;
2564  const char *source_filename = PTUI->source_filename;
2565  const char * const *command_line_args = PTUI->command_line_args;
2566  int num_command_line_args = PTUI->num_command_line_args;
2567  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2568  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2569  unsigned options = PTUI->options;
2570  PTUI->result = 0;
2571
2572  if (!CIdx)
2573    return;
2574
2575  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2576
2577  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2578    setThreadBackgroundPriority();
2579
2580  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2581  // FIXME: Add a flag for modules.
2582  TranslationUnitKind TUKind
2583    = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2584  bool CacheCodeCompetionResults
2585    = options & CXTranslationUnit_CacheCompletionResults;
2586  bool IncludeBriefCommentsInCodeCompletion
2587    = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
2588  bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2589  bool ForSerialization = options & CXTranslationUnit_ForSerialization;
2590
2591  // Configure the diagnostics.
2592  IntrusiveRefCntPtr<DiagnosticsEngine>
2593    Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
2594
2595  // Recover resources if we crash before exiting this function.
2596  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2597    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2598    DiagCleanup(Diags.getPtr());
2599
2600  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2601    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2602
2603  // Recover resources if we crash before exiting this function.
2604  llvm::CrashRecoveryContextCleanupRegistrar<
2605    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2606
2607  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2608    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2609    const llvm::MemoryBuffer *Buffer
2610      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2611    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2612                                            Buffer));
2613  }
2614
2615  OwningPtr<std::vector<const char *> >
2616    Args(new std::vector<const char*>());
2617
2618  // Recover resources if we crash before exiting this method.
2619  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2620    ArgsCleanup(Args.get());
2621
2622  // Since the Clang C library is primarily used by batch tools dealing with
2623  // (often very broken) source code, where spell-checking can have a
2624  // significant negative impact on performance (particularly when
2625  // precompiled headers are involved), we disable it by default.
2626  // Only do this if we haven't found a spell-checking-related argument.
2627  bool FoundSpellCheckingArgument = false;
2628  for (int I = 0; I != num_command_line_args; ++I) {
2629    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2630        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2631      FoundSpellCheckingArgument = true;
2632      break;
2633    }
2634  }
2635  if (!FoundSpellCheckingArgument)
2636    Args->push_back("-fno-spell-checking");
2637
2638  Args->insert(Args->end(), command_line_args,
2639               command_line_args + num_command_line_args);
2640
2641  // The 'source_filename' argument is optional.  If the caller does not
2642  // specify it then it is assumed that the source file is specified
2643  // in the actual argument list.
2644  // Put the source file after command_line_args otherwise if '-x' flag is
2645  // present it will be unused.
2646  if (source_filename)
2647    Args->push_back(source_filename);
2648
2649  // Do we need the detailed preprocessing record?
2650  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2651    Args->push_back("-Xclang");
2652    Args->push_back("-detailed-preprocessing-record");
2653  }
2654
2655  unsigned NumErrors = Diags->getClient()->getNumErrors();
2656  OwningPtr<ASTUnit> ErrUnit;
2657  OwningPtr<ASTUnit> Unit(
2658    ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2659                                 /* vector::data() not portable */,
2660                                 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2661                                 Diags,
2662                                 CXXIdx->getClangResourcesPath(),
2663                                 CXXIdx->getOnlyLocalDecls(),
2664                                 /*CaptureDiagnostics=*/true,
2665                                 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2666                                 RemappedFiles->size(),
2667                                 /*RemappedFilesKeepOriginalName=*/true,
2668                                 PrecompilePreamble,
2669                                 TUKind,
2670                                 CacheCodeCompetionResults,
2671                                 IncludeBriefCommentsInCodeCompletion,
2672                                 /*AllowPCHWithCompilerErrors=*/true,
2673                                 SkipFunctionBodies,
2674                                 /*UserFilesAreVolatile=*/true,
2675                                 ForSerialization,
2676                                 &ErrUnit));
2677
2678  if (NumErrors != Diags->getClient()->getNumErrors()) {
2679    // Make sure to check that 'Unit' is non-NULL.
2680    if (CXXIdx->getDisplayDiagnostics())
2681      printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2682  }
2683
2684  PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2685}
2686CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2687                                             const char *source_filename,
2688                                         const char * const *command_line_args,
2689                                             int num_command_line_args,
2690                                            struct CXUnsavedFile *unsaved_files,
2691                                             unsigned num_unsaved_files,
2692                                             unsigned options) {
2693  LOG_FUNC_SECTION {
2694    *Log << source_filename << ": ";
2695    for (int i = 0; i != num_command_line_args; ++i)
2696      *Log << command_line_args[i] << " ";
2697  }
2698
2699  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2700                                    num_command_line_args, unsaved_files,
2701                                    num_unsaved_files, options, 0 };
2702  llvm::CrashRecoveryContext CRC;
2703
2704  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2705    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2706    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2707    fprintf(stderr, "  'command_line_args' : [");
2708    for (int i = 0; i != num_command_line_args; ++i) {
2709      if (i)
2710        fprintf(stderr, ", ");
2711      fprintf(stderr, "'%s'", command_line_args[i]);
2712    }
2713    fprintf(stderr, "],\n");
2714    fprintf(stderr, "  'unsaved_files' : [");
2715    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2716      if (i)
2717        fprintf(stderr, ", ");
2718      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2719              unsaved_files[i].Length);
2720    }
2721    fprintf(stderr, "],\n");
2722    fprintf(stderr, "  'options' : %d,\n", options);
2723    fprintf(stderr, "}\n");
2724
2725    return 0;
2726  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2727    PrintLibclangResourceUsage(PTUI.result);
2728  }
2729
2730  return PTUI.result;
2731}
2732
2733unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2734  return CXSaveTranslationUnit_None;
2735}
2736
2737namespace {
2738
2739struct SaveTranslationUnitInfo {
2740  CXTranslationUnit TU;
2741  const char *FileName;
2742  unsigned options;
2743  CXSaveError result;
2744};
2745
2746}
2747
2748static void clang_saveTranslationUnit_Impl(void *UserData) {
2749  SaveTranslationUnitInfo *STUI =
2750    static_cast<SaveTranslationUnitInfo*>(UserData);
2751
2752  CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2753  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2754    setThreadBackgroundPriority();
2755
2756  bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2757  STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
2758}
2759
2760int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2761                              unsigned options) {
2762  LOG_FUNC_SECTION {
2763    *Log << TU << ' ' << FileName;
2764  }
2765
2766  if (!TU)
2767    return CXSaveError_InvalidTU;
2768
2769  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2770  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2771  if (!CXXUnit->hasSema())
2772    return CXSaveError_InvalidTU;
2773
2774  SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2775
2776  if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2777      getenv("LIBCLANG_NOTHREADS")) {
2778    clang_saveTranslationUnit_Impl(&STUI);
2779
2780    if (getenv("LIBCLANG_RESOURCE_USAGE"))
2781      PrintLibclangResourceUsage(TU);
2782
2783    return STUI.result;
2784  }
2785
2786  // We have an AST that has invalid nodes due to compiler errors.
2787  // Use a crash recovery thread for protection.
2788
2789  llvm::CrashRecoveryContext CRC;
2790
2791  if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2792    fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2793    fprintf(stderr, "  'filename' : '%s'\n", FileName);
2794    fprintf(stderr, "  'options' : %d,\n", options);
2795    fprintf(stderr, "}\n");
2796
2797    return CXSaveError_Unknown;
2798
2799  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2800    PrintLibclangResourceUsage(TU);
2801  }
2802
2803  return STUI.result;
2804}
2805
2806void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2807  if (CTUnit) {
2808    // If the translation unit has been marked as unsafe to free, just discard
2809    // it.
2810    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2811      return;
2812
2813    delete static_cast<ASTUnit *>(CTUnit->TUData);
2814    disposeCXStringPool(CTUnit->StringPool);
2815    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2816    disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
2817    delete static_cast<SimpleFormatContext*>(CTUnit->FormatContext);
2818    delete CTUnit;
2819  }
2820}
2821
2822unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2823  return CXReparse_None;
2824}
2825
2826struct ReparseTranslationUnitInfo {
2827  CXTranslationUnit TU;
2828  unsigned num_unsaved_files;
2829  struct CXUnsavedFile *unsaved_files;
2830  unsigned options;
2831  int result;
2832};
2833
2834static void clang_reparseTranslationUnit_Impl(void *UserData) {
2835  ReparseTranslationUnitInfo *RTUI =
2836    static_cast<ReparseTranslationUnitInfo*>(UserData);
2837  CXTranslationUnit TU = RTUI->TU;
2838  if (!TU)
2839    return;
2840
2841  // Reset the associated diagnostics.
2842  delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2843  TU->Diagnostics = 0;
2844
2845  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2846  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2847  unsigned options = RTUI->options;
2848  (void) options;
2849  RTUI->result = 1;
2850
2851  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2852  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2853    setThreadBackgroundPriority();
2854
2855  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2856  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2857
2858  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2859    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2860
2861  // Recover resources if we crash before exiting this function.
2862  llvm::CrashRecoveryContextCleanupRegistrar<
2863    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2864
2865  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2866    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2867    const llvm::MemoryBuffer *Buffer
2868      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2869    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2870                                            Buffer));
2871  }
2872
2873  if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2874                        RemappedFiles->size()))
2875    RTUI->result = 0;
2876}
2877
2878int clang_reparseTranslationUnit(CXTranslationUnit TU,
2879                                 unsigned num_unsaved_files,
2880                                 struct CXUnsavedFile *unsaved_files,
2881                                 unsigned options) {
2882  LOG_FUNC_SECTION {
2883    *Log << TU;
2884  }
2885
2886  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2887                                      options, 0 };
2888
2889  if (getenv("LIBCLANG_NOTHREADS")) {
2890    clang_reparseTranslationUnit_Impl(&RTUI);
2891    return RTUI.result;
2892  }
2893
2894  llvm::CrashRecoveryContext CRC;
2895
2896  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2897    fprintf(stderr, "libclang: crash detected during reparsing\n");
2898    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2899    return 1;
2900  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2901    PrintLibclangResourceUsage(TU);
2902
2903  return RTUI.result;
2904}
2905
2906
2907CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2908  if (!CTUnit)
2909    return createCXString("");
2910
2911  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2912  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2913}
2914
2915CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2916  ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2917  return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
2918}
2919
2920} // end: extern "C"
2921
2922//===----------------------------------------------------------------------===//
2923// CXFile Operations.
2924//===----------------------------------------------------------------------===//
2925
2926extern "C" {
2927CXString clang_getFileName(CXFile SFile) {
2928  if (!SFile)
2929    return createCXString((const char*)NULL);
2930
2931  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2932  return createCXString(FEnt->getName());
2933}
2934
2935time_t clang_getFileTime(CXFile SFile) {
2936  if (!SFile)
2937    return 0;
2938
2939  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2940  return FEnt->getModificationTime();
2941}
2942
2943CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2944  if (!tu)
2945    return 0;
2946
2947  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2948
2949  FileManager &FMgr = CXXUnit->getFileManager();
2950  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2951}
2952
2953unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2954  if (!tu || !file)
2955    return 0;
2956
2957  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2958  FileEntry *FEnt = static_cast<FileEntry *>(file);
2959  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2960                                          .isFileMultipleIncludeGuarded(FEnt);
2961}
2962
2963int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
2964  if (!file || !outID)
2965    return 1;
2966
2967#ifdef LLVM_ON_WIN32
2968  return 1; // inodes not supported on windows.
2969#else
2970  FileEntry *FEnt = static_cast<FileEntry *>(file);
2971  outID->data[0] = FEnt->getDevice();
2972  outID->data[1] = FEnt->getInode();
2973  outID->data[2] = FEnt->getModificationTime();
2974  return 0;
2975#endif
2976}
2977
2978} // end: extern "C"
2979
2980//===----------------------------------------------------------------------===//
2981// CXCursor Operations.
2982//===----------------------------------------------------------------------===//
2983
2984static const Decl *getDeclFromExpr(const Stmt *E) {
2985  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2986    return getDeclFromExpr(CE->getSubExpr());
2987
2988  if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2989    return RefExpr->getDecl();
2990  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
2991    return ME->getMemberDecl();
2992  if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2993    return RE->getDecl();
2994  if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2995    if (PRE->isExplicitProperty())
2996      return PRE->getExplicitProperty();
2997    // It could be messaging both getter and setter as in:
2998    // ++myobj.myprop;
2999    // in which case prefer to associate the setter since it is less obvious
3000    // from inspecting the source that the setter is going to get called.
3001    if (PRE->isMessagingSetter())
3002      return PRE->getImplicitPropertySetter();
3003    return PRE->getImplicitPropertyGetter();
3004  }
3005  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3006    return getDeclFromExpr(POE->getSyntacticForm());
3007  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3008    if (Expr *Src = OVE->getSourceExpr())
3009      return getDeclFromExpr(Src);
3010
3011  if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3012    return getDeclFromExpr(CE->getCallee());
3013  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3014    if (!CE->isElidable())
3015    return CE->getConstructor();
3016  if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3017    return OME->getMethodDecl();
3018
3019  if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3020    return PE->getProtocol();
3021  if (const SubstNonTypeTemplateParmPackExpr *NTTP
3022                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3023    return NTTP->getParameterPack();
3024  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3025    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3026        isa<ParmVarDecl>(SizeOfPack->getPack()))
3027      return SizeOfPack->getPack();
3028
3029  return 0;
3030}
3031
3032static SourceLocation getLocationFromExpr(Expr *E) {
3033  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3034    return getLocationFromExpr(CE->getSubExpr());
3035
3036  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3037    return /*FIXME:*/Msg->getLeftLoc();
3038  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3039    return DRE->getLocation();
3040  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3041    return Member->getMemberLoc();
3042  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3043    return Ivar->getLocation();
3044  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3045    return SizeOfPack->getPackLoc();
3046  if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3047    return PropRef->getLocation();
3048
3049  return E->getLocStart();
3050}
3051
3052extern "C" {
3053
3054unsigned clang_visitChildren(CXCursor parent,
3055                             CXCursorVisitor visitor,
3056                             CXClientData client_data) {
3057  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3058                          /*VisitPreprocessorLast=*/false);
3059  return CursorVis.VisitChildren(parent);
3060}
3061
3062#ifndef __has_feature
3063#define __has_feature(x) 0
3064#endif
3065#if __has_feature(blocks)
3066typedef enum CXChildVisitResult
3067     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3068
3069static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3070    CXClientData client_data) {
3071  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3072  return block(cursor, parent);
3073}
3074#else
3075// If we are compiled with a compiler that doesn't have native blocks support,
3076// define and call the block manually, so the
3077typedef struct _CXChildVisitResult
3078{
3079	void *isa;
3080	int flags;
3081	int reserved;
3082	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3083                                         CXCursor);
3084} *CXCursorVisitorBlock;
3085
3086static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3087    CXClientData client_data) {
3088  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3089  return block->invoke(block, cursor, parent);
3090}
3091#endif
3092
3093
3094unsigned clang_visitChildrenWithBlock(CXCursor parent,
3095                                      CXCursorVisitorBlock block) {
3096  return clang_visitChildren(parent, visitWithBlock, block);
3097}
3098
3099static CXString getDeclSpelling(const Decl *D) {
3100  if (!D)
3101    return createCXString("");
3102
3103  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3104  if (!ND) {
3105    if (const ObjCPropertyImplDecl *PropImpl =
3106            dyn_cast<ObjCPropertyImplDecl>(D))
3107      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3108        return createCXString(Property->getIdentifier()->getName());
3109
3110    if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3111      if (Module *Mod = ImportD->getImportedModule())
3112        return createCXString(Mod->getFullModuleName());
3113
3114    return createCXString("");
3115  }
3116
3117  if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3118    return createCXString(OMD->getSelector().getAsString());
3119
3120  if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3121    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3122    // and returns different names. NamedDecl returns the class name and
3123    // ObjCCategoryImplDecl returns the category name.
3124    return createCXString(CIMP->getIdentifier()->getNameStart());
3125
3126  if (isa<UsingDirectiveDecl>(D))
3127    return createCXString("");
3128
3129  SmallString<1024> S;
3130  llvm::raw_svector_ostream os(S);
3131  ND->printName(os);
3132
3133  return createCXString(os.str());
3134}
3135
3136CXString clang_getCursorSpelling(CXCursor C) {
3137  if (clang_isTranslationUnit(C.kind))
3138    return clang_getTranslationUnitSpelling(getCursorTU(C));
3139
3140  if (clang_isReference(C.kind)) {
3141    switch (C.kind) {
3142    case CXCursor_ObjCSuperClassRef: {
3143      const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3144      return createCXString(Super->getIdentifier()->getNameStart());
3145    }
3146    case CXCursor_ObjCClassRef: {
3147      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3148      return createCXString(Class->getIdentifier()->getNameStart());
3149    }
3150    case CXCursor_ObjCProtocolRef: {
3151      const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3152      assert(OID && "getCursorSpelling(): Missing protocol decl");
3153      return createCXString(OID->getIdentifier()->getNameStart());
3154    }
3155    case CXCursor_CXXBaseSpecifier: {
3156      const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3157      return createCXString(B->getType().getAsString());
3158    }
3159    case CXCursor_TypeRef: {
3160      const TypeDecl *Type = getCursorTypeRef(C).first;
3161      assert(Type && "Missing type decl");
3162
3163      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3164                              getAsString());
3165    }
3166    case CXCursor_TemplateRef: {
3167      const TemplateDecl *Template = getCursorTemplateRef(C).first;
3168      assert(Template && "Missing template decl");
3169
3170      return createCXString(Template->getNameAsString());
3171    }
3172
3173    case CXCursor_NamespaceRef: {
3174      const NamedDecl *NS = getCursorNamespaceRef(C).first;
3175      assert(NS && "Missing namespace decl");
3176
3177      return createCXString(NS->getNameAsString());
3178    }
3179
3180    case CXCursor_MemberRef: {
3181      const FieldDecl *Field = getCursorMemberRef(C).first;
3182      assert(Field && "Missing member decl");
3183
3184      return createCXString(Field->getNameAsString());
3185    }
3186
3187    case CXCursor_LabelRef: {
3188      const LabelStmt *Label = getCursorLabelRef(C).first;
3189      assert(Label && "Missing label");
3190
3191      return createCXString(Label->getName());
3192    }
3193
3194    case CXCursor_OverloadedDeclRef: {
3195      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3196      if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3197        if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3198          return createCXString(ND->getNameAsString());
3199        return createCXString("");
3200      }
3201      if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3202        return createCXString(E->getName().getAsString());
3203      OverloadedTemplateStorage *Ovl
3204        = Storage.get<OverloadedTemplateStorage*>();
3205      if (Ovl->size() == 0)
3206        return createCXString("");
3207      return createCXString((*Ovl->begin())->getNameAsString());
3208    }
3209
3210    case CXCursor_VariableRef: {
3211      const VarDecl *Var = getCursorVariableRef(C).first;
3212      assert(Var && "Missing variable decl");
3213
3214      return createCXString(Var->getNameAsString());
3215    }
3216
3217    default:
3218      return createCXString("<not implemented>");
3219    }
3220  }
3221
3222  if (clang_isExpression(C.kind)) {
3223    const Decl *D = getDeclFromExpr(getCursorExpr(C));
3224    if (D)
3225      return getDeclSpelling(D);
3226    return createCXString("");
3227  }
3228
3229  if (clang_isStatement(C.kind)) {
3230    Stmt *S = getCursorStmt(C);
3231    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3232      return createCXString(Label->getName());
3233
3234    return createCXString("");
3235  }
3236
3237  if (C.kind == CXCursor_MacroExpansion)
3238    return createCXString(getCursorMacroExpansion(C).getName()
3239                                                           ->getNameStart());
3240
3241  if (C.kind == CXCursor_MacroDefinition)
3242    return createCXString(getCursorMacroDefinition(C)->getName()
3243                                                           ->getNameStart());
3244
3245  if (C.kind == CXCursor_InclusionDirective)
3246    return createCXString(getCursorInclusionDirective(C)->getFileName());
3247
3248  if (clang_isDeclaration(C.kind))
3249    return getDeclSpelling(getCursorDecl(C));
3250
3251  if (C.kind == CXCursor_AnnotateAttr) {
3252    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3253    return createCXString(AA->getAnnotation());
3254  }
3255
3256  if (C.kind == CXCursor_AsmLabelAttr) {
3257    AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3258    return createCXString(AA->getLabel());
3259  }
3260
3261  return createCXString("");
3262}
3263
3264CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3265                                                unsigned pieceIndex,
3266                                                unsigned options) {
3267  if (clang_Cursor_isNull(C))
3268    return clang_getNullRange();
3269
3270  ASTContext &Ctx = getCursorContext(C);
3271
3272  if (clang_isStatement(C.kind)) {
3273    Stmt *S = getCursorStmt(C);
3274    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3275      if (pieceIndex > 0)
3276        return clang_getNullRange();
3277      return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3278    }
3279
3280    return clang_getNullRange();
3281  }
3282
3283  if (C.kind == CXCursor_ObjCMessageExpr) {
3284    if (ObjCMessageExpr *
3285          ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3286      if (pieceIndex >= ME->getNumSelectorLocs())
3287        return clang_getNullRange();
3288      return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3289    }
3290  }
3291
3292  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3293      C.kind == CXCursor_ObjCClassMethodDecl) {
3294    if (const ObjCMethodDecl *
3295          MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3296      if (pieceIndex >= MD->getNumSelectorLocs())
3297        return clang_getNullRange();
3298      return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3299    }
3300  }
3301
3302  if (C.kind == CXCursor_ObjCCategoryDecl ||
3303      C.kind == CXCursor_ObjCCategoryImplDecl) {
3304    if (pieceIndex > 0)
3305      return clang_getNullRange();
3306    if (const ObjCCategoryDecl *
3307          CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3308      return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3309    if (const ObjCCategoryImplDecl *
3310          CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3311      return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3312  }
3313
3314  if (C.kind == CXCursor_ModuleImportDecl) {
3315    if (pieceIndex > 0)
3316      return clang_getNullRange();
3317    if (const ImportDecl *ImportD =
3318            dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3319      ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3320      if (!Locs.empty())
3321        return cxloc::translateSourceRange(Ctx,
3322                                         SourceRange(Locs.front(), Locs.back()));
3323    }
3324    return clang_getNullRange();
3325  }
3326
3327  // FIXME: A CXCursor_InclusionDirective should give the location of the
3328  // filename, but we don't keep track of this.
3329
3330  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3331  // but we don't keep track of this.
3332
3333  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3334  // but we don't keep track of this.
3335
3336  // Default handling, give the location of the cursor.
3337
3338  if (pieceIndex > 0)
3339    return clang_getNullRange();
3340
3341  CXSourceLocation CXLoc = clang_getCursorLocation(C);
3342  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3343  return cxloc::translateSourceRange(Ctx, Loc);
3344}
3345
3346CXString clang_getCursorDisplayName(CXCursor C) {
3347  if (!clang_isDeclaration(C.kind))
3348    return clang_getCursorSpelling(C);
3349
3350  const Decl *D = getCursorDecl(C);
3351  if (!D)
3352    return createCXString("");
3353
3354  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3355  if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3356    D = FunTmpl->getTemplatedDecl();
3357
3358  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3359    SmallString<64> Str;
3360    llvm::raw_svector_ostream OS(Str);
3361    OS << *Function;
3362    if (Function->getPrimaryTemplate())
3363      OS << "<>";
3364    OS << "(";
3365    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3366      if (I)
3367        OS << ", ";
3368      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3369    }
3370
3371    if (Function->isVariadic()) {
3372      if (Function->getNumParams())
3373        OS << ", ";
3374      OS << "...";
3375    }
3376    OS << ")";
3377    return createCXString(OS.str());
3378  }
3379
3380  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3381    SmallString<64> Str;
3382    llvm::raw_svector_ostream OS(Str);
3383    OS << *ClassTemplate;
3384    OS << "<";
3385    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3386    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3387      if (I)
3388        OS << ", ";
3389
3390      NamedDecl *Param = Params->getParam(I);
3391      if (Param->getIdentifier()) {
3392        OS << Param->getIdentifier()->getName();
3393        continue;
3394      }
3395
3396      // There is no parameter name, which makes this tricky. Try to come up
3397      // with something useful that isn't too long.
3398      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3399        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3400      else if (NonTypeTemplateParmDecl *NTTP
3401                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3402        OS << NTTP->getType().getAsString(Policy);
3403      else
3404        OS << "template<...> class";
3405    }
3406
3407    OS << ">";
3408    return createCXString(OS.str());
3409  }
3410
3411  if (const ClassTemplateSpecializationDecl *ClassSpec
3412                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3413    // If the type was explicitly written, use that.
3414    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3415      return createCXString(TSInfo->getType().getAsString(Policy));
3416
3417    SmallString<64> Str;
3418    llvm::raw_svector_ostream OS(Str);
3419    OS << *ClassSpec;
3420    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3421                                      ClassSpec->getTemplateArgs().data(),
3422                                      ClassSpec->getTemplateArgs().size(),
3423                                                                Policy);
3424    return createCXString(OS.str());
3425  }
3426
3427  return clang_getCursorSpelling(C);
3428}
3429
3430CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3431  switch (Kind) {
3432  case CXCursor_FunctionDecl:
3433      return createCXString("FunctionDecl");
3434  case CXCursor_TypedefDecl:
3435      return createCXString("TypedefDecl");
3436  case CXCursor_EnumDecl:
3437      return createCXString("EnumDecl");
3438  case CXCursor_EnumConstantDecl:
3439      return createCXString("EnumConstantDecl");
3440  case CXCursor_StructDecl:
3441      return createCXString("StructDecl");
3442  case CXCursor_UnionDecl:
3443      return createCXString("UnionDecl");
3444  case CXCursor_ClassDecl:
3445      return createCXString("ClassDecl");
3446  case CXCursor_FieldDecl:
3447      return createCXString("FieldDecl");
3448  case CXCursor_VarDecl:
3449      return createCXString("VarDecl");
3450  case CXCursor_ParmDecl:
3451      return createCXString("ParmDecl");
3452  case CXCursor_ObjCInterfaceDecl:
3453      return createCXString("ObjCInterfaceDecl");
3454  case CXCursor_ObjCCategoryDecl:
3455      return createCXString("ObjCCategoryDecl");
3456  case CXCursor_ObjCProtocolDecl:
3457      return createCXString("ObjCProtocolDecl");
3458  case CXCursor_ObjCPropertyDecl:
3459      return createCXString("ObjCPropertyDecl");
3460  case CXCursor_ObjCIvarDecl:
3461      return createCXString("ObjCIvarDecl");
3462  case CXCursor_ObjCInstanceMethodDecl:
3463      return createCXString("ObjCInstanceMethodDecl");
3464  case CXCursor_ObjCClassMethodDecl:
3465      return createCXString("ObjCClassMethodDecl");
3466  case CXCursor_ObjCImplementationDecl:
3467      return createCXString("ObjCImplementationDecl");
3468  case CXCursor_ObjCCategoryImplDecl:
3469      return createCXString("ObjCCategoryImplDecl");
3470  case CXCursor_CXXMethod:
3471      return createCXString("CXXMethod");
3472  case CXCursor_UnexposedDecl:
3473      return createCXString("UnexposedDecl");
3474  case CXCursor_ObjCSuperClassRef:
3475      return createCXString("ObjCSuperClassRef");
3476  case CXCursor_ObjCProtocolRef:
3477      return createCXString("ObjCProtocolRef");
3478  case CXCursor_ObjCClassRef:
3479      return createCXString("ObjCClassRef");
3480  case CXCursor_TypeRef:
3481      return createCXString("TypeRef");
3482  case CXCursor_TemplateRef:
3483      return createCXString("TemplateRef");
3484  case CXCursor_NamespaceRef:
3485    return createCXString("NamespaceRef");
3486  case CXCursor_MemberRef:
3487    return createCXString("MemberRef");
3488  case CXCursor_LabelRef:
3489    return createCXString("LabelRef");
3490  case CXCursor_OverloadedDeclRef:
3491    return createCXString("OverloadedDeclRef");
3492  case CXCursor_VariableRef:
3493    return createCXString("VariableRef");
3494  case CXCursor_IntegerLiteral:
3495      return createCXString("IntegerLiteral");
3496  case CXCursor_FloatingLiteral:
3497      return createCXString("FloatingLiteral");
3498  case CXCursor_ImaginaryLiteral:
3499      return createCXString("ImaginaryLiteral");
3500  case CXCursor_StringLiteral:
3501      return createCXString("StringLiteral");
3502  case CXCursor_CharacterLiteral:
3503      return createCXString("CharacterLiteral");
3504  case CXCursor_ParenExpr:
3505      return createCXString("ParenExpr");
3506  case CXCursor_UnaryOperator:
3507      return createCXString("UnaryOperator");
3508  case CXCursor_ArraySubscriptExpr:
3509      return createCXString("ArraySubscriptExpr");
3510  case CXCursor_BinaryOperator:
3511      return createCXString("BinaryOperator");
3512  case CXCursor_CompoundAssignOperator:
3513      return createCXString("CompoundAssignOperator");
3514  case CXCursor_ConditionalOperator:
3515      return createCXString("ConditionalOperator");
3516  case CXCursor_CStyleCastExpr:
3517      return createCXString("CStyleCastExpr");
3518  case CXCursor_CompoundLiteralExpr:
3519      return createCXString("CompoundLiteralExpr");
3520  case CXCursor_InitListExpr:
3521      return createCXString("InitListExpr");
3522  case CXCursor_AddrLabelExpr:
3523      return createCXString("AddrLabelExpr");
3524  case CXCursor_StmtExpr:
3525      return createCXString("StmtExpr");
3526  case CXCursor_GenericSelectionExpr:
3527      return createCXString("GenericSelectionExpr");
3528  case CXCursor_GNUNullExpr:
3529      return createCXString("GNUNullExpr");
3530  case CXCursor_CXXStaticCastExpr:
3531      return createCXString("CXXStaticCastExpr");
3532  case CXCursor_CXXDynamicCastExpr:
3533      return createCXString("CXXDynamicCastExpr");
3534  case CXCursor_CXXReinterpretCastExpr:
3535      return createCXString("CXXReinterpretCastExpr");
3536  case CXCursor_CXXConstCastExpr:
3537      return createCXString("CXXConstCastExpr");
3538  case CXCursor_CXXFunctionalCastExpr:
3539      return createCXString("CXXFunctionalCastExpr");
3540  case CXCursor_CXXTypeidExpr:
3541      return createCXString("CXXTypeidExpr");
3542  case CXCursor_CXXBoolLiteralExpr:
3543      return createCXString("CXXBoolLiteralExpr");
3544  case CXCursor_CXXNullPtrLiteralExpr:
3545      return createCXString("CXXNullPtrLiteralExpr");
3546  case CXCursor_CXXThisExpr:
3547      return createCXString("CXXThisExpr");
3548  case CXCursor_CXXThrowExpr:
3549      return createCXString("CXXThrowExpr");
3550  case CXCursor_CXXNewExpr:
3551      return createCXString("CXXNewExpr");
3552  case CXCursor_CXXDeleteExpr:
3553      return createCXString("CXXDeleteExpr");
3554  case CXCursor_UnaryExpr:
3555      return createCXString("UnaryExpr");
3556  case CXCursor_ObjCStringLiteral:
3557      return createCXString("ObjCStringLiteral");
3558  case CXCursor_ObjCBoolLiteralExpr:
3559      return createCXString("ObjCBoolLiteralExpr");
3560  case CXCursor_ObjCEncodeExpr:
3561      return createCXString("ObjCEncodeExpr");
3562  case CXCursor_ObjCSelectorExpr:
3563      return createCXString("ObjCSelectorExpr");
3564  case CXCursor_ObjCProtocolExpr:
3565      return createCXString("ObjCProtocolExpr");
3566  case CXCursor_ObjCBridgedCastExpr:
3567      return createCXString("ObjCBridgedCastExpr");
3568  case CXCursor_BlockExpr:
3569      return createCXString("BlockExpr");
3570  case CXCursor_PackExpansionExpr:
3571      return createCXString("PackExpansionExpr");
3572  case CXCursor_SizeOfPackExpr:
3573      return createCXString("SizeOfPackExpr");
3574  case CXCursor_LambdaExpr:
3575    return createCXString("LambdaExpr");
3576  case CXCursor_UnexposedExpr:
3577      return createCXString("UnexposedExpr");
3578  case CXCursor_DeclRefExpr:
3579      return createCXString("DeclRefExpr");
3580  case CXCursor_MemberRefExpr:
3581      return createCXString("MemberRefExpr");
3582  case CXCursor_CallExpr:
3583      return createCXString("CallExpr");
3584  case CXCursor_ObjCMessageExpr:
3585      return createCXString("ObjCMessageExpr");
3586  case CXCursor_UnexposedStmt:
3587      return createCXString("UnexposedStmt");
3588  case CXCursor_DeclStmt:
3589      return createCXString("DeclStmt");
3590  case CXCursor_LabelStmt:
3591      return createCXString("LabelStmt");
3592  case CXCursor_CompoundStmt:
3593      return createCXString("CompoundStmt");
3594  case CXCursor_CaseStmt:
3595      return createCXString("CaseStmt");
3596  case CXCursor_DefaultStmt:
3597      return createCXString("DefaultStmt");
3598  case CXCursor_IfStmt:
3599      return createCXString("IfStmt");
3600  case CXCursor_SwitchStmt:
3601      return createCXString("SwitchStmt");
3602  case CXCursor_WhileStmt:
3603      return createCXString("WhileStmt");
3604  case CXCursor_DoStmt:
3605      return createCXString("DoStmt");
3606  case CXCursor_ForStmt:
3607      return createCXString("ForStmt");
3608  case CXCursor_GotoStmt:
3609      return createCXString("GotoStmt");
3610  case CXCursor_IndirectGotoStmt:
3611      return createCXString("IndirectGotoStmt");
3612  case CXCursor_ContinueStmt:
3613      return createCXString("ContinueStmt");
3614  case CXCursor_BreakStmt:
3615      return createCXString("BreakStmt");
3616  case CXCursor_ReturnStmt:
3617      return createCXString("ReturnStmt");
3618  case CXCursor_GCCAsmStmt:
3619      return createCXString("GCCAsmStmt");
3620  case CXCursor_MSAsmStmt:
3621      return createCXString("MSAsmStmt");
3622  case CXCursor_ObjCAtTryStmt:
3623      return createCXString("ObjCAtTryStmt");
3624  case CXCursor_ObjCAtCatchStmt:
3625      return createCXString("ObjCAtCatchStmt");
3626  case CXCursor_ObjCAtFinallyStmt:
3627      return createCXString("ObjCAtFinallyStmt");
3628  case CXCursor_ObjCAtThrowStmt:
3629      return createCXString("ObjCAtThrowStmt");
3630  case CXCursor_ObjCAtSynchronizedStmt:
3631      return createCXString("ObjCAtSynchronizedStmt");
3632  case CXCursor_ObjCAutoreleasePoolStmt:
3633      return createCXString("ObjCAutoreleasePoolStmt");
3634  case CXCursor_ObjCForCollectionStmt:
3635      return createCXString("ObjCForCollectionStmt");
3636  case CXCursor_CXXCatchStmt:
3637      return createCXString("CXXCatchStmt");
3638  case CXCursor_CXXTryStmt:
3639      return createCXString("CXXTryStmt");
3640  case CXCursor_CXXForRangeStmt:
3641      return createCXString("CXXForRangeStmt");
3642  case CXCursor_SEHTryStmt:
3643      return createCXString("SEHTryStmt");
3644  case CXCursor_SEHExceptStmt:
3645      return createCXString("SEHExceptStmt");
3646  case CXCursor_SEHFinallyStmt:
3647      return createCXString("SEHFinallyStmt");
3648  case CXCursor_NullStmt:
3649      return createCXString("NullStmt");
3650  case CXCursor_InvalidFile:
3651      return createCXString("InvalidFile");
3652  case CXCursor_InvalidCode:
3653    return createCXString("InvalidCode");
3654  case CXCursor_NoDeclFound:
3655      return createCXString("NoDeclFound");
3656  case CXCursor_NotImplemented:
3657      return createCXString("NotImplemented");
3658  case CXCursor_TranslationUnit:
3659      return createCXString("TranslationUnit");
3660  case CXCursor_UnexposedAttr:
3661      return createCXString("UnexposedAttr");
3662  case CXCursor_IBActionAttr:
3663      return createCXString("attribute(ibaction)");
3664  case CXCursor_IBOutletAttr:
3665     return createCXString("attribute(iboutlet)");
3666  case CXCursor_IBOutletCollectionAttr:
3667      return createCXString("attribute(iboutletcollection)");
3668  case CXCursor_CXXFinalAttr:
3669      return createCXString("attribute(final)");
3670  case CXCursor_CXXOverrideAttr:
3671      return createCXString("attribute(override)");
3672  case CXCursor_AnnotateAttr:
3673    return createCXString("attribute(annotate)");
3674  case CXCursor_AsmLabelAttr:
3675    return createCXString("asm label");
3676  case CXCursor_PreprocessingDirective:
3677    return createCXString("preprocessing directive");
3678  case CXCursor_MacroDefinition:
3679    return createCXString("macro definition");
3680  case CXCursor_MacroExpansion:
3681    return createCXString("macro expansion");
3682  case CXCursor_InclusionDirective:
3683    return createCXString("inclusion directive");
3684  case CXCursor_Namespace:
3685    return createCXString("Namespace");
3686  case CXCursor_LinkageSpec:
3687    return createCXString("LinkageSpec");
3688  case CXCursor_CXXBaseSpecifier:
3689    return createCXString("C++ base class specifier");
3690  case CXCursor_Constructor:
3691    return createCXString("CXXConstructor");
3692  case CXCursor_Destructor:
3693    return createCXString("CXXDestructor");
3694  case CXCursor_ConversionFunction:
3695    return createCXString("CXXConversion");
3696  case CXCursor_TemplateTypeParameter:
3697    return createCXString("TemplateTypeParameter");
3698  case CXCursor_NonTypeTemplateParameter:
3699    return createCXString("NonTypeTemplateParameter");
3700  case CXCursor_TemplateTemplateParameter:
3701    return createCXString("TemplateTemplateParameter");
3702  case CXCursor_FunctionTemplate:
3703    return createCXString("FunctionTemplate");
3704  case CXCursor_ClassTemplate:
3705    return createCXString("ClassTemplate");
3706  case CXCursor_ClassTemplatePartialSpecialization:
3707    return createCXString("ClassTemplatePartialSpecialization");
3708  case CXCursor_NamespaceAlias:
3709    return createCXString("NamespaceAlias");
3710  case CXCursor_UsingDirective:
3711    return createCXString("UsingDirective");
3712  case CXCursor_UsingDeclaration:
3713    return createCXString("UsingDeclaration");
3714  case CXCursor_TypeAliasDecl:
3715    return createCXString("TypeAliasDecl");
3716  case CXCursor_ObjCSynthesizeDecl:
3717    return createCXString("ObjCSynthesizeDecl");
3718  case CXCursor_ObjCDynamicDecl:
3719    return createCXString("ObjCDynamicDecl");
3720  case CXCursor_CXXAccessSpecifier:
3721    return createCXString("CXXAccessSpecifier");
3722  case CXCursor_ModuleImportDecl:
3723    return createCXString("ModuleImport");
3724  }
3725
3726  llvm_unreachable("Unhandled CXCursorKind");
3727}
3728
3729struct GetCursorData {
3730  SourceLocation TokenBeginLoc;
3731  bool PointsAtMacroArgExpansion;
3732  bool VisitedObjCPropertyImplDecl;
3733  SourceLocation VisitedDeclaratorDeclStartLoc;
3734  CXCursor &BestCursor;
3735
3736  GetCursorData(SourceManager &SM,
3737                SourceLocation tokenBegin, CXCursor &outputCursor)
3738    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3739    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3740    VisitedObjCPropertyImplDecl = false;
3741  }
3742};
3743
3744static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3745                                                CXCursor parent,
3746                                                CXClientData client_data) {
3747  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3748  CXCursor *BestCursor = &Data->BestCursor;
3749
3750  // If we point inside a macro argument we should provide info of what the
3751  // token is so use the actual cursor, don't replace it with a macro expansion
3752  // cursor.
3753  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3754    return CXChildVisit_Recurse;
3755
3756  if (clang_isDeclaration(cursor.kind)) {
3757    // Avoid having the implicit methods override the property decls.
3758    if (const ObjCMethodDecl *MD
3759          = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
3760      if (MD->isImplicit())
3761        return CXChildVisit_Break;
3762
3763    } else if (const ObjCInterfaceDecl *ID
3764                 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3765      // Check that when we have multiple @class references in the same line,
3766      // that later ones do not override the previous ones.
3767      // If we have:
3768      // @class Foo, Bar;
3769      // source ranges for both start at '@', so 'Bar' will end up overriding
3770      // 'Foo' even though the cursor location was at 'Foo'.
3771      if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3772          BestCursor->kind == CXCursor_ObjCClassRef)
3773        if (const ObjCInterfaceDecl *PrevID
3774             = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3775         if (PrevID != ID &&
3776             !PrevID->isThisDeclarationADefinition() &&
3777             !ID->isThisDeclarationADefinition())
3778           return CXChildVisit_Break;
3779        }
3780
3781    } else if (const DeclaratorDecl *DD
3782                    = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3783      SourceLocation StartLoc = DD->getSourceRange().getBegin();
3784      // Check that when we have multiple declarators in the same line,
3785      // that later ones do not override the previous ones.
3786      // If we have:
3787      // int Foo, Bar;
3788      // source ranges for both start at 'int', so 'Bar' will end up overriding
3789      // 'Foo' even though the cursor location was at 'Foo'.
3790      if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3791        return CXChildVisit_Break;
3792      Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3793
3794    } else if (const ObjCPropertyImplDecl *PropImp
3795              = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3796      (void)PropImp;
3797      // Check that when we have multiple @synthesize in the same line,
3798      // that later ones do not override the previous ones.
3799      // If we have:
3800      // @synthesize Foo, Bar;
3801      // source ranges for both start at '@', so 'Bar' will end up overriding
3802      // 'Foo' even though the cursor location was at 'Foo'.
3803      if (Data->VisitedObjCPropertyImplDecl)
3804        return CXChildVisit_Break;
3805      Data->VisitedObjCPropertyImplDecl = true;
3806    }
3807  }
3808
3809  if (clang_isExpression(cursor.kind) &&
3810      clang_isDeclaration(BestCursor->kind)) {
3811    if (const Decl *D = getCursorDecl(*BestCursor)) {
3812      // Avoid having the cursor of an expression replace the declaration cursor
3813      // when the expression source range overlaps the declaration range.
3814      // This can happen for C++ constructor expressions whose range generally
3815      // include the variable declaration, e.g.:
3816      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3817      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3818          D->getLocation() == Data->TokenBeginLoc)
3819        return CXChildVisit_Break;
3820    }
3821  }
3822
3823  // If our current best cursor is the construction of a temporary object,
3824  // don't replace that cursor with a type reference, because we want
3825  // clang_getCursor() to point at the constructor.
3826  if (clang_isExpression(BestCursor->kind) &&
3827      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3828      cursor.kind == CXCursor_TypeRef) {
3829    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3830    // as having the actual point on the type reference.
3831    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3832    return CXChildVisit_Recurse;
3833  }
3834
3835  *BestCursor = cursor;
3836  return CXChildVisit_Recurse;
3837}
3838
3839CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3840  if (!TU)
3841    return clang_getNullCursor();
3842
3843  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3844  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3845
3846  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3847  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3848
3849  LOG_FUNC_SECTION {
3850    CXFile SearchFile;
3851    unsigned SearchLine, SearchColumn;
3852    CXFile ResultFile;
3853    unsigned ResultLine, ResultColumn;
3854    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3855    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3856    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3857
3858    clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3859    clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
3860                               &ResultColumn, 0);
3861    SearchFileName = clang_getFileName(SearchFile);
3862    ResultFileName = clang_getFileName(ResultFile);
3863    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3864    USR = clang_getCursorUSR(Result);
3865    *Log << llvm::format("(%s:%d:%d) = %s",
3866                   clang_getCString(SearchFileName), SearchLine, SearchColumn,
3867                   clang_getCString(KindSpelling))
3868        << llvm::format("(%s:%d:%d):%s%s",
3869                     clang_getCString(ResultFileName), ResultLine, ResultColumn,
3870                     clang_getCString(USR), IsDef);
3871    clang_disposeString(SearchFileName);
3872    clang_disposeString(ResultFileName);
3873    clang_disposeString(KindSpelling);
3874    clang_disposeString(USR);
3875
3876    CXCursor Definition = clang_getCursorDefinition(Result);
3877    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3878      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3879      CXString DefinitionKindSpelling
3880                                = clang_getCursorKindSpelling(Definition.kind);
3881      CXFile DefinitionFile;
3882      unsigned DefinitionLine, DefinitionColumn;
3883      clang_getFileLocation(DefinitionLoc, &DefinitionFile,
3884                                 &DefinitionLine, &DefinitionColumn, 0);
3885      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3886      *Log << llvm::format("  -> %s(%s:%d:%d)",
3887                     clang_getCString(DefinitionKindSpelling),
3888                     clang_getCString(DefinitionFileName),
3889                     DefinitionLine, DefinitionColumn);
3890      clang_disposeString(DefinitionFileName);
3891      clang_disposeString(DefinitionKindSpelling);
3892    }
3893  }
3894
3895  return Result;
3896}
3897
3898CXCursor clang_getNullCursor(void) {
3899  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3900}
3901
3902unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3903  // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
3904  // can't set consistently. For example, when visiting a DeclStmt we will set
3905  // it but we don't set it on the result of clang_getCursorDefinition for
3906  // a reference of the same declaration.
3907  // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
3908  // when visiting a DeclStmt currently, the AST should be enhanced to be able
3909  // to provide that kind of info.
3910  if (clang_isDeclaration(X.kind))
3911    X.data[1] = 0;
3912  if (clang_isDeclaration(Y.kind))
3913    Y.data[1] = 0;
3914
3915  return X == Y;
3916}
3917
3918unsigned clang_hashCursor(CXCursor C) {
3919  unsigned Index = 0;
3920  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3921    Index = 1;
3922
3923  return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
3924                                        std::make_pair(C.kind, C.data[Index]));
3925}
3926
3927unsigned clang_isInvalid(enum CXCursorKind K) {
3928  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3929}
3930
3931unsigned clang_isDeclaration(enum CXCursorKind K) {
3932  return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3933         (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
3934}
3935
3936unsigned clang_isReference(enum CXCursorKind K) {
3937  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3938}
3939
3940unsigned clang_isExpression(enum CXCursorKind K) {
3941  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3942}
3943
3944unsigned clang_isStatement(enum CXCursorKind K) {
3945  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3946}
3947
3948unsigned clang_isAttribute(enum CXCursorKind K) {
3949    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3950}
3951
3952unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3953  return K == CXCursor_TranslationUnit;
3954}
3955
3956unsigned clang_isPreprocessing(enum CXCursorKind K) {
3957  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3958}
3959
3960unsigned clang_isUnexposed(enum CXCursorKind K) {
3961  switch (K) {
3962    case CXCursor_UnexposedDecl:
3963    case CXCursor_UnexposedExpr:
3964    case CXCursor_UnexposedStmt:
3965    case CXCursor_UnexposedAttr:
3966      return true;
3967    default:
3968      return false;
3969  }
3970}
3971
3972CXCursorKind clang_getCursorKind(CXCursor C) {
3973  return C.kind;
3974}
3975
3976CXSourceLocation clang_getCursorLocation(CXCursor C) {
3977  if (clang_isReference(C.kind)) {
3978    switch (C.kind) {
3979    case CXCursor_ObjCSuperClassRef: {
3980      std::pair<const ObjCInterfaceDecl *, SourceLocation> P
3981        = getCursorObjCSuperClassRef(C);
3982      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3983    }
3984
3985    case CXCursor_ObjCProtocolRef: {
3986      std::pair<const ObjCProtocolDecl *, SourceLocation> P
3987        = getCursorObjCProtocolRef(C);
3988      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3989    }
3990
3991    case CXCursor_ObjCClassRef: {
3992      std::pair<const ObjCInterfaceDecl *, SourceLocation> P
3993        = getCursorObjCClassRef(C);
3994      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3995    }
3996
3997    case CXCursor_TypeRef: {
3998      std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3999      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4000    }
4001
4002    case CXCursor_TemplateRef: {
4003      std::pair<const TemplateDecl *, SourceLocation> P =
4004          getCursorTemplateRef(C);
4005      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4006    }
4007
4008    case CXCursor_NamespaceRef: {
4009      std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
4010      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4011    }
4012
4013    case CXCursor_MemberRef: {
4014      std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4015      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4016    }
4017
4018    case CXCursor_VariableRef: {
4019      std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4020      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4021    }
4022
4023    case CXCursor_CXXBaseSpecifier: {
4024      const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4025      if (!BaseSpec)
4026        return clang_getNullLocation();
4027
4028      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4029        return cxloc::translateSourceLocation(getCursorContext(C),
4030                                            TSInfo->getTypeLoc().getBeginLoc());
4031
4032      return cxloc::translateSourceLocation(getCursorContext(C),
4033                                        BaseSpec->getLocStart());
4034    }
4035
4036    case CXCursor_LabelRef: {
4037      std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4038      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4039    }
4040
4041    case CXCursor_OverloadedDeclRef:
4042      return cxloc::translateSourceLocation(getCursorContext(C),
4043                                          getCursorOverloadedDeclRef(C).second);
4044
4045    default:
4046      // FIXME: Need a way to enumerate all non-reference cases.
4047      llvm_unreachable("Missed a reference kind");
4048    }
4049  }
4050
4051  if (clang_isExpression(C.kind))
4052    return cxloc::translateSourceLocation(getCursorContext(C),
4053                                   getLocationFromExpr(getCursorExpr(C)));
4054
4055  if (clang_isStatement(C.kind))
4056    return cxloc::translateSourceLocation(getCursorContext(C),
4057                                          getCursorStmt(C)->getLocStart());
4058
4059  if (C.kind == CXCursor_PreprocessingDirective) {
4060    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4061    return cxloc::translateSourceLocation(getCursorContext(C), L);
4062  }
4063
4064  if (C.kind == CXCursor_MacroExpansion) {
4065    SourceLocation L
4066      = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4067    return cxloc::translateSourceLocation(getCursorContext(C), L);
4068  }
4069
4070  if (C.kind == CXCursor_MacroDefinition) {
4071    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4072    return cxloc::translateSourceLocation(getCursorContext(C), L);
4073  }
4074
4075  if (C.kind == CXCursor_InclusionDirective) {
4076    SourceLocation L
4077      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4078    return cxloc::translateSourceLocation(getCursorContext(C), L);
4079  }
4080
4081  if (!clang_isDeclaration(C.kind))
4082    return clang_getNullLocation();
4083
4084  const Decl *D = getCursorDecl(C);
4085  if (!D)
4086    return clang_getNullLocation();
4087
4088  SourceLocation Loc = D->getLocation();
4089  // FIXME: Multiple variables declared in a single declaration
4090  // currently lack the information needed to correctly determine their
4091  // ranges when accounting for the type-specifier.  We use context
4092  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4093  // and if so, whether it is the first decl.
4094  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4095    if (!cxcursor::isFirstInDeclGroup(C))
4096      Loc = VD->getLocation();
4097  }
4098
4099  // For ObjC methods, give the start location of the method name.
4100  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4101    Loc = MD->getSelectorStartLoc();
4102
4103  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4104}
4105
4106} // end extern "C"
4107
4108CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4109  assert(TU);
4110
4111  // Guard against an invalid SourceLocation, or we may assert in one
4112  // of the following calls.
4113  if (SLoc.isInvalid())
4114    return clang_getNullCursor();
4115
4116  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4117
4118  // Translate the given source location to make it point at the beginning of
4119  // the token under the cursor.
4120  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4121                                    CXXUnit->getASTContext().getLangOpts());
4122
4123  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4124  if (SLoc.isValid()) {
4125    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4126    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4127                            /*VisitPreprocessorLast=*/true,
4128                            /*VisitIncludedEntities=*/false,
4129                            SourceLocation(SLoc));
4130    CursorVis.visitFileRegion();
4131  }
4132
4133  return Result;
4134}
4135
4136static SourceRange getRawCursorExtent(CXCursor C) {
4137  if (clang_isReference(C.kind)) {
4138    switch (C.kind) {
4139    case CXCursor_ObjCSuperClassRef:
4140      return  getCursorObjCSuperClassRef(C).second;
4141
4142    case CXCursor_ObjCProtocolRef:
4143      return getCursorObjCProtocolRef(C).second;
4144
4145    case CXCursor_ObjCClassRef:
4146      return getCursorObjCClassRef(C).second;
4147
4148    case CXCursor_TypeRef:
4149      return getCursorTypeRef(C).second;
4150
4151    case CXCursor_TemplateRef:
4152      return getCursorTemplateRef(C).second;
4153
4154    case CXCursor_NamespaceRef:
4155      return getCursorNamespaceRef(C).second;
4156
4157    case CXCursor_MemberRef:
4158      return getCursorMemberRef(C).second;
4159
4160    case CXCursor_CXXBaseSpecifier:
4161      return getCursorCXXBaseSpecifier(C)->getSourceRange();
4162
4163    case CXCursor_LabelRef:
4164      return getCursorLabelRef(C).second;
4165
4166    case CXCursor_OverloadedDeclRef:
4167      return getCursorOverloadedDeclRef(C).second;
4168
4169    case CXCursor_VariableRef:
4170      return getCursorVariableRef(C).second;
4171
4172    default:
4173      // FIXME: Need a way to enumerate all non-reference cases.
4174      llvm_unreachable("Missed a reference kind");
4175    }
4176  }
4177
4178  if (clang_isExpression(C.kind))
4179    return getCursorExpr(C)->getSourceRange();
4180
4181  if (clang_isStatement(C.kind))
4182    return getCursorStmt(C)->getSourceRange();
4183
4184  if (clang_isAttribute(C.kind))
4185    return getCursorAttr(C)->getRange();
4186
4187  if (C.kind == CXCursor_PreprocessingDirective)
4188    return cxcursor::getCursorPreprocessingDirective(C);
4189
4190  if (C.kind == CXCursor_MacroExpansion) {
4191    ASTUnit *TU = getCursorASTUnit(C);
4192    SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4193    return TU->mapRangeFromPreamble(Range);
4194  }
4195
4196  if (C.kind == CXCursor_MacroDefinition) {
4197    ASTUnit *TU = getCursorASTUnit(C);
4198    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4199    return TU->mapRangeFromPreamble(Range);
4200  }
4201
4202  if (C.kind == CXCursor_InclusionDirective) {
4203    ASTUnit *TU = getCursorASTUnit(C);
4204    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4205    return TU->mapRangeFromPreamble(Range);
4206  }
4207
4208  if (C.kind == CXCursor_TranslationUnit) {
4209    ASTUnit *TU = getCursorASTUnit(C);
4210    FileID MainID = TU->getSourceManager().getMainFileID();
4211    SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4212    SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4213    return SourceRange(Start, End);
4214  }
4215
4216  if (clang_isDeclaration(C.kind)) {
4217    const Decl *D = cxcursor::getCursorDecl(C);
4218    if (!D)
4219      return SourceRange();
4220
4221    SourceRange R = D->getSourceRange();
4222    // FIXME: Multiple variables declared in a single declaration
4223    // currently lack the information needed to correctly determine their
4224    // ranges when accounting for the type-specifier.  We use context
4225    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4226    // and if so, whether it is the first decl.
4227    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4228      if (!cxcursor::isFirstInDeclGroup(C))
4229        R.setBegin(VD->getLocation());
4230    }
4231    return R;
4232  }
4233  return SourceRange();
4234}
4235
4236/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4237/// the decl-specifier-seq for declarations.
4238static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4239  if (clang_isDeclaration(C.kind)) {
4240    const Decl *D = cxcursor::getCursorDecl(C);
4241    if (!D)
4242      return SourceRange();
4243
4244    SourceRange R = D->getSourceRange();
4245
4246    // Adjust the start of the location for declarations preceded by
4247    // declaration specifiers.
4248    SourceLocation StartLoc;
4249    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4250      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4251        StartLoc = TI->getTypeLoc().getLocStart();
4252    } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4253      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4254        StartLoc = TI->getTypeLoc().getLocStart();
4255    }
4256
4257    if (StartLoc.isValid() && R.getBegin().isValid() &&
4258        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4259      R.setBegin(StartLoc);
4260
4261    // FIXME: Multiple variables declared in a single declaration
4262    // currently lack the information needed to correctly determine their
4263    // ranges when accounting for the type-specifier.  We use context
4264    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4265    // and if so, whether it is the first decl.
4266    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4267      if (!cxcursor::isFirstInDeclGroup(C))
4268        R.setBegin(VD->getLocation());
4269    }
4270
4271    return R;
4272  }
4273
4274  return getRawCursorExtent(C);
4275}
4276
4277extern "C" {
4278
4279CXSourceRange clang_getCursorExtent(CXCursor C) {
4280  SourceRange R = getRawCursorExtent(C);
4281  if (R.isInvalid())
4282    return clang_getNullRange();
4283
4284  return cxloc::translateSourceRange(getCursorContext(C), R);
4285}
4286
4287CXCursor clang_getCursorReferenced(CXCursor C) {
4288  if (clang_isInvalid(C.kind))
4289    return clang_getNullCursor();
4290
4291  CXTranslationUnit tu = getCursorTU(C);
4292  if (clang_isDeclaration(C.kind)) {
4293    const Decl *D = getCursorDecl(C);
4294    if (!D)
4295      return clang_getNullCursor();
4296    if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4297      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4298    if (const ObjCPropertyImplDecl *PropImpl =
4299            dyn_cast<ObjCPropertyImplDecl>(D))
4300      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4301        return MakeCXCursor(Property, tu);
4302
4303    return C;
4304  }
4305
4306  if (clang_isExpression(C.kind)) {
4307    const Expr *E = getCursorExpr(C);
4308    const Decl *D = getDeclFromExpr(E);
4309    if (D) {
4310      CXCursor declCursor = MakeCXCursor(D, tu);
4311      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4312                                               declCursor);
4313      return declCursor;
4314    }
4315
4316    if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4317      return MakeCursorOverloadedDeclRef(Ovl, tu);
4318
4319    return clang_getNullCursor();
4320  }
4321
4322  if (clang_isStatement(C.kind)) {
4323    Stmt *S = getCursorStmt(C);
4324    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4325      if (LabelDecl *label = Goto->getLabel())
4326        if (LabelStmt *labelS = label->getStmt())
4327        return MakeCXCursor(labelS, getCursorDecl(C), tu);
4328
4329    return clang_getNullCursor();
4330  }
4331
4332  if (C.kind == CXCursor_MacroExpansion) {
4333    if (const MacroDefinition *Def = getCursorMacroExpansion(C).getDefinition())
4334      return MakeMacroDefinitionCursor(Def, tu);
4335  }
4336
4337  if (!clang_isReference(C.kind))
4338    return clang_getNullCursor();
4339
4340  switch (C.kind) {
4341    case CXCursor_ObjCSuperClassRef:
4342      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4343
4344    case CXCursor_ObjCProtocolRef: {
4345      const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4346      if (const ObjCProtocolDecl *Def = Prot->getDefinition())
4347        return MakeCXCursor(Def, tu);
4348
4349      return MakeCXCursor(Prot, tu);
4350    }
4351
4352    case CXCursor_ObjCClassRef: {
4353      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4354      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
4355        return MakeCXCursor(Def, tu);
4356
4357      return MakeCXCursor(Class, tu);
4358    }
4359
4360    case CXCursor_TypeRef:
4361      return MakeCXCursor(getCursorTypeRef(C).first, tu );
4362
4363    case CXCursor_TemplateRef:
4364      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4365
4366    case CXCursor_NamespaceRef:
4367      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4368
4369    case CXCursor_MemberRef:
4370      return MakeCXCursor(getCursorMemberRef(C).first, tu );
4371
4372    case CXCursor_CXXBaseSpecifier: {
4373      const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4374      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4375                                                         tu ));
4376    }
4377
4378    case CXCursor_LabelRef:
4379      // FIXME: We end up faking the "parent" declaration here because we
4380      // don't want to make CXCursor larger.
4381      return MakeCXCursor(getCursorLabelRef(C).first,
4382               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4383                          .getTranslationUnitDecl(),
4384                          tu);
4385
4386    case CXCursor_OverloadedDeclRef:
4387      return C;
4388
4389    case CXCursor_VariableRef:
4390      return MakeCXCursor(getCursorVariableRef(C).first, tu);
4391
4392    default:
4393      // We would prefer to enumerate all non-reference cursor kinds here.
4394      llvm_unreachable("Unhandled reference cursor kind");
4395  }
4396}
4397
4398CXCursor clang_getCursorDefinition(CXCursor C) {
4399  if (clang_isInvalid(C.kind))
4400    return clang_getNullCursor();
4401
4402  CXTranslationUnit TU = getCursorTU(C);
4403
4404  bool WasReference = false;
4405  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4406    C = clang_getCursorReferenced(C);
4407    WasReference = true;
4408  }
4409
4410  if (C.kind == CXCursor_MacroExpansion)
4411    return clang_getCursorReferenced(C);
4412
4413  if (!clang_isDeclaration(C.kind))
4414    return clang_getNullCursor();
4415
4416  const Decl *D = getCursorDecl(C);
4417  if (!D)
4418    return clang_getNullCursor();
4419
4420  switch (D->getKind()) {
4421  // Declaration kinds that don't really separate the notions of
4422  // declaration and definition.
4423  case Decl::Namespace:
4424  case Decl::Typedef:
4425  case Decl::TypeAlias:
4426  case Decl::TypeAliasTemplate:
4427  case Decl::TemplateTypeParm:
4428  case Decl::EnumConstant:
4429  case Decl::Field:
4430  case Decl::IndirectField:
4431  case Decl::ObjCIvar:
4432  case Decl::ObjCAtDefsField:
4433  case Decl::ImplicitParam:
4434  case Decl::ParmVar:
4435  case Decl::NonTypeTemplateParm:
4436  case Decl::TemplateTemplateParm:
4437  case Decl::ObjCCategoryImpl:
4438  case Decl::ObjCImplementation:
4439  case Decl::AccessSpec:
4440  case Decl::LinkageSpec:
4441  case Decl::ObjCPropertyImpl:
4442  case Decl::FileScopeAsm:
4443  case Decl::StaticAssert:
4444  case Decl::Block:
4445  case Decl::Label:  // FIXME: Is this right??
4446  case Decl::ClassScopeFunctionSpecialization:
4447  case Decl::Import:
4448    return C;
4449
4450  // Declaration kinds that don't make any sense here, but are
4451  // nonetheless harmless.
4452  case Decl::TranslationUnit:
4453    break;
4454
4455  // Declaration kinds for which the definition is not resolvable.
4456  case Decl::UnresolvedUsingTypename:
4457  case Decl::UnresolvedUsingValue:
4458    break;
4459
4460  case Decl::UsingDirective:
4461    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4462                        TU);
4463
4464  case Decl::NamespaceAlias:
4465    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4466
4467  case Decl::Enum:
4468  case Decl::Record:
4469  case Decl::CXXRecord:
4470  case Decl::ClassTemplateSpecialization:
4471  case Decl::ClassTemplatePartialSpecialization:
4472    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4473      return MakeCXCursor(Def, TU);
4474    return clang_getNullCursor();
4475
4476  case Decl::Function:
4477  case Decl::CXXMethod:
4478  case Decl::CXXConstructor:
4479  case Decl::CXXDestructor:
4480  case Decl::CXXConversion: {
4481    const FunctionDecl *Def = 0;
4482    if (cast<FunctionDecl>(D)->getBody(Def))
4483      return MakeCXCursor(Def, TU);
4484    return clang_getNullCursor();
4485  }
4486
4487  case Decl::Var: {
4488    // Ask the variable if it has a definition.
4489    if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4490      return MakeCXCursor(Def, TU);
4491    return clang_getNullCursor();
4492  }
4493
4494  case Decl::FunctionTemplate: {
4495    const FunctionDecl *Def = 0;
4496    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4497      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4498    return clang_getNullCursor();
4499  }
4500
4501  case Decl::ClassTemplate: {
4502    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4503                                                            ->getDefinition())
4504      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4505                          TU);
4506    return clang_getNullCursor();
4507  }
4508
4509  case Decl::Using:
4510    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4511                                       D->getLocation(), TU);
4512
4513  case Decl::UsingShadow:
4514    return clang_getCursorDefinition(
4515                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4516                                    TU));
4517
4518  case Decl::ObjCMethod: {
4519    const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4520    if (Method->isThisDeclarationADefinition())
4521      return C;
4522
4523    // Dig out the method definition in the associated
4524    // @implementation, if we have it.
4525    // FIXME: The ASTs should make finding the definition easier.
4526    if (const ObjCInterfaceDecl *Class
4527                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4528      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4529        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4530                                                  Method->isInstanceMethod()))
4531          if (Def->isThisDeclarationADefinition())
4532            return MakeCXCursor(Def, TU);
4533
4534    return clang_getNullCursor();
4535  }
4536
4537  case Decl::ObjCCategory:
4538    if (ObjCCategoryImplDecl *Impl
4539                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4540      return MakeCXCursor(Impl, TU);
4541    return clang_getNullCursor();
4542
4543  case Decl::ObjCProtocol:
4544    if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4545      return MakeCXCursor(Def, TU);
4546    return clang_getNullCursor();
4547
4548  case Decl::ObjCInterface: {
4549    // There are two notions of a "definition" for an Objective-C
4550    // class: the interface and its implementation. When we resolved a
4551    // reference to an Objective-C class, produce the @interface as
4552    // the definition; when we were provided with the interface,
4553    // produce the @implementation as the definition.
4554    const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4555    if (WasReference) {
4556      if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
4557        return MakeCXCursor(Def, TU);
4558    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4559      return MakeCXCursor(Impl, TU);
4560    return clang_getNullCursor();
4561  }
4562
4563  case Decl::ObjCProperty:
4564    // FIXME: We don't really know where to find the
4565    // ObjCPropertyImplDecls that implement this property.
4566    return clang_getNullCursor();
4567
4568  case Decl::ObjCCompatibleAlias:
4569    if (const ObjCInterfaceDecl *Class
4570          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4571      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
4572        return MakeCXCursor(Def, TU);
4573
4574    return clang_getNullCursor();
4575
4576  case Decl::Friend:
4577    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4578      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4579    return clang_getNullCursor();
4580
4581  case Decl::FriendTemplate:
4582    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4583      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4584    return clang_getNullCursor();
4585  }
4586
4587  return clang_getNullCursor();
4588}
4589
4590unsigned clang_isCursorDefinition(CXCursor C) {
4591  if (!clang_isDeclaration(C.kind))
4592    return 0;
4593
4594  return clang_getCursorDefinition(C) == C;
4595}
4596
4597CXCursor clang_getCanonicalCursor(CXCursor C) {
4598  if (!clang_isDeclaration(C.kind))
4599    return C;
4600
4601  if (const Decl *D = getCursorDecl(C)) {
4602    if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4603      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4604        return MakeCXCursor(CatD, getCursorTU(C));
4605
4606    if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4607      if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4608        return MakeCXCursor(IFD, getCursorTU(C));
4609
4610    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4611  }
4612
4613  return C;
4614}
4615
4616int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4617  return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4618}
4619
4620unsigned clang_getNumOverloadedDecls(CXCursor C) {
4621  if (C.kind != CXCursor_OverloadedDeclRef)
4622    return 0;
4623
4624  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4625  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4626    return E->getNumDecls();
4627
4628  if (OverloadedTemplateStorage *S
4629                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4630    return S->size();
4631
4632  const Decl *D = Storage.get<const Decl *>();
4633  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4634    return Using->shadow_size();
4635
4636  return 0;
4637}
4638
4639CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4640  if (cursor.kind != CXCursor_OverloadedDeclRef)
4641    return clang_getNullCursor();
4642
4643  if (index >= clang_getNumOverloadedDecls(cursor))
4644    return clang_getNullCursor();
4645
4646  CXTranslationUnit TU = getCursorTU(cursor);
4647  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4648  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4649    return MakeCXCursor(E->decls_begin()[index], TU);
4650
4651  if (OverloadedTemplateStorage *S
4652                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4653    return MakeCXCursor(S->begin()[index], TU);
4654
4655  const Decl *D = Storage.get<const Decl *>();
4656  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4657    // FIXME: This is, unfortunately, linear time.
4658    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4659    std::advance(Pos, index);
4660    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4661  }
4662
4663  return clang_getNullCursor();
4664}
4665
4666void clang_getDefinitionSpellingAndExtent(CXCursor C,
4667                                          const char **startBuf,
4668                                          const char **endBuf,
4669                                          unsigned *startLine,
4670                                          unsigned *startColumn,
4671                                          unsigned *endLine,
4672                                          unsigned *endColumn) {
4673  assert(getCursorDecl(C) && "CXCursor has null decl");
4674  const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
4675  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4676
4677  SourceManager &SM = FD->getASTContext().getSourceManager();
4678  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4679  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4680  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4681  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4682  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4683  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4684}
4685
4686
4687CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4688                                                unsigned PieceIndex) {
4689  RefNamePieces Pieces;
4690
4691  switch (C.kind) {
4692  case CXCursor_MemberRefExpr:
4693    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4694      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4695                           E->getQualifierLoc().getSourceRange());
4696    break;
4697
4698  case CXCursor_DeclRefExpr:
4699    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4700      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4701                           E->getQualifierLoc().getSourceRange(),
4702                           E->getOptionalExplicitTemplateArgs());
4703    break;
4704
4705  case CXCursor_CallExpr:
4706    if (CXXOperatorCallExpr *OCE =
4707        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4708      Expr *Callee = OCE->getCallee();
4709      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4710        Callee = ICE->getSubExpr();
4711
4712      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4713        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4714                             DRE->getQualifierLoc().getSourceRange());
4715    }
4716    break;
4717
4718  default:
4719    break;
4720  }
4721
4722  if (Pieces.empty()) {
4723    if (PieceIndex == 0)
4724      return clang_getCursorExtent(C);
4725  } else if (PieceIndex < Pieces.size()) {
4726      SourceRange R = Pieces[PieceIndex];
4727      if (R.isValid())
4728        return cxloc::translateSourceRange(getCursorContext(C), R);
4729  }
4730
4731  return clang_getNullRange();
4732}
4733
4734void clang_enableStackTraces(void) {
4735  llvm::sys::PrintStackTraceOnErrorSignal();
4736}
4737
4738void clang_executeOnThread(void (*fn)(void*), void *user_data,
4739                           unsigned stack_size) {
4740  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4741}
4742
4743} // end: extern "C"
4744
4745//===----------------------------------------------------------------------===//
4746// Token-based Operations.
4747//===----------------------------------------------------------------------===//
4748
4749/* CXToken layout:
4750 *   int_data[0]: a CXTokenKind
4751 *   int_data[1]: starting token location
4752 *   int_data[2]: token length
4753 *   int_data[3]: reserved
4754 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4755 *   otherwise unused.
4756 */
4757extern "C" {
4758
4759CXTokenKind clang_getTokenKind(CXToken CXTok) {
4760  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4761}
4762
4763CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4764  switch (clang_getTokenKind(CXTok)) {
4765  case CXToken_Identifier:
4766  case CXToken_Keyword:
4767    // We know we have an IdentifierInfo*, so use that.
4768    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4769                            ->getNameStart());
4770
4771  case CXToken_Literal: {
4772    // We have stashed the starting pointer in the ptr_data field. Use it.
4773    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4774    return createCXString(StringRef(Text, CXTok.int_data[2]));
4775  }
4776
4777  case CXToken_Punctuation:
4778  case CXToken_Comment:
4779    break;
4780  }
4781
4782  // We have to find the starting buffer pointer the hard way, by
4783  // deconstructing the source location.
4784  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4785  if (!CXXUnit)
4786    return createCXString("");
4787
4788  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4789  std::pair<FileID, unsigned> LocInfo
4790    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4791  bool Invalid = false;
4792  StringRef Buffer
4793    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4794  if (Invalid)
4795    return createCXString("");
4796
4797  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4798}
4799
4800CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4801  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4802  if (!CXXUnit)
4803    return clang_getNullLocation();
4804
4805  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4806                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4807}
4808
4809CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4810  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4811  if (!CXXUnit)
4812    return clang_getNullRange();
4813
4814  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4815                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4816}
4817
4818static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4819                      SmallVectorImpl<CXToken> &CXTokens) {
4820  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4821  std::pair<FileID, unsigned> BeginLocInfo
4822    = SourceMgr.getDecomposedLoc(Range.getBegin());
4823  std::pair<FileID, unsigned> EndLocInfo
4824    = SourceMgr.getDecomposedLoc(Range.getEnd());
4825
4826  // Cannot tokenize across files.
4827  if (BeginLocInfo.first != EndLocInfo.first)
4828    return;
4829
4830  // Create a lexer
4831  bool Invalid = false;
4832  StringRef Buffer
4833    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4834  if (Invalid)
4835    return;
4836
4837  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4838            CXXUnit->getASTContext().getLangOpts(),
4839            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4840  Lex.SetCommentRetentionState(true);
4841
4842  // Lex tokens until we hit the end of the range.
4843  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4844  Token Tok;
4845  bool previousWasAt = false;
4846  do {
4847    // Lex the next token
4848    Lex.LexFromRawLexer(Tok);
4849    if (Tok.is(tok::eof))
4850      break;
4851
4852    // Initialize the CXToken.
4853    CXToken CXTok;
4854
4855    //   - Common fields
4856    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4857    CXTok.int_data[2] = Tok.getLength();
4858    CXTok.int_data[3] = 0;
4859
4860    //   - Kind-specific fields
4861    if (Tok.isLiteral()) {
4862      CXTok.int_data[0] = CXToken_Literal;
4863      CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
4864    } else if (Tok.is(tok::raw_identifier)) {
4865      // Lookup the identifier to determine whether we have a keyword.
4866      IdentifierInfo *II
4867        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4868
4869      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4870        CXTok.int_data[0] = CXToken_Keyword;
4871      }
4872      else {
4873        CXTok.int_data[0] = Tok.is(tok::identifier)
4874          ? CXToken_Identifier
4875          : CXToken_Keyword;
4876      }
4877      CXTok.ptr_data = II;
4878    } else if (Tok.is(tok::comment)) {
4879      CXTok.int_data[0] = CXToken_Comment;
4880      CXTok.ptr_data = 0;
4881    } else {
4882      CXTok.int_data[0] = CXToken_Punctuation;
4883      CXTok.ptr_data = 0;
4884    }
4885    CXTokens.push_back(CXTok);
4886    previousWasAt = Tok.is(tok::at);
4887  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4888}
4889
4890void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4891                    CXToken **Tokens, unsigned *NumTokens) {
4892  LOG_FUNC_SECTION {
4893    *Log << TU << ' ' << Range;
4894  }
4895
4896  if (Tokens)
4897    *Tokens = 0;
4898  if (NumTokens)
4899    *NumTokens = 0;
4900
4901  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4902  if (!CXXUnit || !Tokens || !NumTokens)
4903    return;
4904
4905  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4906
4907  SourceRange R = cxloc::translateCXSourceRange(Range);
4908  if (R.isInvalid())
4909    return;
4910
4911  SmallVector<CXToken, 32> CXTokens;
4912  getTokens(CXXUnit, R, CXTokens);
4913
4914  if (CXTokens.empty())
4915    return;
4916
4917  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4918  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4919  *NumTokens = CXTokens.size();
4920}
4921
4922void clang_disposeTokens(CXTranslationUnit TU,
4923                         CXToken *Tokens, unsigned NumTokens) {
4924  free(Tokens);
4925}
4926
4927} // end: extern "C"
4928
4929//===----------------------------------------------------------------------===//
4930// Token annotation APIs.
4931//===----------------------------------------------------------------------===//
4932
4933static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4934                                                     CXCursor parent,
4935                                                     CXClientData client_data);
4936static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4937                                              CXClientData client_data);
4938
4939namespace {
4940class AnnotateTokensWorker {
4941  CXToken *Tokens;
4942  CXCursor *Cursors;
4943  unsigned NumTokens;
4944  unsigned TokIdx;
4945  unsigned PreprocessingTokIdx;
4946  CursorVisitor AnnotateVis;
4947  SourceManager &SrcMgr;
4948  bool HasContextSensitiveKeywords;
4949
4950  struct PostChildrenInfo {
4951    CXCursor Cursor;
4952    SourceRange CursorRange;
4953    unsigned BeforeChildrenTokenIdx;
4954  };
4955  SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
4956
4957  bool MoreTokens() const { return TokIdx < NumTokens; }
4958  unsigned NextToken() const { return TokIdx; }
4959  void AdvanceToken() { ++TokIdx; }
4960  SourceLocation GetTokenLoc(unsigned tokI) {
4961    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4962  }
4963  bool isFunctionMacroToken(unsigned tokI) const {
4964    return Tokens[tokI].int_data[3] != 0;
4965  }
4966  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4967    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4968  }
4969
4970  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4971  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4972                                             SourceRange);
4973
4974public:
4975  AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4976                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4977    : Tokens(tokens), Cursors(cursors),
4978      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4979      AnnotateVis(tu,
4980                  AnnotateTokensVisitor, this,
4981                  /*VisitPreprocessorLast=*/true,
4982                  /*VisitIncludedEntities=*/false,
4983                  RegionOfInterest,
4984                  /*VisitDeclsOnly=*/false,
4985                  AnnotateTokensPostChildrenVisitor),
4986      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4987      HasContextSensitiveKeywords(false) { }
4988
4989  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4990  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4991  bool postVisitChildren(CXCursor cursor);
4992  void AnnotateTokens();
4993
4994  /// \brief Determine whether the annotator saw any cursors that have
4995  /// context-sensitive keywords.
4996  bool hasContextSensitiveKeywords() const {
4997    return HasContextSensitiveKeywords;
4998  }
4999
5000  ~AnnotateTokensWorker() {
5001    assert(PostChildrenInfos.empty());
5002  }
5003};
5004}
5005
5006void AnnotateTokensWorker::AnnotateTokens() {
5007  // Walk the AST within the region of interest, annotating tokens
5008  // along the way.
5009  AnnotateVis.visitFileRegion();
5010}
5011
5012static inline void updateCursorAnnotation(CXCursor &Cursor,
5013                                          const CXCursor &updateC) {
5014  if (clang_isInvalid(updateC.kind) || clang_isPreprocessing(Cursor.kind))
5015    return;
5016  Cursor = updateC;
5017}
5018
5019/// \brief It annotates and advances tokens with a cursor until the comparison
5020//// between the cursor location and the source range is the same as
5021/// \arg compResult.
5022///
5023/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5024/// Pass RangeOverlap to annotate tokens inside a range.
5025void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5026                                               RangeComparisonResult compResult,
5027                                               SourceRange range) {
5028  while (MoreTokens()) {
5029    const unsigned I = NextToken();
5030    if (isFunctionMacroToken(I))
5031      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
5032
5033    SourceLocation TokLoc = GetTokenLoc(I);
5034    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5035      updateCursorAnnotation(Cursors[I], updateC);
5036      AdvanceToken();
5037      continue;
5038    }
5039    break;
5040  }
5041}
5042
5043/// \brief Special annotation handling for macro argument tokens.
5044void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5045                                               CXCursor updateC,
5046                                               RangeComparisonResult compResult,
5047                                               SourceRange range) {
5048  assert(MoreTokens());
5049  assert(isFunctionMacroToken(NextToken()) &&
5050         "Should be called only for macro arg tokens");
5051
5052  // This works differently than annotateAndAdvanceTokens; because expanded
5053  // macro arguments can have arbitrary translation-unit source order, we do not
5054  // advance the token index one by one until a token fails the range test.
5055  // We only advance once past all of the macro arg tokens if all of them
5056  // pass the range test. If one of them fails we keep the token index pointing
5057  // at the start of the macro arg tokens so that the failing token will be
5058  // annotated by a subsequent annotation try.
5059
5060  bool atLeastOneCompFail = false;
5061
5062  unsigned I = NextToken();
5063  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5064    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5065    if (TokLoc.isFileID())
5066      continue; // not macro arg token, it's parens or comma.
5067    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5068      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5069        Cursors[I] = updateC;
5070    } else
5071      atLeastOneCompFail = true;
5072  }
5073
5074  if (!atLeastOneCompFail)
5075    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5076}
5077
5078enum CXChildVisitResult
5079AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5080  SourceRange cursorRange = getRawCursorExtent(cursor);
5081  if (cursorRange.isInvalid())
5082    return CXChildVisit_Recurse;
5083
5084  if (!HasContextSensitiveKeywords) {
5085    // Objective-C properties can have context-sensitive keywords.
5086    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5087      if (const ObjCPropertyDecl *Property
5088                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5089        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5090    }
5091    // Objective-C methods can have context-sensitive keywords.
5092    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5093             cursor.kind == CXCursor_ObjCClassMethodDecl) {
5094      if (const ObjCMethodDecl *Method
5095            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5096        if (Method->getObjCDeclQualifier())
5097          HasContextSensitiveKeywords = true;
5098        else {
5099          for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
5100                                                 PEnd = Method->param_end();
5101               P != PEnd; ++P) {
5102            if ((*P)->getObjCDeclQualifier()) {
5103              HasContextSensitiveKeywords = true;
5104              break;
5105            }
5106          }
5107        }
5108      }
5109    }
5110    // C++ methods can have context-sensitive keywords.
5111    else if (cursor.kind == CXCursor_CXXMethod) {
5112      if (const CXXMethodDecl *Method
5113                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5114        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5115          HasContextSensitiveKeywords = true;
5116      }
5117    }
5118    // C++ classes can have context-sensitive keywords.
5119    else if (cursor.kind == CXCursor_StructDecl ||
5120             cursor.kind == CXCursor_ClassDecl ||
5121             cursor.kind == CXCursor_ClassTemplate ||
5122             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5123      if (const Decl *D = getCursorDecl(cursor))
5124        if (D->hasAttr<FinalAttr>())
5125          HasContextSensitiveKeywords = true;
5126    }
5127  }
5128
5129  if (clang_isPreprocessing(cursor.kind)) {
5130    // Items in the preprocessing record are kept separate from items in
5131    // declarations, so we keep a separate token index.
5132    unsigned SavedTokIdx = TokIdx;
5133    TokIdx = PreprocessingTokIdx;
5134
5135    // Skip tokens up until we catch up to the beginning of the preprocessing
5136    // entry.
5137    while (MoreTokens()) {
5138      const unsigned I = NextToken();
5139      SourceLocation TokLoc = GetTokenLoc(I);
5140      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5141      case RangeBefore:
5142        AdvanceToken();
5143        continue;
5144      case RangeAfter:
5145      case RangeOverlap:
5146        break;
5147      }
5148      break;
5149    }
5150
5151    // Look at all of the tokens within this range.
5152    while (MoreTokens()) {
5153      const unsigned I = NextToken();
5154      SourceLocation TokLoc = GetTokenLoc(I);
5155      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5156      case RangeBefore:
5157        llvm_unreachable("Infeasible");
5158      case RangeAfter:
5159        break;
5160      case RangeOverlap:
5161        // We may have already annotated macro names inside macro definitions.
5162        if (Cursors[I].kind != CXCursor_MacroExpansion)
5163          Cursors[I] = cursor;
5164        AdvanceToken();
5165        // For macro expansions, just note where the beginning of the macro
5166        // expansion occurs.
5167        if (cursor.kind == CXCursor_MacroExpansion)
5168          break;
5169        continue;
5170      }
5171      break;
5172    }
5173
5174    // Save the preprocessing token index; restore the non-preprocessing
5175    // token index.
5176    PreprocessingTokIdx = TokIdx;
5177    TokIdx = SavedTokIdx;
5178    return CXChildVisit_Recurse;
5179  }
5180
5181  if (cursorRange.isInvalid())
5182    return CXChildVisit_Continue;
5183
5184  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5185  const enum CXCursorKind K = clang_getCursorKind(parent);
5186  const CXCursor updateC =
5187    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5188     ? clang_getNullCursor() : parent;
5189
5190  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5191
5192  // Avoid having the cursor of an expression "overwrite" the annotation of the
5193  // variable declaration that it belongs to.
5194  // This can happen for C++ constructor expressions whose range generally
5195  // include the variable declaration, e.g.:
5196  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5197  if (clang_isExpression(cursorK)) {
5198    Expr *E = getCursorExpr(cursor);
5199    if (Decl *D = getCursorParentDecl(cursor)) {
5200      const unsigned I = NextToken();
5201      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5202          E->getLocStart() == D->getLocation() &&
5203          E->getLocStart() == GetTokenLoc(I)) {
5204        updateCursorAnnotation(Cursors[I], updateC);
5205        AdvanceToken();
5206      }
5207    }
5208  }
5209
5210  // Before recursing into the children keep some state that we are going
5211  // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5212  // extra work after the child nodes are visited.
5213  // Note that we don't call VisitChildren here to avoid traversing statements
5214  // code-recursively which can blow the stack.
5215
5216  PostChildrenInfo Info;
5217  Info.Cursor = cursor;
5218  Info.CursorRange = cursorRange;
5219  Info.BeforeChildrenTokenIdx = NextToken();
5220  PostChildrenInfos.push_back(Info);
5221
5222  return CXChildVisit_Recurse;
5223}
5224
5225bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5226  if (PostChildrenInfos.empty())
5227    return false;
5228  const PostChildrenInfo &Info = PostChildrenInfos.back();
5229  if (!clang_equalCursors(Info.Cursor, cursor))
5230    return false;
5231
5232  const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5233  const unsigned AfterChildren = NextToken();
5234  SourceRange cursorRange = Info.CursorRange;
5235
5236  // Scan the tokens that are at the end of the cursor, but are not captured
5237  // but the child cursors.
5238  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5239
5240  // Scan the tokens that are at the beginning of the cursor, but are not
5241  // capture by the child cursors.
5242  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5243    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5244      break;
5245
5246    Cursors[I] = cursor;
5247  }
5248
5249  PostChildrenInfos.pop_back();
5250  return false;
5251}
5252
5253static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5254                                                     CXCursor parent,
5255                                                     CXClientData client_data) {
5256  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5257}
5258
5259static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5260                                              CXClientData client_data) {
5261  return static_cast<AnnotateTokensWorker*>(client_data)->
5262                                                      postVisitChildren(cursor);
5263}
5264
5265namespace {
5266
5267/// \brief Uses the macro expansions in the preprocessing record to find
5268/// and mark tokens that are macro arguments. This info is used by the
5269/// AnnotateTokensWorker.
5270class MarkMacroArgTokensVisitor {
5271  SourceManager &SM;
5272  CXToken *Tokens;
5273  unsigned NumTokens;
5274  unsigned CurIdx;
5275
5276public:
5277  MarkMacroArgTokensVisitor(SourceManager &SM,
5278                            CXToken *tokens, unsigned numTokens)
5279    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5280
5281  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5282    if (cursor.kind != CXCursor_MacroExpansion)
5283      return CXChildVisit_Continue;
5284
5285    SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
5286    if (macroRange.getBegin() == macroRange.getEnd())
5287      return CXChildVisit_Continue; // it's not a function macro.
5288
5289    for (; CurIdx < NumTokens; ++CurIdx) {
5290      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5291                                        macroRange.getBegin()))
5292        break;
5293    }
5294
5295    if (CurIdx == NumTokens)
5296      return CXChildVisit_Break;
5297
5298    for (; CurIdx < NumTokens; ++CurIdx) {
5299      SourceLocation tokLoc = getTokenLoc(CurIdx);
5300      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5301        break;
5302
5303      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5304    }
5305
5306    if (CurIdx == NumTokens)
5307      return CXChildVisit_Break;
5308
5309    return CXChildVisit_Continue;
5310  }
5311
5312private:
5313  SourceLocation getTokenLoc(unsigned tokI) {
5314    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5315  }
5316
5317  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5318    // The third field is reserved and currently not used. Use it here
5319    // to mark macro arg expanded tokens with their expanded locations.
5320    Tokens[tokI].int_data[3] = loc.getRawEncoding();
5321  }
5322};
5323
5324} // end anonymous namespace
5325
5326static CXChildVisitResult
5327MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5328                                  CXClientData client_data) {
5329  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5330                                                                     parent);
5331}
5332
5333namespace {
5334  struct clang_annotateTokens_Data {
5335    CXTranslationUnit TU;
5336    ASTUnit *CXXUnit;
5337    CXToken *Tokens;
5338    unsigned NumTokens;
5339    CXCursor *Cursors;
5340  };
5341}
5342
5343/// \brief Used by \c annotatePreprocessorTokens.
5344/// \returns true if lexing was finished, false otherwise.
5345static bool lexNext(Lexer &Lex, Token &Tok,
5346                   unsigned &NextIdx, unsigned NumTokens) {
5347  if (NextIdx >= NumTokens)
5348    return true;
5349
5350  ++NextIdx;
5351  Lex.LexFromRawLexer(Tok);
5352  if (Tok.is(tok::eof))
5353    return true;
5354
5355  return false;
5356}
5357
5358static void annotatePreprocessorTokens(CXTranslationUnit TU,
5359                                       SourceRange RegionOfInterest,
5360                                       CXCursor *Cursors,
5361                                       CXToken *Tokens,
5362                                       unsigned NumTokens) {
5363  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5364
5365  Preprocessor &PP = CXXUnit->getPreprocessor();
5366  SourceManager &SourceMgr = CXXUnit->getSourceManager();
5367  std::pair<FileID, unsigned> BeginLocInfo
5368    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5369  std::pair<FileID, unsigned> EndLocInfo
5370    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5371
5372  if (BeginLocInfo.first != EndLocInfo.first)
5373    return;
5374
5375  StringRef Buffer;
5376  bool Invalid = false;
5377  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5378  if (Buffer.empty() || Invalid)
5379    return;
5380
5381  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5382            CXXUnit->getASTContext().getLangOpts(),
5383            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5384            Buffer.end());
5385  Lex.SetCommentRetentionState(true);
5386
5387  unsigned NextIdx = 0;
5388  // Lex tokens in raw mode until we hit the end of the range, to avoid
5389  // entering #includes or expanding macros.
5390  while (true) {
5391    Token Tok;
5392    if (lexNext(Lex, Tok, NextIdx, NumTokens))
5393      break;
5394    unsigned TokIdx = NextIdx-1;
5395    assert(Tok.getLocation() ==
5396             SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
5397
5398  reprocess:
5399    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5400      // We have found a preprocessing directive. Annotate the tokens
5401      // appropriately.
5402      //
5403      // FIXME: Some simple tests here could identify macro definitions and
5404      // #undefs, to provide specific cursor kinds for those.
5405
5406      SourceLocation BeginLoc = Tok.getLocation();
5407      if (lexNext(Lex, Tok, NextIdx, NumTokens))
5408        break;
5409
5410      MacroInfo *MI = 0;
5411      if (Tok.is(tok::raw_identifier) &&
5412          StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == "define") {
5413        if (lexNext(Lex, Tok, NextIdx, NumTokens))
5414          break;
5415
5416        if (Tok.is(tok::raw_identifier)) {
5417          StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
5418          IdentifierInfo &II = PP.getIdentifierTable().get(Name);
5419          SourceLocation MappedTokLoc =
5420              CXXUnit->mapLocationToPreamble(Tok.getLocation());
5421          MI = getMacroInfo(II, MappedTokLoc, TU);
5422        }
5423      }
5424
5425      bool finished = false;
5426      do {
5427        if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
5428          finished = true;
5429          break;
5430        }
5431        // If we are in a macro definition, check if the token was ever a
5432        // macro name and annotate it if that's the case.
5433        if (MI) {
5434          SourceLocation SaveLoc = Tok.getLocation();
5435          Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
5436          MacroDefinition *MacroDef = checkForMacroInMacroDefinition(MI,Tok,TU);
5437          Tok.setLocation(SaveLoc);
5438          if (MacroDef)
5439            Cursors[NextIdx-1] = MakeMacroExpansionCursor(MacroDef,
5440                                                         Tok.getLocation(), TU);
5441        }
5442      } while (!Tok.isAtStartOfLine());
5443
5444      unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
5445      assert(TokIdx <= LastIdx);
5446      SourceLocation EndLoc =
5447          SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
5448      CXCursor Cursor =
5449          MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
5450
5451      for (; TokIdx <= LastIdx; ++TokIdx)
5452        updateCursorAnnotation(Cursors[TokIdx], Cursor);
5453
5454      if (finished)
5455        break;
5456      goto reprocess;
5457    }
5458  }
5459}
5460
5461// This gets run a separate thread to avoid stack blowout.
5462static void clang_annotateTokensImpl(void *UserData) {
5463  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5464  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5465  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5466  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5467  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5468
5469  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5470  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5471    setThreadBackgroundPriority();
5472
5473  // Determine the region of interest, which contains all of the tokens.
5474  SourceRange RegionOfInterest;
5475  RegionOfInterest.setBegin(
5476    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5477  RegionOfInterest.setEnd(
5478    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5479                                                         Tokens[NumTokens-1])));
5480
5481  // Relex the tokens within the source range to look for preprocessing
5482  // directives.
5483  annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
5484
5485  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5486    // Search and mark tokens that are macro argument expansions.
5487    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5488                                      Tokens, NumTokens);
5489    CursorVisitor MacroArgMarker(TU,
5490                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5491                                 /*VisitPreprocessorLast=*/true,
5492                                 /*VisitIncludedEntities=*/false,
5493                                 RegionOfInterest);
5494    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5495  }
5496
5497  // Annotate all of the source locations in the region of interest that map to
5498  // a specific cursor.
5499  AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
5500
5501  // FIXME: We use a ridiculous stack size here because the data-recursion
5502  // algorithm uses a large stack frame than the non-data recursive version,
5503  // and AnnotationTokensWorker currently transforms the data-recursion
5504  // algorithm back into a traditional recursion by explicitly calling
5505  // VisitChildren().  We will need to remove this explicit recursive call.
5506  W.AnnotateTokens();
5507
5508  // If we ran into any entities that involve context-sensitive keywords,
5509  // take another pass through the tokens to mark them as such.
5510  if (W.hasContextSensitiveKeywords()) {
5511    for (unsigned I = 0; I != NumTokens; ++I) {
5512      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5513        continue;
5514
5515      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5516        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5517        if (const ObjCPropertyDecl *Property
5518            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5519          if (Property->getPropertyAttributesAsWritten() != 0 &&
5520              llvm::StringSwitch<bool>(II->getName())
5521              .Case("readonly", true)
5522              .Case("assign", true)
5523              .Case("unsafe_unretained", true)
5524              .Case("readwrite", true)
5525              .Case("retain", true)
5526              .Case("copy", true)
5527              .Case("nonatomic", true)
5528              .Case("atomic", true)
5529              .Case("getter", true)
5530              .Case("setter", true)
5531              .Case("strong", true)
5532              .Case("weak", true)
5533              .Default(false))
5534            Tokens[I].int_data[0] = CXToken_Keyword;
5535        }
5536        continue;
5537      }
5538
5539      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5540          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5541        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5542        if (llvm::StringSwitch<bool>(II->getName())
5543            .Case("in", true)
5544            .Case("out", true)
5545            .Case("inout", true)
5546            .Case("oneway", true)
5547            .Case("bycopy", true)
5548            .Case("byref", true)
5549            .Default(false))
5550          Tokens[I].int_data[0] = CXToken_Keyword;
5551        continue;
5552      }
5553
5554      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5555          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5556        Tokens[I].int_data[0] = CXToken_Keyword;
5557        continue;
5558      }
5559    }
5560  }
5561}
5562
5563extern "C" {
5564
5565void clang_annotateTokens(CXTranslationUnit TU,
5566                          CXToken *Tokens, unsigned NumTokens,
5567                          CXCursor *Cursors) {
5568  if (NumTokens == 0 || !Tokens || !Cursors) {
5569    LOG_FUNC_SECTION { *Log << "<null input>"; }
5570    return;
5571  }
5572
5573  LOG_FUNC_SECTION {
5574    *Log << TU << ' ';
5575    CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
5576    CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
5577    *Log << clang_getRange(bloc, eloc);
5578  }
5579
5580  // Any token we don't specifically annotate will have a NULL cursor.
5581  CXCursor C = clang_getNullCursor();
5582  for (unsigned I = 0; I != NumTokens; ++I)
5583    Cursors[I] = C;
5584
5585  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5586  if (!CXXUnit)
5587    return;
5588
5589  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5590
5591  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5592  llvm::CrashRecoveryContext CRC;
5593  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5594                 GetSafetyThreadStackSize() * 2)) {
5595    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5596  }
5597}
5598
5599} // end: extern "C"
5600
5601//===----------------------------------------------------------------------===//
5602// Operations for querying linkage of a cursor.
5603//===----------------------------------------------------------------------===//
5604
5605extern "C" {
5606CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5607  if (!clang_isDeclaration(cursor.kind))
5608    return CXLinkage_Invalid;
5609
5610  const Decl *D = cxcursor::getCursorDecl(cursor);
5611  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5612    switch (ND->getLinkage()) {
5613      case NoLinkage: return CXLinkage_NoLinkage;
5614      case InternalLinkage: return CXLinkage_Internal;
5615      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5616      case ExternalLinkage: return CXLinkage_External;
5617    };
5618
5619  return CXLinkage_Invalid;
5620}
5621} // end: extern "C"
5622
5623//===----------------------------------------------------------------------===//
5624// Operations for querying language of a cursor.
5625//===----------------------------------------------------------------------===//
5626
5627static CXLanguageKind getDeclLanguage(const Decl *D) {
5628  if (!D)
5629    return CXLanguage_C;
5630
5631  switch (D->getKind()) {
5632    default:
5633      break;
5634    case Decl::ImplicitParam:
5635    case Decl::ObjCAtDefsField:
5636    case Decl::ObjCCategory:
5637    case Decl::ObjCCategoryImpl:
5638    case Decl::ObjCCompatibleAlias:
5639    case Decl::ObjCImplementation:
5640    case Decl::ObjCInterface:
5641    case Decl::ObjCIvar:
5642    case Decl::ObjCMethod:
5643    case Decl::ObjCProperty:
5644    case Decl::ObjCPropertyImpl:
5645    case Decl::ObjCProtocol:
5646      return CXLanguage_ObjC;
5647    case Decl::CXXConstructor:
5648    case Decl::CXXConversion:
5649    case Decl::CXXDestructor:
5650    case Decl::CXXMethod:
5651    case Decl::CXXRecord:
5652    case Decl::ClassTemplate:
5653    case Decl::ClassTemplatePartialSpecialization:
5654    case Decl::ClassTemplateSpecialization:
5655    case Decl::Friend:
5656    case Decl::FriendTemplate:
5657    case Decl::FunctionTemplate:
5658    case Decl::LinkageSpec:
5659    case Decl::Namespace:
5660    case Decl::NamespaceAlias:
5661    case Decl::NonTypeTemplateParm:
5662    case Decl::StaticAssert:
5663    case Decl::TemplateTemplateParm:
5664    case Decl::TemplateTypeParm:
5665    case Decl::UnresolvedUsingTypename:
5666    case Decl::UnresolvedUsingValue:
5667    case Decl::Using:
5668    case Decl::UsingDirective:
5669    case Decl::UsingShadow:
5670      return CXLanguage_CPlusPlus;
5671  }
5672
5673  return CXLanguage_C;
5674}
5675
5676extern "C" {
5677
5678enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5679  if (clang_isDeclaration(cursor.kind))
5680    if (const Decl *D = cxcursor::getCursorDecl(cursor)) {
5681      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5682        return CXAvailability_Available;
5683
5684      switch (D->getAvailability()) {
5685      case AR_Available:
5686      case AR_NotYetIntroduced:
5687        return CXAvailability_Available;
5688
5689      case AR_Deprecated:
5690        return CXAvailability_Deprecated;
5691
5692      case AR_Unavailable:
5693        return CXAvailability_NotAvailable;
5694      }
5695    }
5696
5697  return CXAvailability_Available;
5698}
5699
5700static CXVersion convertVersion(VersionTuple In) {
5701  CXVersion Out = { -1, -1, -1 };
5702  if (In.empty())
5703    return Out;
5704
5705  Out.Major = In.getMajor();
5706
5707  if (llvm::Optional<unsigned> Minor = In.getMinor())
5708    Out.Minor = *Minor;
5709  else
5710    return Out;
5711
5712  if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5713    Out.Subminor = *Subminor;
5714
5715  return Out;
5716}
5717
5718int clang_getCursorPlatformAvailability(CXCursor cursor,
5719                                        int *always_deprecated,
5720                                        CXString *deprecated_message,
5721                                        int *always_unavailable,
5722                                        CXString *unavailable_message,
5723                                        CXPlatformAvailability *availability,
5724                                        int availability_size) {
5725  if (always_deprecated)
5726    *always_deprecated = 0;
5727  if (deprecated_message)
5728    *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5729  if (always_unavailable)
5730    *always_unavailable = 0;
5731  if (unavailable_message)
5732    *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5733
5734  if (!clang_isDeclaration(cursor.kind))
5735    return 0;
5736
5737  const Decl *D = cxcursor::getCursorDecl(cursor);
5738  if (!D)
5739    return 0;
5740
5741  int N = 0;
5742  for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5743       ++A) {
5744    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5745      if (always_deprecated)
5746        *always_deprecated = 1;
5747      if (deprecated_message)
5748        *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5749      continue;
5750    }
5751
5752    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5753      if (always_unavailable)
5754        *always_unavailable = 1;
5755      if (unavailable_message) {
5756        *unavailable_message
5757          = cxstring::createCXString(Unavailable->getMessage());
5758      }
5759      continue;
5760    }
5761
5762    if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5763      if (N < availability_size) {
5764        availability[N].Platform
5765          = cxstring::createCXString(Avail->getPlatform()->getName());
5766        availability[N].Introduced = convertVersion(Avail->getIntroduced());
5767        availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5768        availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5769        availability[N].Unavailable = Avail->getUnavailable();
5770        availability[N].Message = cxstring::createCXString(Avail->getMessage());
5771      }
5772      ++N;
5773    }
5774  }
5775
5776  return N;
5777}
5778
5779void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5780  clang_disposeString(availability->Platform);
5781  clang_disposeString(availability->Message);
5782}
5783
5784CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5785  if (clang_isDeclaration(cursor.kind))
5786    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5787
5788  return CXLanguage_Invalid;
5789}
5790
5791 /// \brief If the given cursor is the "templated" declaration
5792 /// descibing a class or function template, return the class or
5793 /// function template.
5794static const Decl *maybeGetTemplateCursor(const Decl *D) {
5795  if (!D)
5796    return 0;
5797
5798  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5799    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5800      return FunTmpl;
5801
5802  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5803    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5804      return ClassTmpl;
5805
5806  return D;
5807}
5808
5809CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5810  if (clang_isDeclaration(cursor.kind)) {
5811    if (const Decl *D = getCursorDecl(cursor)) {
5812      const DeclContext *DC = D->getDeclContext();
5813      if (!DC)
5814        return clang_getNullCursor();
5815
5816      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5817                          getCursorTU(cursor));
5818    }
5819  }
5820
5821  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5822    if (const Decl *D = getCursorDecl(cursor))
5823      return MakeCXCursor(D, getCursorTU(cursor));
5824  }
5825
5826  return clang_getNullCursor();
5827}
5828
5829CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5830  if (clang_isDeclaration(cursor.kind)) {
5831    if (const Decl *D = getCursorDecl(cursor)) {
5832      const DeclContext *DC = D->getLexicalDeclContext();
5833      if (!DC)
5834        return clang_getNullCursor();
5835
5836      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5837                          getCursorTU(cursor));
5838    }
5839  }
5840
5841  // FIXME: Note that we can't easily compute the lexical context of a
5842  // statement or expression, so we return nothing.
5843  return clang_getNullCursor();
5844}
5845
5846CXFile clang_getIncludedFile(CXCursor cursor) {
5847  if (cursor.kind != CXCursor_InclusionDirective)
5848    return 0;
5849
5850  const InclusionDirective *ID = getCursorInclusionDirective(cursor);
5851  return const_cast<FileEntry *>(ID->getFile());
5852}
5853
5854CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5855  if (!clang_isDeclaration(C.kind))
5856    return clang_getNullRange();
5857
5858  const Decl *D = getCursorDecl(C);
5859  ASTContext &Context = getCursorContext(C);
5860  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5861  if (!RC)
5862    return clang_getNullRange();
5863
5864  return cxloc::translateSourceRange(Context, RC->getSourceRange());
5865}
5866
5867CXString clang_Cursor_getRawCommentText(CXCursor C) {
5868  if (!clang_isDeclaration(C.kind))
5869    return createCXString((const char *) NULL);
5870
5871  const Decl *D = getCursorDecl(C);
5872  ASTContext &Context = getCursorContext(C);
5873  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5874  StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5875                           StringRef();
5876
5877  // Don't duplicate the string because RawText points directly into source
5878  // code.
5879  return createCXString(RawText, false);
5880}
5881
5882CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5883  if (!clang_isDeclaration(C.kind))
5884    return createCXString((const char *) NULL);
5885
5886  const Decl *D = getCursorDecl(C);
5887  const ASTContext &Context = getCursorContext(C);
5888  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5889
5890  if (RC) {
5891    StringRef BriefText = RC->getBriefText(Context);
5892
5893    // Don't duplicate the string because RawComment ensures that this memory
5894    // will not go away.
5895    return createCXString(BriefText, false);
5896  }
5897
5898  return createCXString((const char *) NULL);
5899}
5900
5901CXComment clang_Cursor_getParsedComment(CXCursor C) {
5902  if (!clang_isDeclaration(C.kind))
5903    return cxcomment::createCXComment(NULL, NULL);
5904
5905  const Decl *D = getCursorDecl(C);
5906  const ASTContext &Context = getCursorContext(C);
5907  const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
5908
5909  return cxcomment::createCXComment(FC, getCursorTU(C));
5910}
5911
5912CXModule clang_Cursor_getModule(CXCursor C) {
5913  if (C.kind == CXCursor_ModuleImportDecl) {
5914    if (const ImportDecl *ImportD =
5915            dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5916      return ImportD->getImportedModule();
5917  }
5918
5919  return 0;
5920}
5921
5922CXModule clang_Module_getParent(CXModule CXMod) {
5923  if (!CXMod)
5924    return 0;
5925  Module *Mod = static_cast<Module*>(CXMod);
5926  return Mod->Parent;
5927}
5928
5929CXString clang_Module_getName(CXModule CXMod) {
5930  if (!CXMod)
5931    return createCXString("");
5932  Module *Mod = static_cast<Module*>(CXMod);
5933  return createCXString(Mod->Name);
5934}
5935
5936CXString clang_Module_getFullName(CXModule CXMod) {
5937  if (!CXMod)
5938    return createCXString("");
5939  Module *Mod = static_cast<Module*>(CXMod);
5940  return createCXString(Mod->getFullModuleName());
5941}
5942
5943unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5944  if (!CXMod)
5945    return 0;
5946  Module *Mod = static_cast<Module*>(CXMod);
5947  return Mod->TopHeaders.size();
5948}
5949
5950CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5951  if (!CXMod)
5952    return 0;
5953  Module *Mod = static_cast<Module*>(CXMod);
5954
5955  if (Index < Mod->TopHeaders.size())
5956    return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5957
5958  return 0;
5959}
5960
5961} // end: extern "C"
5962
5963//===----------------------------------------------------------------------===//
5964// C++ AST instrospection.
5965//===----------------------------------------------------------------------===//
5966
5967extern "C" {
5968unsigned clang_CXXMethod_isStatic(CXCursor C) {
5969  if (!clang_isDeclaration(C.kind))
5970    return 0;
5971
5972  const CXXMethodDecl *Method = 0;
5973  const Decl *D = cxcursor::getCursorDecl(C);
5974  if (const FunctionTemplateDecl *FunTmpl =
5975          dyn_cast_or_null<FunctionTemplateDecl>(D))
5976    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5977  else
5978    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5979  return (Method && Method->isStatic()) ? 1 : 0;
5980}
5981
5982unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5983  if (!clang_isDeclaration(C.kind))
5984    return 0;
5985
5986  const CXXMethodDecl *Method = 0;
5987  const Decl *D = cxcursor::getCursorDecl(C);
5988  if (const FunctionTemplateDecl *FunTmpl =
5989          dyn_cast_or_null<FunctionTemplateDecl>(D))
5990    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5991  else
5992    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5993  return (Method && Method->isVirtual()) ? 1 : 0;
5994}
5995} // end: extern "C"
5996
5997//===----------------------------------------------------------------------===//
5998// Attribute introspection.
5999//===----------------------------------------------------------------------===//
6000
6001extern "C" {
6002CXType clang_getIBOutletCollectionType(CXCursor C) {
6003  if (C.kind != CXCursor_IBOutletCollectionAttr)
6004    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
6005
6006  IBOutletCollectionAttr *A =
6007    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
6008
6009  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
6010}
6011} // end: extern "C"
6012
6013//===----------------------------------------------------------------------===//
6014// Inspecting memory usage.
6015//===----------------------------------------------------------------------===//
6016
6017typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
6018
6019static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
6020                                              enum CXTUResourceUsageKind k,
6021                                              unsigned long amount) {
6022  CXTUResourceUsageEntry entry = { k, amount };
6023  entries.push_back(entry);
6024}
6025
6026extern "C" {
6027
6028const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
6029  const char *str = "";
6030  switch (kind) {
6031    case CXTUResourceUsage_AST:
6032      str = "ASTContext: expressions, declarations, and types";
6033      break;
6034    case CXTUResourceUsage_Identifiers:
6035      str = "ASTContext: identifiers";
6036      break;
6037    case CXTUResourceUsage_Selectors:
6038      str = "ASTContext: selectors";
6039      break;
6040    case CXTUResourceUsage_GlobalCompletionResults:
6041      str = "Code completion: cached global results";
6042      break;
6043    case CXTUResourceUsage_SourceManagerContentCache:
6044      str = "SourceManager: content cache allocator";
6045      break;
6046    case CXTUResourceUsage_AST_SideTables:
6047      str = "ASTContext: side tables";
6048      break;
6049    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
6050      str = "SourceManager: malloc'ed memory buffers";
6051      break;
6052    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
6053      str = "SourceManager: mmap'ed memory buffers";
6054      break;
6055    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6056      str = "ExternalASTSource: malloc'ed memory buffers";
6057      break;
6058    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6059      str = "ExternalASTSource: mmap'ed memory buffers";
6060      break;
6061    case CXTUResourceUsage_Preprocessor:
6062      str = "Preprocessor: malloc'ed memory";
6063      break;
6064    case CXTUResourceUsage_PreprocessingRecord:
6065      str = "Preprocessor: PreprocessingRecord";
6066      break;
6067    case CXTUResourceUsage_SourceManager_DataStructures:
6068      str = "SourceManager: data structures and tables";
6069      break;
6070    case CXTUResourceUsage_Preprocessor_HeaderSearch:
6071      str = "Preprocessor: header search tables";
6072      break;
6073  }
6074  return str;
6075}
6076
6077CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
6078  if (!TU) {
6079    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
6080    return usage;
6081  }
6082
6083  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
6084  OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
6085  ASTContext &astContext = astUnit->getASTContext();
6086
6087  // How much memory is used by AST nodes and types?
6088  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
6089    (unsigned long) astContext.getASTAllocatedMemory());
6090
6091  // How much memory is used by identifiers?
6092  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
6093    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6094
6095  // How much memory is used for selectors?
6096  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
6097    (unsigned long) astContext.Selectors.getTotalMemory());
6098
6099  // How much memory is used by ASTContext's side tables?
6100  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6101    (unsigned long) astContext.getSideTableAllocatedMemory());
6102
6103  // How much memory is used for caching global code completion results?
6104  unsigned long completionBytes = 0;
6105  if (GlobalCodeCompletionAllocator *completionAllocator =
6106      astUnit->getCachedCompletionAllocator().getPtr()) {
6107    completionBytes = completionAllocator->getTotalMemory();
6108  }
6109  createCXTUResourceUsageEntry(*entries,
6110                               CXTUResourceUsage_GlobalCompletionResults,
6111                               completionBytes);
6112
6113  // How much memory is being used by SourceManager's content cache?
6114  createCXTUResourceUsageEntry(*entries,
6115          CXTUResourceUsage_SourceManagerContentCache,
6116          (unsigned long) astContext.getSourceManager().getContentCacheSize());
6117
6118  // How much memory is being used by the MemoryBuffer's in SourceManager?
6119  const SourceManager::MemoryBufferSizes &srcBufs =
6120    astUnit->getSourceManager().getMemoryBufferSizes();
6121
6122  createCXTUResourceUsageEntry(*entries,
6123                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6124                               (unsigned long) srcBufs.malloc_bytes);
6125  createCXTUResourceUsageEntry(*entries,
6126                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
6127                               (unsigned long) srcBufs.mmap_bytes);
6128  createCXTUResourceUsageEntry(*entries,
6129                               CXTUResourceUsage_SourceManager_DataStructures,
6130                               (unsigned long) astContext.getSourceManager()
6131                                .getDataStructureSizes());
6132
6133  // How much memory is being used by the ExternalASTSource?
6134  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6135    const ExternalASTSource::MemoryBufferSizes &sizes =
6136      esrc->getMemoryBufferSizes();
6137
6138    createCXTUResourceUsageEntry(*entries,
6139      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6140                                 (unsigned long) sizes.malloc_bytes);
6141    createCXTUResourceUsageEntry(*entries,
6142      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6143                                 (unsigned long) sizes.mmap_bytes);
6144  }
6145
6146  // How much memory is being used by the Preprocessor?
6147  Preprocessor &pp = astUnit->getPreprocessor();
6148  createCXTUResourceUsageEntry(*entries,
6149                               CXTUResourceUsage_Preprocessor,
6150                               pp.getTotalMemory());
6151
6152  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6153    createCXTUResourceUsageEntry(*entries,
6154                                 CXTUResourceUsage_PreprocessingRecord,
6155                                 pRec->getTotalMemory());
6156  }
6157
6158  createCXTUResourceUsageEntry(*entries,
6159                               CXTUResourceUsage_Preprocessor_HeaderSearch,
6160                               pp.getHeaderSearchInfo().getTotalMemory());
6161
6162  CXTUResourceUsage usage = { (void*) entries.get(),
6163                            (unsigned) entries->size(),
6164                            entries->size() ? &(*entries)[0] : 0 };
6165  entries.take();
6166  return usage;
6167}
6168
6169void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
6170  if (usage.data)
6171    delete (MemUsageEntries*) usage.data;
6172}
6173
6174} // end extern "C"
6175
6176void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6177  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6178  for (unsigned I = 0; I != Usage.numEntries; ++I)
6179    fprintf(stderr, "  %s: %lu\n",
6180            clang_getTUResourceUsageName(Usage.entries[I].kind),
6181            Usage.entries[I].amount);
6182
6183  clang_disposeCXTUResourceUsage(Usage);
6184}
6185
6186//===----------------------------------------------------------------------===//
6187// Misc. utility functions.
6188//===----------------------------------------------------------------------===//
6189
6190/// Default to using an 8 MB stack size on "safety" threads.
6191static unsigned SafetyStackThreadSize = 8 << 20;
6192
6193namespace clang {
6194
6195bool RunSafely(llvm::CrashRecoveryContext &CRC,
6196               void (*Fn)(void*), void *UserData,
6197               unsigned Size) {
6198  if (!Size)
6199    Size = GetSafetyThreadStackSize();
6200  if (Size)
6201    return CRC.RunSafelyOnThread(Fn, UserData, Size);
6202  return CRC.RunSafely(Fn, UserData);
6203}
6204
6205unsigned GetSafetyThreadStackSize() {
6206  return SafetyStackThreadSize;
6207}
6208
6209void SetSafetyThreadStackSize(unsigned Value) {
6210  SafetyStackThreadSize = Value;
6211}
6212
6213}
6214
6215void clang::setThreadBackgroundPriority() {
6216  if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6217    return;
6218
6219  // FIXME: Move to llvm/Support and make it cross-platform.
6220#ifdef __APPLE__
6221  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6222#endif
6223}
6224
6225void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6226  if (!Unit)
6227    return;
6228
6229  for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6230                                  DEnd = Unit->stored_diag_end();
6231       D != DEnd; ++D) {
6232    CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6233    CXString Msg = clang_formatDiagnostic(&Diag,
6234                                clang_defaultDiagnosticDisplayOptions());
6235    fprintf(stderr, "%s\n", clang_getCString(Msg));
6236    clang_disposeString(Msg);
6237  }
6238#ifdef LLVM_ON_WIN32
6239  // On Windows, force a flush, since there may be multiple copies of
6240  // stderr and stdout in the file system, all with different buffers
6241  // but writing to the same device.
6242  fflush(stderr);
6243#endif
6244}
6245
6246MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
6247                                 SourceLocation MacroDefLoc,
6248                                 CXTranslationUnit TU){
6249  if (MacroDefLoc.isInvalid() || !TU)
6250    return 0;
6251  if (!II.hadMacroDefinition())
6252    return 0;
6253
6254  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6255  Preprocessor &PP = Unit->getPreprocessor();
6256  MacroInfo *MI = PP.getMacroInfoHistory(&II);
6257  while (MI) {
6258    if (MacroDefLoc == MI->getDefinitionLoc())
6259      return MI;
6260    MI = MI->getPreviousDefinition();
6261  }
6262
6263  return 0;
6264}
6265
6266const MacroInfo *cxindex::getMacroInfo(const MacroDefinition *MacroDef,
6267                                       CXTranslationUnit TU) {
6268  if (!MacroDef || !TU)
6269    return 0;
6270  const IdentifierInfo *II = MacroDef->getName();
6271  if (!II)
6272    return 0;
6273
6274  return getMacroInfo(*II, MacroDef->getLocation(), TU);
6275}
6276
6277MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6278                                                         const Token &Tok,
6279                                                         CXTranslationUnit TU) {
6280  if (!MI || !TU)
6281    return 0;
6282  if (Tok.isNot(tok::raw_identifier))
6283    return 0;
6284
6285  if (MI->getNumTokens() == 0)
6286    return 0;
6287  SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
6288                       MI->getDefinitionEndLoc());
6289  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6290
6291  // Check that the token is inside the definition and not its argument list.
6292  SourceManager &SM = Unit->getSourceManager();
6293  if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
6294    return 0;
6295  if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
6296    return 0;
6297
6298  Preprocessor &PP = Unit->getPreprocessor();
6299  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
6300  if (!PPRec)
6301    return 0;
6302
6303  StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
6304  IdentifierInfo &II = PP.getIdentifierTable().get(Name);
6305  if (!II.hadMacroDefinition())
6306    return 0;
6307
6308  // Check that the identifier is not one of the macro arguments.
6309  if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
6310    return 0;
6311
6312  MacroInfo *InnerMI = PP.getMacroInfoHistory(&II);
6313  if (!InnerMI)
6314    return 0;
6315
6316  return PPRec->findMacroDefinition(InnerMI);
6317}
6318
6319MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6320                                                         SourceLocation Loc,
6321                                                         CXTranslationUnit TU) {
6322  if (Loc.isInvalid() || !MI || !TU)
6323    return 0;
6324
6325  if (MI->getNumTokens() == 0)
6326    return 0;
6327  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6328  Preprocessor &PP = Unit->getPreprocessor();
6329  if (!PP.getPreprocessingRecord())
6330    return 0;
6331  Loc = Unit->getSourceManager().getSpellingLoc(Loc);
6332  Token Tok;
6333  if (PP.getRawToken(Loc, Tok))
6334    return 0;
6335
6336  return checkForMacroInMacroDefinition(MI, Tok, TU);
6337}
6338
6339extern "C" {
6340
6341CXString clang_getClangVersion() {
6342  return createCXString(getClangFullVersion());
6343}
6344
6345} // end: extern "C"
6346
6347Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
6348  if (TU) {
6349    if (ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData)) {
6350      LogOS << '<' << Unit->getMainFileName() << '>';
6351      return *this;
6352    }
6353  }
6354
6355  LogOS << "<NULL TU>";
6356  return *this;
6357}
6358
6359Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
6360  CXFile File;
6361  unsigned Line, Column;
6362  clang_getFileLocation(Loc, &File, &Line, &Column, 0);
6363  CXString FileName = clang_getFileName(File);
6364  *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
6365  clang_disposeString(FileName);
6366  return *this;
6367}
6368
6369Logger &cxindex::Logger::operator<<(CXSourceRange range) {
6370  CXSourceLocation BLoc = clang_getRangeStart(range);
6371  CXSourceLocation ELoc = clang_getRangeEnd(range);
6372
6373  CXFile BFile;
6374  unsigned BLine, BColumn;
6375  clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, 0);
6376
6377  CXFile EFile;
6378  unsigned ELine, EColumn;
6379  clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, 0);
6380
6381  CXString BFileName = clang_getFileName(BFile);
6382  if (BFile == EFile) {
6383    *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
6384                         BLine, BColumn, ELine, EColumn);
6385  } else {
6386    CXString EFileName = clang_getFileName(EFile);
6387    *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
6388                          BLine, BColumn)
6389          << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
6390                          ELine, EColumn);
6391    clang_disposeString(EFileName);
6392  }
6393  clang_disposeString(BFileName);
6394  return *this;
6395}
6396
6397Logger &cxindex::Logger::operator<<(CXString Str) {
6398  *this << clang_getCString(Str);
6399  return *this;
6400}
6401
6402Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
6403  LogOS << Fmt;
6404  return *this;
6405}
6406
6407cxindex::Logger::~Logger() {
6408  LogOS.flush();
6409
6410  llvm::sys::ScopedLock L(EnableMultithreadingMutex);
6411
6412  static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
6413
6414  raw_ostream &OS = llvm::errs();
6415  OS << "[libclang:" << Name << ':';
6416
6417  // FIXME: Portability.
6418#if HAVE_PTHREAD_H && __APPLE__
6419  mach_port_t tid = pthread_mach_thread_np(pthread_self());
6420  OS << tid << ':';
6421#endif
6422
6423  llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
6424  OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
6425  OS << Msg.str() << '\n';
6426
6427  if (Trace) {
6428    llvm::sys::PrintStackTrace(stderr);
6429    OS << "--------------------------------------------------\n";
6430  }
6431}
6432