CIndex.cpp revision e22339c44bb28d71a2cc97c840d3da0c4bdb4909
1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CIndexDiagnostic.h"
17#include "CLog.h"
18#include "CXComment.h"
19#include "CXCursor.h"
20#include "CXSourceLocation.h"
21#include "CXString.h"
22#include "CXTranslationUnit.h"
23#include "CXType.h"
24#include "CursorVisitor.h"
25#include "SimpleFormatContext.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
31#include "clang/Frontend/FrontendDiagnostic.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/Lexer.h"
34#include "clang/Lex/PreprocessingRecord.h"
35#include "clang/Lex/Preprocessor.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringSwitch.h"
39#include "llvm/Config/config.h"
40#include "llvm/Support/Compiler.h"
41#include "llvm/Support/CrashRecoveryContext.h"
42#include "llvm/Support/Format.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/Mutex.h"
45#include "llvm/Support/PrettyStackTrace.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/SaveAndRestore.h"
48#include "llvm/Support/Signals.h"
49#include "llvm/Support/Threading.h"
50#include "llvm/Support/Timer.h"
51#include "llvm/Support/raw_ostream.h"
52
53#if HAVE_PTHREAD_H
54#include <pthread.h>
55#endif
56
57using namespace clang;
58using namespace clang::cxcursor;
59using namespace clang::cxstring;
60using namespace clang::cxtu;
61using namespace clang::cxindex;
62
63CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
64  if (!TU)
65    return 0;
66  CXTranslationUnit D = new CXTranslationUnitImpl();
67  D->CIdx = CIdx;
68  D->TUData = TU;
69  D->StringPool = createCXStringPool();
70  D->Diagnostics = 0;
71  D->OverridenCursorsPool = createOverridenCXCursorsPool();
72  D->FormatContext = 0;
73  D->FormatInMemoryUniqueId = 0;
74  return D;
75}
76
77cxtu::CXTUOwner::~CXTUOwner() {
78  if (TU)
79    clang_disposeTranslationUnit(TU);
80}
81
82/// \brief Compare two source ranges to determine their relative position in
83/// the translation unit.
84static RangeComparisonResult RangeCompare(SourceManager &SM,
85                                          SourceRange R1,
86                                          SourceRange R2) {
87  assert(R1.isValid() && "First range is invalid?");
88  assert(R2.isValid() && "Second range is invalid?");
89  if (R1.getEnd() != R2.getBegin() &&
90      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
91    return RangeBefore;
92  if (R2.getEnd() != R1.getBegin() &&
93      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
94    return RangeAfter;
95  return RangeOverlap;
96}
97
98/// \brief Determine if a source location falls within, before, or after a
99///   a given source range.
100static RangeComparisonResult LocationCompare(SourceManager &SM,
101                                             SourceLocation L, SourceRange R) {
102  assert(R.isValid() && "First range is invalid?");
103  assert(L.isValid() && "Second range is invalid?");
104  if (L == R.getBegin() || L == R.getEnd())
105    return RangeOverlap;
106  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
107    return RangeBefore;
108  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
109    return RangeAfter;
110  return RangeOverlap;
111}
112
113/// \brief Translate a Clang source range into a CIndex source range.
114///
115/// Clang internally represents ranges where the end location points to the
116/// start of the token at the end. However, for external clients it is more
117/// useful to have a CXSourceRange be a proper half-open interval. This routine
118/// does the appropriate translation.
119CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
120                                          const LangOptions &LangOpts,
121                                          const CharSourceRange &R) {
122  // We want the last character in this location, so we will adjust the
123  // location accordingly.
124  SourceLocation EndLoc = R.getEnd();
125  if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
126    EndLoc = SM.getExpansionRange(EndLoc).second;
127  if (R.isTokenRange() && !EndLoc.isInvalid()) {
128    unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
129                                                SM, LangOpts);
130    EndLoc = EndLoc.getLocWithOffset(Length);
131  }
132
133  CXSourceRange Result = {
134    { &SM, &LangOpts },
135    R.getBegin().getRawEncoding(),
136    EndLoc.getRawEncoding()
137  };
138  return Result;
139}
140
141//===----------------------------------------------------------------------===//
142// Cursor visitor.
143//===----------------------------------------------------------------------===//
144
145static SourceRange getRawCursorExtent(CXCursor C);
146static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
147
148
149RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
150  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
151}
152
153/// \brief Visit the given cursor and, if requested by the visitor,
154/// its children.
155///
156/// \param Cursor the cursor to visit.
157///
158/// \param CheckedRegionOfInterest if true, then the caller already checked
159/// that this cursor is within the region of interest.
160///
161/// \returns true if the visitation should be aborted, false if it
162/// should continue.
163bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
164  if (clang_isInvalid(Cursor.kind))
165    return false;
166
167  if (clang_isDeclaration(Cursor.kind)) {
168    const Decl *D = getCursorDecl(Cursor);
169    if (!D) {
170      assert(0 && "Invalid declaration cursor");
171      return true; // abort.
172    }
173
174    // Ignore implicit declarations, unless it's an objc method because
175    // currently we should report implicit methods for properties when indexing.
176    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
177      return false;
178  }
179
180  // If we have a range of interest, and this cursor doesn't intersect with it,
181  // we're done.
182  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
183    SourceRange Range = getRawCursorExtent(Cursor);
184    if (Range.isInvalid() || CompareRegionOfInterest(Range))
185      return false;
186  }
187
188  switch (Visitor(Cursor, Parent, ClientData)) {
189  case CXChildVisit_Break:
190    return true;
191
192  case CXChildVisit_Continue:
193    return false;
194
195  case CXChildVisit_Recurse: {
196    bool ret = VisitChildren(Cursor);
197    if (PostChildrenVisitor)
198      if (PostChildrenVisitor(Cursor, ClientData))
199        return true;
200    return ret;
201  }
202  }
203
204  llvm_unreachable("Invalid CXChildVisitResult!");
205}
206
207static bool visitPreprocessedEntitiesInRange(SourceRange R,
208                                             PreprocessingRecord &PPRec,
209                                             CursorVisitor &Visitor) {
210  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
211  FileID FID;
212
213  if (!Visitor.shouldVisitIncludedEntities()) {
214    // If the begin/end of the range lie in the same FileID, do the optimization
215    // where we skip preprocessed entities that do not come from the same FileID.
216    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
217    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
218      FID = FileID();
219  }
220
221  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
222    Entities = PPRec.getPreprocessedEntitiesInRange(R);
223  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
224                                           PPRec, FID);
225}
226
227void CursorVisitor::visitFileRegion() {
228  if (RegionOfInterest.isInvalid())
229    return;
230
231  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
232  SourceManager &SM = Unit->getSourceManager();
233
234  std::pair<FileID, unsigned>
235    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
236    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
237
238  if (End.first != Begin.first) {
239    // If the end does not reside in the same file, try to recover by
240    // picking the end of the file of begin location.
241    End.first = Begin.first;
242    End.second = SM.getFileIDSize(Begin.first);
243  }
244
245  assert(Begin.first == End.first);
246  if (Begin.second > End.second)
247    return;
248
249  FileID File = Begin.first;
250  unsigned Offset = Begin.second;
251  unsigned Length = End.second - Begin.second;
252
253  if (!VisitDeclsOnly && !VisitPreprocessorLast)
254    if (visitPreprocessedEntitiesInRegion())
255      return; // visitation break.
256
257  visitDeclsFromFileRegion(File, Offset, Length);
258
259  if (!VisitDeclsOnly && VisitPreprocessorLast)
260    visitPreprocessedEntitiesInRegion();
261}
262
263static bool isInLexicalContext(Decl *D, DeclContext *DC) {
264  if (!DC)
265    return false;
266
267  for (DeclContext *DeclDC = D->getLexicalDeclContext();
268         DeclDC; DeclDC = DeclDC->getLexicalParent()) {
269    if (DeclDC == DC)
270      return true;
271  }
272  return false;
273}
274
275void CursorVisitor::visitDeclsFromFileRegion(FileID File,
276                                             unsigned Offset, unsigned Length) {
277  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
278  SourceManager &SM = Unit->getSourceManager();
279  SourceRange Range = RegionOfInterest;
280
281  SmallVector<Decl *, 16> Decls;
282  Unit->findFileRegionDecls(File, Offset, Length, Decls);
283
284  // If we didn't find any file level decls for the file, try looking at the
285  // file that it was included from.
286  while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
287    bool Invalid = false;
288    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
289    if (Invalid)
290      return;
291
292    SourceLocation Outer;
293    if (SLEntry.isFile())
294      Outer = SLEntry.getFile().getIncludeLoc();
295    else
296      Outer = SLEntry.getExpansion().getExpansionLocStart();
297    if (Outer.isInvalid())
298      return;
299
300    llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
301    Length = 0;
302    Unit->findFileRegionDecls(File, Offset, Length, Decls);
303  }
304
305  assert(!Decls.empty());
306
307  bool VisitedAtLeastOnce = false;
308  DeclContext *CurDC = 0;
309  SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
310  for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
311    Decl *D = *DIt;
312    if (D->getSourceRange().isInvalid())
313      continue;
314
315    if (isInLexicalContext(D, CurDC))
316      continue;
317
318    CurDC = dyn_cast<DeclContext>(D);
319
320    if (TagDecl *TD = dyn_cast<TagDecl>(D))
321      if (!TD->isFreeStanding())
322        continue;
323
324    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
325    if (CompRes == RangeBefore)
326      continue;
327    if (CompRes == RangeAfter)
328      break;
329
330    assert(CompRes == RangeOverlap);
331    VisitedAtLeastOnce = true;
332
333    if (isa<ObjCContainerDecl>(D)) {
334      FileDI_current = &DIt;
335      FileDE_current = DE;
336    } else {
337      FileDI_current = 0;
338    }
339
340    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
341      break;
342  }
343
344  if (VisitedAtLeastOnce)
345    return;
346
347  // No Decls overlapped with the range. Move up the lexical context until there
348  // is a context that contains the range or we reach the translation unit
349  // level.
350  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
351                                         : (*(DIt-1))->getLexicalDeclContext();
352
353  while (DC && !DC->isTranslationUnit()) {
354    Decl *D = cast<Decl>(DC);
355    SourceRange CurDeclRange = D->getSourceRange();
356    if (CurDeclRange.isInvalid())
357      break;
358
359    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
360      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
361      break;
362    }
363
364    DC = D->getLexicalDeclContext();
365  }
366}
367
368bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
369  if (!AU->getPreprocessor().getPreprocessingRecord())
370    return false;
371
372  PreprocessingRecord &PPRec
373    = *AU->getPreprocessor().getPreprocessingRecord();
374  SourceManager &SM = AU->getSourceManager();
375
376  if (RegionOfInterest.isValid()) {
377    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
378    SourceLocation B = MappedRange.getBegin();
379    SourceLocation E = MappedRange.getEnd();
380
381    if (AU->isInPreambleFileID(B)) {
382      if (SM.isLoadedSourceLocation(E))
383        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
384                                                 PPRec, *this);
385
386      // Beginning of range lies in the preamble but it also extends beyond
387      // it into the main file. Split the range into 2 parts, one covering
388      // the preamble and another covering the main file. This allows subsequent
389      // calls to visitPreprocessedEntitiesInRange to accept a source range that
390      // lies in the same FileID, allowing it to skip preprocessed entities that
391      // do not come from the same FileID.
392      bool breaked =
393        visitPreprocessedEntitiesInRange(
394                                   SourceRange(B, AU->getEndOfPreambleFileID()),
395                                          PPRec, *this);
396      if (breaked) return true;
397      return visitPreprocessedEntitiesInRange(
398                                    SourceRange(AU->getStartOfMainFileID(), E),
399                                        PPRec, *this);
400    }
401
402    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
403  }
404
405  bool OnlyLocalDecls
406    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
407
408  if (OnlyLocalDecls)
409    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
410                                     PPRec);
411
412  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
413}
414
415template<typename InputIterator>
416bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
417                                              InputIterator Last,
418                                              PreprocessingRecord &PPRec,
419                                              FileID FID) {
420  for (; First != Last; ++First) {
421    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
422      continue;
423
424    PreprocessedEntity *PPE = *First;
425    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
426      if (Visit(MakeMacroExpansionCursor(ME, TU)))
427        return true;
428
429      continue;
430    }
431
432    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
433      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
434        return true;
435
436      continue;
437    }
438
439    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
440      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
441        return true;
442
443      continue;
444    }
445  }
446
447  return false;
448}
449
450/// \brief Visit the children of the given cursor.
451///
452/// \returns true if the visitation should be aborted, false if it
453/// should continue.
454bool CursorVisitor::VisitChildren(CXCursor Cursor) {
455  if (clang_isReference(Cursor.kind) &&
456      Cursor.kind != CXCursor_CXXBaseSpecifier) {
457    // By definition, references have no children.
458    return false;
459  }
460
461  // Set the Parent field to Cursor, then back to its old value once we're
462  // done.
463  SetParentRAII SetParent(Parent, StmtParent, Cursor);
464
465  if (clang_isDeclaration(Cursor.kind)) {
466    Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
467    if (!D)
468      return false;
469
470    return VisitAttributes(D) || Visit(D);
471  }
472
473  if (clang_isStatement(Cursor.kind)) {
474    if (Stmt *S = getCursorStmt(Cursor))
475      return Visit(S);
476
477    return false;
478  }
479
480  if (clang_isExpression(Cursor.kind)) {
481    if (Expr *E = getCursorExpr(Cursor))
482      return Visit(E);
483
484    return false;
485  }
486
487  if (clang_isTranslationUnit(Cursor.kind)) {
488    CXTranslationUnit tu = getCursorTU(Cursor);
489    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
490
491    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
492    for (unsigned I = 0; I != 2; ++I) {
493      if (VisitOrder[I]) {
494        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
495            RegionOfInterest.isInvalid()) {
496          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
497                                        TLEnd = CXXUnit->top_level_end();
498               TL != TLEnd; ++TL) {
499            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
500              return true;
501          }
502        } else if (VisitDeclContext(
503                                CXXUnit->getASTContext().getTranslationUnitDecl()))
504          return true;
505        continue;
506      }
507
508      // Walk the preprocessing record.
509      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
510        visitPreprocessedEntitiesInRegion();
511    }
512
513    return false;
514  }
515
516  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
517    if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
518      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
519        return Visit(BaseTSInfo->getTypeLoc());
520      }
521    }
522  }
523
524  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
525    IBOutletCollectionAttr *A =
526      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
527    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
528      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
529                                                    A->getInterfaceLoc(), TU));
530  }
531
532  // If pointing inside a macro definition, check if the token is an identifier
533  // that was ever defined as a macro. In such a case, create a "pseudo" macro
534  // expansion cursor for that token.
535  SourceLocation BeginLoc = RegionOfInterest.getBegin();
536  if (Cursor.kind == CXCursor_MacroDefinition &&
537      BeginLoc == RegionOfInterest.getEnd()) {
538    SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
539    const MacroInfo *MI =
540        getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
541    if (MacroDefinition *MacroDef =
542          checkForMacroInMacroDefinition(MI, Loc, TU))
543      return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
544  }
545
546  // Nothing to visit at the moment.
547  return false;
548}
549
550bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
551  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
552    if (Visit(TSInfo->getTypeLoc()))
553        return true;
554
555  if (Stmt *Body = B->getBody())
556    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
557
558  return false;
559}
560
561llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
562  if (RegionOfInterest.isValid()) {
563    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
564    if (Range.isInvalid())
565      return llvm::Optional<bool>();
566
567    switch (CompareRegionOfInterest(Range)) {
568    case RangeBefore:
569      // This declaration comes before the region of interest; skip it.
570      return llvm::Optional<bool>();
571
572    case RangeAfter:
573      // This declaration comes after the region of interest; we're done.
574      return false;
575
576    case RangeOverlap:
577      // This declaration overlaps the region of interest; visit it.
578      break;
579    }
580  }
581  return true;
582}
583
584bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
585  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
586
587  // FIXME: Eventually remove.  This part of a hack to support proper
588  // iteration over all Decls contained lexically within an ObjC container.
589  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
590  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
591
592  for ( ; I != E; ++I) {
593    Decl *D = *I;
594    if (D->getLexicalDeclContext() != DC)
595      continue;
596    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
597
598    // Ignore synthesized ivars here, otherwise if we have something like:
599    //   @synthesize prop = _prop;
600    // and '_prop' is not declared, we will encounter a '_prop' ivar before
601    // encountering the 'prop' synthesize declaration and we will think that
602    // we passed the region-of-interest.
603    if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
604      if (ivarD->getSynthesize())
605        continue;
606    }
607
608    // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
609    // declarations is a mismatch with the compiler semantics.
610    if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
611      ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
612      if (!ID->isThisDeclarationADefinition())
613        Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
614
615    } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
616      ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
617      if (!PD->isThisDeclarationADefinition())
618        Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
619    }
620
621    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
622    if (!V.hasValue())
623      continue;
624    if (!V.getValue())
625      return false;
626    if (Visit(Cursor, true))
627      return true;
628  }
629  return false;
630}
631
632bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
633  llvm_unreachable("Translation units are visited directly by Visit()");
634}
635
636bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
637  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
638    return Visit(TSInfo->getTypeLoc());
639
640  return false;
641}
642
643bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
644  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
645    return Visit(TSInfo->getTypeLoc());
646
647  return false;
648}
649
650bool CursorVisitor::VisitTagDecl(TagDecl *D) {
651  return VisitDeclContext(D);
652}
653
654bool CursorVisitor::VisitClassTemplateSpecializationDecl(
655                                          ClassTemplateSpecializationDecl *D) {
656  bool ShouldVisitBody = false;
657  switch (D->getSpecializationKind()) {
658  case TSK_Undeclared:
659  case TSK_ImplicitInstantiation:
660    // Nothing to visit
661    return false;
662
663  case TSK_ExplicitInstantiationDeclaration:
664  case TSK_ExplicitInstantiationDefinition:
665    break;
666
667  case TSK_ExplicitSpecialization:
668    ShouldVisitBody = true;
669    break;
670  }
671
672  // Visit the template arguments used in the specialization.
673  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
674    TypeLoc TL = SpecType->getTypeLoc();
675    if (TemplateSpecializationTypeLoc *TSTLoc
676          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
677      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
678        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
679          return true;
680    }
681  }
682
683  if (ShouldVisitBody && VisitCXXRecordDecl(D))
684    return true;
685
686  return false;
687}
688
689bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
690                                   ClassTemplatePartialSpecializationDecl *D) {
691  // FIXME: Visit the "outer" template parameter lists on the TagDecl
692  // before visiting these template parameters.
693  if (VisitTemplateParameters(D->getTemplateParameters()))
694    return true;
695
696  // Visit the partial specialization arguments.
697  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
698  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
699    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
700      return true;
701
702  return VisitCXXRecordDecl(D);
703}
704
705bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
706  // Visit the default argument.
707  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
708    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
709      if (Visit(DefArg->getTypeLoc()))
710        return true;
711
712  return false;
713}
714
715bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
716  if (Expr *Init = D->getInitExpr())
717    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
718  return false;
719}
720
721bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
722  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
723    if (Visit(TSInfo->getTypeLoc()))
724      return true;
725
726  // Visit the nested-name-specifier, if present.
727  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
728    if (VisitNestedNameSpecifierLoc(QualifierLoc))
729      return true;
730
731  return false;
732}
733
734/// \brief Compare two base or member initializers based on their source order.
735static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
736  CXXCtorInitializer const * const *X
737    = static_cast<CXXCtorInitializer const * const *>(Xp);
738  CXXCtorInitializer const * const *Y
739    = static_cast<CXXCtorInitializer const * const *>(Yp);
740
741  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
742    return -1;
743  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
744    return 1;
745  else
746    return 0;
747}
748
749bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
750  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
751    // Visit the function declaration's syntactic components in the order
752    // written. This requires a bit of work.
753    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
754    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
755
756    // If we have a function declared directly (without the use of a typedef),
757    // visit just the return type. Otherwise, just visit the function's type
758    // now.
759    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
760        (!FTL && Visit(TL)))
761      return true;
762
763    // Visit the nested-name-specifier, if present.
764    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
765      if (VisitNestedNameSpecifierLoc(QualifierLoc))
766        return true;
767
768    // Visit the declaration name.
769    if (VisitDeclarationNameInfo(ND->getNameInfo()))
770      return true;
771
772    // FIXME: Visit explicitly-specified template arguments!
773
774    // Visit the function parameters, if we have a function type.
775    if (FTL && VisitFunctionTypeLoc(*FTL, true))
776      return true;
777
778    // FIXME: Attributes?
779  }
780
781  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
782    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
783      // Find the initializers that were written in the source.
784      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
785      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
786                                          IEnd = Constructor->init_end();
787           I != IEnd; ++I) {
788        if (!(*I)->isWritten())
789          continue;
790
791        WrittenInits.push_back(*I);
792      }
793
794      // Sort the initializers in source order
795      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
796                           &CompareCXXCtorInitializers);
797
798      // Visit the initializers in source order
799      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
800        CXXCtorInitializer *Init = WrittenInits[I];
801        if (Init->isAnyMemberInitializer()) {
802          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
803                                        Init->getMemberLocation(), TU)))
804            return true;
805        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
806          if (Visit(TInfo->getTypeLoc()))
807            return true;
808        }
809
810        // Visit the initializer value.
811        if (Expr *Initializer = Init->getInit())
812          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
813            return true;
814      }
815    }
816
817    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
818      return true;
819  }
820
821  return false;
822}
823
824bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
825  if (VisitDeclaratorDecl(D))
826    return true;
827
828  if (Expr *BitWidth = D->getBitWidth())
829    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
830
831  return false;
832}
833
834bool CursorVisitor::VisitVarDecl(VarDecl *D) {
835  if (VisitDeclaratorDecl(D))
836    return true;
837
838  if (Expr *Init = D->getInit())
839    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
840
841  return false;
842}
843
844bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
845  if (VisitDeclaratorDecl(D))
846    return true;
847
848  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
849    if (Expr *DefArg = D->getDefaultArgument())
850      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
851
852  return false;
853}
854
855bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
856  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
857  // before visiting these template parameters.
858  if (VisitTemplateParameters(D->getTemplateParameters()))
859    return true;
860
861  return VisitFunctionDecl(D->getTemplatedDecl());
862}
863
864bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
865  // FIXME: Visit the "outer" template parameter lists on the TagDecl
866  // before visiting these template parameters.
867  if (VisitTemplateParameters(D->getTemplateParameters()))
868    return true;
869
870  return VisitCXXRecordDecl(D->getTemplatedDecl());
871}
872
873bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
874  if (VisitTemplateParameters(D->getTemplateParameters()))
875    return true;
876
877  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
878      VisitTemplateArgumentLoc(D->getDefaultArgument()))
879    return true;
880
881  return false;
882}
883
884bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
885  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
886    if (Visit(TSInfo->getTypeLoc()))
887      return true;
888
889  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
890       PEnd = ND->param_end();
891       P != PEnd; ++P) {
892    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
893      return true;
894  }
895
896  if (ND->isThisDeclarationADefinition() &&
897      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
898    return true;
899
900  return false;
901}
902
903template <typename DeclIt>
904static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
905                                      SourceManager &SM, SourceLocation EndLoc,
906                                      SmallVectorImpl<Decl *> &Decls) {
907  DeclIt next = *DI_current;
908  while (++next != DE_current) {
909    Decl *D_next = *next;
910    if (!D_next)
911      break;
912    SourceLocation L = D_next->getLocStart();
913    if (!L.isValid())
914      break;
915    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
916      *DI_current = next;
917      Decls.push_back(D_next);
918      continue;
919    }
920    break;
921  }
922}
923
924namespace {
925  struct ContainerDeclsSort {
926    SourceManager &SM;
927    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
928    bool operator()(Decl *A, Decl *B) {
929      SourceLocation L_A = A->getLocStart();
930      SourceLocation L_B = B->getLocStart();
931      assert(L_A.isValid() && L_B.isValid());
932      return SM.isBeforeInTranslationUnit(L_A, L_B);
933    }
934  };
935}
936
937bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
938  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
939  // an @implementation can lexically contain Decls that are not properly
940  // nested in the AST.  When we identify such cases, we need to retrofit
941  // this nesting here.
942  if (!DI_current && !FileDI_current)
943    return VisitDeclContext(D);
944
945  // Scan the Decls that immediately come after the container
946  // in the current DeclContext.  If any fall within the
947  // container's lexical region, stash them into a vector
948  // for later processing.
949  SmallVector<Decl *, 24> DeclsInContainer;
950  SourceLocation EndLoc = D->getSourceRange().getEnd();
951  SourceManager &SM = AU->getSourceManager();
952  if (EndLoc.isValid()) {
953    if (DI_current) {
954      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
955                                DeclsInContainer);
956    } else {
957      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
958                                DeclsInContainer);
959    }
960  }
961
962  // The common case.
963  if (DeclsInContainer.empty())
964    return VisitDeclContext(D);
965
966  // Get all the Decls in the DeclContext, and sort them with the
967  // additional ones we've collected.  Then visit them.
968  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
969       I!=E; ++I) {
970    Decl *subDecl = *I;
971    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
972        subDecl->getLocStart().isInvalid())
973      continue;
974    DeclsInContainer.push_back(subDecl);
975  }
976
977  // Now sort the Decls so that they appear in lexical order.
978  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
979            ContainerDeclsSort(SM));
980
981  // Now visit the decls.
982  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
983         E = DeclsInContainer.end(); I != E; ++I) {
984    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
985    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
986    if (!V.hasValue())
987      continue;
988    if (!V.getValue())
989      return false;
990    if (Visit(Cursor, true))
991      return true;
992  }
993  return false;
994}
995
996bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
997  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
998                                   TU)))
999    return true;
1000
1001  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1002  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1003         E = ND->protocol_end(); I != E; ++I, ++PL)
1004    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1005      return true;
1006
1007  return VisitObjCContainerDecl(ND);
1008}
1009
1010bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1011  if (!PID->isThisDeclarationADefinition())
1012    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1013
1014  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1015  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1016       E = PID->protocol_end(); I != E; ++I, ++PL)
1017    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1018      return true;
1019
1020  return VisitObjCContainerDecl(PID);
1021}
1022
1023bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1024  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1025    return true;
1026
1027  // FIXME: This implements a workaround with @property declarations also being
1028  // installed in the DeclContext for the @interface.  Eventually this code
1029  // should be removed.
1030  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1031  if (!CDecl || !CDecl->IsClassExtension())
1032    return false;
1033
1034  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
2963} // end: extern "C"
2964
2965//===----------------------------------------------------------------------===//
2966// CXCursor Operations.
2967//===----------------------------------------------------------------------===//
2968
2969static const Decl *getDeclFromExpr(const Stmt *E) {
2970  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2971    return getDeclFromExpr(CE->getSubExpr());
2972
2973  if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2974    return RefExpr->getDecl();
2975  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
2976    return ME->getMemberDecl();
2977  if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2978    return RE->getDecl();
2979  if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2980    if (PRE->isExplicitProperty())
2981      return PRE->getExplicitProperty();
2982    // It could be messaging both getter and setter as in:
2983    // ++myobj.myprop;
2984    // in which case prefer to associate the setter since it is less obvious
2985    // from inspecting the source that the setter is going to get called.
2986    if (PRE->isMessagingSetter())
2987      return PRE->getImplicitPropertySetter();
2988    return PRE->getImplicitPropertyGetter();
2989  }
2990  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2991    return getDeclFromExpr(POE->getSyntacticForm());
2992  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2993    if (Expr *Src = OVE->getSourceExpr())
2994      return getDeclFromExpr(Src);
2995
2996  if (const CallExpr *CE = dyn_cast<CallExpr>(E))
2997    return getDeclFromExpr(CE->getCallee());
2998  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2999    if (!CE->isElidable())
3000    return CE->getConstructor();
3001  if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3002    return OME->getMethodDecl();
3003
3004  if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3005    return PE->getProtocol();
3006  if (const SubstNonTypeTemplateParmPackExpr *NTTP
3007                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3008    return NTTP->getParameterPack();
3009  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3010    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3011        isa<ParmVarDecl>(SizeOfPack->getPack()))
3012      return SizeOfPack->getPack();
3013
3014  return 0;
3015}
3016
3017static SourceLocation getLocationFromExpr(Expr *E) {
3018  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3019    return getLocationFromExpr(CE->getSubExpr());
3020
3021  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3022    return /*FIXME:*/Msg->getLeftLoc();
3023  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3024    return DRE->getLocation();
3025  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3026    return Member->getMemberLoc();
3027  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3028    return Ivar->getLocation();
3029  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3030    return SizeOfPack->getPackLoc();
3031  if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3032    return PropRef->getLocation();
3033
3034  return E->getLocStart();
3035}
3036
3037extern "C" {
3038
3039unsigned clang_visitChildren(CXCursor parent,
3040                             CXCursorVisitor visitor,
3041                             CXClientData client_data) {
3042  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3043                          /*VisitPreprocessorLast=*/false);
3044  return CursorVis.VisitChildren(parent);
3045}
3046
3047#ifndef __has_feature
3048#define __has_feature(x) 0
3049#endif
3050#if __has_feature(blocks)
3051typedef enum CXChildVisitResult
3052     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3053
3054static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3055    CXClientData client_data) {
3056  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3057  return block(cursor, parent);
3058}
3059#else
3060// If we are compiled with a compiler that doesn't have native blocks support,
3061// define and call the block manually, so the
3062typedef struct _CXChildVisitResult
3063{
3064	void *isa;
3065	int flags;
3066	int reserved;
3067	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3068                                         CXCursor);
3069} *CXCursorVisitorBlock;
3070
3071static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3072    CXClientData client_data) {
3073  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3074  return block->invoke(block, cursor, parent);
3075}
3076#endif
3077
3078
3079unsigned clang_visitChildrenWithBlock(CXCursor parent,
3080                                      CXCursorVisitorBlock block) {
3081  return clang_visitChildren(parent, visitWithBlock, block);
3082}
3083
3084static CXString getDeclSpelling(const Decl *D) {
3085  if (!D)
3086    return createCXString("");
3087
3088  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3089  if (!ND) {
3090    if (const ObjCPropertyImplDecl *PropImpl =
3091            dyn_cast<ObjCPropertyImplDecl>(D))
3092      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3093        return createCXString(Property->getIdentifier()->getName());
3094
3095    if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3096      if (Module *Mod = ImportD->getImportedModule())
3097        return createCXString(Mod->getFullModuleName());
3098
3099    return createCXString("");
3100  }
3101
3102  if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3103    return createCXString(OMD->getSelector().getAsString());
3104
3105  if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3106    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3107    // and returns different names. NamedDecl returns the class name and
3108    // ObjCCategoryImplDecl returns the category name.
3109    return createCXString(CIMP->getIdentifier()->getNameStart());
3110
3111  if (isa<UsingDirectiveDecl>(D))
3112    return createCXString("");
3113
3114  SmallString<1024> S;
3115  llvm::raw_svector_ostream os(S);
3116  ND->printName(os);
3117
3118  return createCXString(os.str());
3119}
3120
3121CXString clang_getCursorSpelling(CXCursor C) {
3122  if (clang_isTranslationUnit(C.kind))
3123    return clang_getTranslationUnitSpelling(getCursorTU(C));
3124
3125  if (clang_isReference(C.kind)) {
3126    switch (C.kind) {
3127    case CXCursor_ObjCSuperClassRef: {
3128      const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3129      return createCXString(Super->getIdentifier()->getNameStart());
3130    }
3131    case CXCursor_ObjCClassRef: {
3132      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3133      return createCXString(Class->getIdentifier()->getNameStart());
3134    }
3135    case CXCursor_ObjCProtocolRef: {
3136      const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3137      assert(OID && "getCursorSpelling(): Missing protocol decl");
3138      return createCXString(OID->getIdentifier()->getNameStart());
3139    }
3140    case CXCursor_CXXBaseSpecifier: {
3141      const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3142      return createCXString(B->getType().getAsString());
3143    }
3144    case CXCursor_TypeRef: {
3145      const TypeDecl *Type = getCursorTypeRef(C).first;
3146      assert(Type && "Missing type decl");
3147
3148      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3149                              getAsString());
3150    }
3151    case CXCursor_TemplateRef: {
3152      const TemplateDecl *Template = getCursorTemplateRef(C).first;
3153      assert(Template && "Missing template decl");
3154
3155      return createCXString(Template->getNameAsString());
3156    }
3157
3158    case CXCursor_NamespaceRef: {
3159      const NamedDecl *NS = getCursorNamespaceRef(C).first;
3160      assert(NS && "Missing namespace decl");
3161
3162      return createCXString(NS->getNameAsString());
3163    }
3164
3165    case CXCursor_MemberRef: {
3166      const FieldDecl *Field = getCursorMemberRef(C).first;
3167      assert(Field && "Missing member decl");
3168
3169      return createCXString(Field->getNameAsString());
3170    }
3171
3172    case CXCursor_LabelRef: {
3173      const LabelStmt *Label = getCursorLabelRef(C).first;
3174      assert(Label && "Missing label");
3175
3176      return createCXString(Label->getName());
3177    }
3178
3179    case CXCursor_OverloadedDeclRef: {
3180      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3181      if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3182        if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3183          return createCXString(ND->getNameAsString());
3184        return createCXString("");
3185      }
3186      if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3187        return createCXString(E->getName().getAsString());
3188      OverloadedTemplateStorage *Ovl
3189        = Storage.get<OverloadedTemplateStorage*>();
3190      if (Ovl->size() == 0)
3191        return createCXString("");
3192      return createCXString((*Ovl->begin())->getNameAsString());
3193    }
3194
3195    case CXCursor_VariableRef: {
3196      const VarDecl *Var = getCursorVariableRef(C).first;
3197      assert(Var && "Missing variable decl");
3198
3199      return createCXString(Var->getNameAsString());
3200    }
3201
3202    default:
3203      return createCXString("<not implemented>");
3204    }
3205  }
3206
3207  if (clang_isExpression(C.kind)) {
3208    const Decl *D = getDeclFromExpr(getCursorExpr(C));
3209    if (D)
3210      return getDeclSpelling(D);
3211    return createCXString("");
3212  }
3213
3214  if (clang_isStatement(C.kind)) {
3215    Stmt *S = getCursorStmt(C);
3216    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3217      return createCXString(Label->getName());
3218
3219    return createCXString("");
3220  }
3221
3222  if (C.kind == CXCursor_MacroExpansion)
3223    return createCXString(getCursorMacroExpansion(C).getName()
3224                                                           ->getNameStart());
3225
3226  if (C.kind == CXCursor_MacroDefinition)
3227    return createCXString(getCursorMacroDefinition(C)->getName()
3228                                                           ->getNameStart());
3229
3230  if (C.kind == CXCursor_InclusionDirective)
3231    return createCXString(getCursorInclusionDirective(C)->getFileName());
3232
3233  if (clang_isDeclaration(C.kind))
3234    return getDeclSpelling(getCursorDecl(C));
3235
3236  if (C.kind == CXCursor_AnnotateAttr) {
3237    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3238    return createCXString(AA->getAnnotation());
3239  }
3240
3241  if (C.kind == CXCursor_AsmLabelAttr) {
3242    AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3243    return createCXString(AA->getLabel());
3244  }
3245
3246  return createCXString("");
3247}
3248
3249CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3250                                                unsigned pieceIndex,
3251                                                unsigned options) {
3252  if (clang_Cursor_isNull(C))
3253    return clang_getNullRange();
3254
3255  ASTContext &Ctx = getCursorContext(C);
3256
3257  if (clang_isStatement(C.kind)) {
3258    Stmt *S = getCursorStmt(C);
3259    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3260      if (pieceIndex > 0)
3261        return clang_getNullRange();
3262      return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3263    }
3264
3265    return clang_getNullRange();
3266  }
3267
3268  if (C.kind == CXCursor_ObjCMessageExpr) {
3269    if (ObjCMessageExpr *
3270          ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3271      if (pieceIndex >= ME->getNumSelectorLocs())
3272        return clang_getNullRange();
3273      return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3274    }
3275  }
3276
3277  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3278      C.kind == CXCursor_ObjCClassMethodDecl) {
3279    if (const ObjCMethodDecl *
3280          MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3281      if (pieceIndex >= MD->getNumSelectorLocs())
3282        return clang_getNullRange();
3283      return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3284    }
3285  }
3286
3287  if (C.kind == CXCursor_ObjCCategoryDecl ||
3288      C.kind == CXCursor_ObjCCategoryImplDecl) {
3289    if (pieceIndex > 0)
3290      return clang_getNullRange();
3291    if (const ObjCCategoryDecl *
3292          CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3293      return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3294    if (const ObjCCategoryImplDecl *
3295          CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3296      return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3297  }
3298
3299  if (C.kind == CXCursor_ModuleImportDecl) {
3300    if (pieceIndex > 0)
3301      return clang_getNullRange();
3302    if (const ImportDecl *ImportD =
3303            dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3304      ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3305      if (!Locs.empty())
3306        return cxloc::translateSourceRange(Ctx,
3307                                         SourceRange(Locs.front(), Locs.back()));
3308    }
3309    return clang_getNullRange();
3310  }
3311
3312  // FIXME: A CXCursor_InclusionDirective should give the location of the
3313  // filename, but we don't keep track of this.
3314
3315  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3316  // but we don't keep track of this.
3317
3318  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3319  // but we don't keep track of this.
3320
3321  // Default handling, give the location of the cursor.
3322
3323  if (pieceIndex > 0)
3324    return clang_getNullRange();
3325
3326  CXSourceLocation CXLoc = clang_getCursorLocation(C);
3327  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3328  return cxloc::translateSourceRange(Ctx, Loc);
3329}
3330
3331CXString clang_getCursorDisplayName(CXCursor C) {
3332  if (!clang_isDeclaration(C.kind))
3333    return clang_getCursorSpelling(C);
3334
3335  const Decl *D = getCursorDecl(C);
3336  if (!D)
3337    return createCXString("");
3338
3339  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3340  if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3341    D = FunTmpl->getTemplatedDecl();
3342
3343  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3344    SmallString<64> Str;
3345    llvm::raw_svector_ostream OS(Str);
3346    OS << *Function;
3347    if (Function->getPrimaryTemplate())
3348      OS << "<>";
3349    OS << "(";
3350    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3351      if (I)
3352        OS << ", ";
3353      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3354    }
3355
3356    if (Function->isVariadic()) {
3357      if (Function->getNumParams())
3358        OS << ", ";
3359      OS << "...";
3360    }
3361    OS << ")";
3362    return createCXString(OS.str());
3363  }
3364
3365  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3366    SmallString<64> Str;
3367    llvm::raw_svector_ostream OS(Str);
3368    OS << *ClassTemplate;
3369    OS << "<";
3370    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3371    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3372      if (I)
3373        OS << ", ";
3374
3375      NamedDecl *Param = Params->getParam(I);
3376      if (Param->getIdentifier()) {
3377        OS << Param->getIdentifier()->getName();
3378        continue;
3379      }
3380
3381      // There is no parameter name, which makes this tricky. Try to come up
3382      // with something useful that isn't too long.
3383      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3384        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3385      else if (NonTypeTemplateParmDecl *NTTP
3386                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3387        OS << NTTP->getType().getAsString(Policy);
3388      else
3389        OS << "template<...> class";
3390    }
3391
3392    OS << ">";
3393    return createCXString(OS.str());
3394  }
3395
3396  if (const ClassTemplateSpecializationDecl *ClassSpec
3397                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3398    // If the type was explicitly written, use that.
3399    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3400      return createCXString(TSInfo->getType().getAsString(Policy));
3401
3402    SmallString<64> Str;
3403    llvm::raw_svector_ostream OS(Str);
3404    OS << *ClassSpec;
3405    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3406                                      ClassSpec->getTemplateArgs().data(),
3407                                      ClassSpec->getTemplateArgs().size(),
3408                                                                Policy);
3409    return createCXString(OS.str());
3410  }
3411
3412  return clang_getCursorSpelling(C);
3413}
3414
3415CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3416  switch (Kind) {
3417  case CXCursor_FunctionDecl:
3418      return createCXString("FunctionDecl");
3419  case CXCursor_TypedefDecl:
3420      return createCXString("TypedefDecl");
3421  case CXCursor_EnumDecl:
3422      return createCXString("EnumDecl");
3423  case CXCursor_EnumConstantDecl:
3424      return createCXString("EnumConstantDecl");
3425  case CXCursor_StructDecl:
3426      return createCXString("StructDecl");
3427  case CXCursor_UnionDecl:
3428      return createCXString("UnionDecl");
3429  case CXCursor_ClassDecl:
3430      return createCXString("ClassDecl");
3431  case CXCursor_FieldDecl:
3432      return createCXString("FieldDecl");
3433  case CXCursor_VarDecl:
3434      return createCXString("VarDecl");
3435  case CXCursor_ParmDecl:
3436      return createCXString("ParmDecl");
3437  case CXCursor_ObjCInterfaceDecl:
3438      return createCXString("ObjCInterfaceDecl");
3439  case CXCursor_ObjCCategoryDecl:
3440      return createCXString("ObjCCategoryDecl");
3441  case CXCursor_ObjCProtocolDecl:
3442      return createCXString("ObjCProtocolDecl");
3443  case CXCursor_ObjCPropertyDecl:
3444      return createCXString("ObjCPropertyDecl");
3445  case CXCursor_ObjCIvarDecl:
3446      return createCXString("ObjCIvarDecl");
3447  case CXCursor_ObjCInstanceMethodDecl:
3448      return createCXString("ObjCInstanceMethodDecl");
3449  case CXCursor_ObjCClassMethodDecl:
3450      return createCXString("ObjCClassMethodDecl");
3451  case CXCursor_ObjCImplementationDecl:
3452      return createCXString("ObjCImplementationDecl");
3453  case CXCursor_ObjCCategoryImplDecl:
3454      return createCXString("ObjCCategoryImplDecl");
3455  case CXCursor_CXXMethod:
3456      return createCXString("CXXMethod");
3457  case CXCursor_UnexposedDecl:
3458      return createCXString("UnexposedDecl");
3459  case CXCursor_ObjCSuperClassRef:
3460      return createCXString("ObjCSuperClassRef");
3461  case CXCursor_ObjCProtocolRef:
3462      return createCXString("ObjCProtocolRef");
3463  case CXCursor_ObjCClassRef:
3464      return createCXString("ObjCClassRef");
3465  case CXCursor_TypeRef:
3466      return createCXString("TypeRef");
3467  case CXCursor_TemplateRef:
3468      return createCXString("TemplateRef");
3469  case CXCursor_NamespaceRef:
3470    return createCXString("NamespaceRef");
3471  case CXCursor_MemberRef:
3472    return createCXString("MemberRef");
3473  case CXCursor_LabelRef:
3474    return createCXString("LabelRef");
3475  case CXCursor_OverloadedDeclRef:
3476    return createCXString("OverloadedDeclRef");
3477  case CXCursor_VariableRef:
3478    return createCXString("VariableRef");
3479  case CXCursor_IntegerLiteral:
3480      return createCXString("IntegerLiteral");
3481  case CXCursor_FloatingLiteral:
3482      return createCXString("FloatingLiteral");
3483  case CXCursor_ImaginaryLiteral:
3484      return createCXString("ImaginaryLiteral");
3485  case CXCursor_StringLiteral:
3486      return createCXString("StringLiteral");
3487  case CXCursor_CharacterLiteral:
3488      return createCXString("CharacterLiteral");
3489  case CXCursor_ParenExpr:
3490      return createCXString("ParenExpr");
3491  case CXCursor_UnaryOperator:
3492      return createCXString("UnaryOperator");
3493  case CXCursor_ArraySubscriptExpr:
3494      return createCXString("ArraySubscriptExpr");
3495  case CXCursor_BinaryOperator:
3496      return createCXString("BinaryOperator");
3497  case CXCursor_CompoundAssignOperator:
3498      return createCXString("CompoundAssignOperator");
3499  case CXCursor_ConditionalOperator:
3500      return createCXString("ConditionalOperator");
3501  case CXCursor_CStyleCastExpr:
3502      return createCXString("CStyleCastExpr");
3503  case CXCursor_CompoundLiteralExpr:
3504      return createCXString("CompoundLiteralExpr");
3505  case CXCursor_InitListExpr:
3506      return createCXString("InitListExpr");
3507  case CXCursor_AddrLabelExpr:
3508      return createCXString("AddrLabelExpr");
3509  case CXCursor_StmtExpr:
3510      return createCXString("StmtExpr");
3511  case CXCursor_GenericSelectionExpr:
3512      return createCXString("GenericSelectionExpr");
3513  case CXCursor_GNUNullExpr:
3514      return createCXString("GNUNullExpr");
3515  case CXCursor_CXXStaticCastExpr:
3516      return createCXString("CXXStaticCastExpr");
3517  case CXCursor_CXXDynamicCastExpr:
3518      return createCXString("CXXDynamicCastExpr");
3519  case CXCursor_CXXReinterpretCastExpr:
3520      return createCXString("CXXReinterpretCastExpr");
3521  case CXCursor_CXXConstCastExpr:
3522      return createCXString("CXXConstCastExpr");
3523  case CXCursor_CXXFunctionalCastExpr:
3524      return createCXString("CXXFunctionalCastExpr");
3525  case CXCursor_CXXTypeidExpr:
3526      return createCXString("CXXTypeidExpr");
3527  case CXCursor_CXXBoolLiteralExpr:
3528      return createCXString("CXXBoolLiteralExpr");
3529  case CXCursor_CXXNullPtrLiteralExpr:
3530      return createCXString("CXXNullPtrLiteralExpr");
3531  case CXCursor_CXXThisExpr:
3532      return createCXString("CXXThisExpr");
3533  case CXCursor_CXXThrowExpr:
3534      return createCXString("CXXThrowExpr");
3535  case CXCursor_CXXNewExpr:
3536      return createCXString("CXXNewExpr");
3537  case CXCursor_CXXDeleteExpr:
3538      return createCXString("CXXDeleteExpr");
3539  case CXCursor_UnaryExpr:
3540      return createCXString("UnaryExpr");
3541  case CXCursor_ObjCStringLiteral:
3542      return createCXString("ObjCStringLiteral");
3543  case CXCursor_ObjCBoolLiteralExpr:
3544      return createCXString("ObjCBoolLiteralExpr");
3545  case CXCursor_ObjCEncodeExpr:
3546      return createCXString("ObjCEncodeExpr");
3547  case CXCursor_ObjCSelectorExpr:
3548      return createCXString("ObjCSelectorExpr");
3549  case CXCursor_ObjCProtocolExpr:
3550      return createCXString("ObjCProtocolExpr");
3551  case CXCursor_ObjCBridgedCastExpr:
3552      return createCXString("ObjCBridgedCastExpr");
3553  case CXCursor_BlockExpr:
3554      return createCXString("BlockExpr");
3555  case CXCursor_PackExpansionExpr:
3556      return createCXString("PackExpansionExpr");
3557  case CXCursor_SizeOfPackExpr:
3558      return createCXString("SizeOfPackExpr");
3559  case CXCursor_LambdaExpr:
3560    return createCXString("LambdaExpr");
3561  case CXCursor_UnexposedExpr:
3562      return createCXString("UnexposedExpr");
3563  case CXCursor_DeclRefExpr:
3564      return createCXString("DeclRefExpr");
3565  case CXCursor_MemberRefExpr:
3566      return createCXString("MemberRefExpr");
3567  case CXCursor_CallExpr:
3568      return createCXString("CallExpr");
3569  case CXCursor_ObjCMessageExpr:
3570      return createCXString("ObjCMessageExpr");
3571  case CXCursor_UnexposedStmt:
3572      return createCXString("UnexposedStmt");
3573  case CXCursor_DeclStmt:
3574      return createCXString("DeclStmt");
3575  case CXCursor_LabelStmt:
3576      return createCXString("LabelStmt");
3577  case CXCursor_CompoundStmt:
3578      return createCXString("CompoundStmt");
3579  case CXCursor_CaseStmt:
3580      return createCXString("CaseStmt");
3581  case CXCursor_DefaultStmt:
3582      return createCXString("DefaultStmt");
3583  case CXCursor_IfStmt:
3584      return createCXString("IfStmt");
3585  case CXCursor_SwitchStmt:
3586      return createCXString("SwitchStmt");
3587  case CXCursor_WhileStmt:
3588      return createCXString("WhileStmt");
3589  case CXCursor_DoStmt:
3590      return createCXString("DoStmt");
3591  case CXCursor_ForStmt:
3592      return createCXString("ForStmt");
3593  case CXCursor_GotoStmt:
3594      return createCXString("GotoStmt");
3595  case CXCursor_IndirectGotoStmt:
3596      return createCXString("IndirectGotoStmt");
3597  case CXCursor_ContinueStmt:
3598      return createCXString("ContinueStmt");
3599  case CXCursor_BreakStmt:
3600      return createCXString("BreakStmt");
3601  case CXCursor_ReturnStmt:
3602      return createCXString("ReturnStmt");
3603  case CXCursor_GCCAsmStmt:
3604      return createCXString("GCCAsmStmt");
3605  case CXCursor_MSAsmStmt:
3606      return createCXString("MSAsmStmt");
3607  case CXCursor_ObjCAtTryStmt:
3608      return createCXString("ObjCAtTryStmt");
3609  case CXCursor_ObjCAtCatchStmt:
3610      return createCXString("ObjCAtCatchStmt");
3611  case CXCursor_ObjCAtFinallyStmt:
3612      return createCXString("ObjCAtFinallyStmt");
3613  case CXCursor_ObjCAtThrowStmt:
3614      return createCXString("ObjCAtThrowStmt");
3615  case CXCursor_ObjCAtSynchronizedStmt:
3616      return createCXString("ObjCAtSynchronizedStmt");
3617  case CXCursor_ObjCAutoreleasePoolStmt:
3618      return createCXString("ObjCAutoreleasePoolStmt");
3619  case CXCursor_ObjCForCollectionStmt:
3620      return createCXString("ObjCForCollectionStmt");
3621  case CXCursor_CXXCatchStmt:
3622      return createCXString("CXXCatchStmt");
3623  case CXCursor_CXXTryStmt:
3624      return createCXString("CXXTryStmt");
3625  case CXCursor_CXXForRangeStmt:
3626      return createCXString("CXXForRangeStmt");
3627  case CXCursor_SEHTryStmt:
3628      return createCXString("SEHTryStmt");
3629  case CXCursor_SEHExceptStmt:
3630      return createCXString("SEHExceptStmt");
3631  case CXCursor_SEHFinallyStmt:
3632      return createCXString("SEHFinallyStmt");
3633  case CXCursor_NullStmt:
3634      return createCXString("NullStmt");
3635  case CXCursor_InvalidFile:
3636      return createCXString("InvalidFile");
3637  case CXCursor_InvalidCode:
3638    return createCXString("InvalidCode");
3639  case CXCursor_NoDeclFound:
3640      return createCXString("NoDeclFound");
3641  case CXCursor_NotImplemented:
3642      return createCXString("NotImplemented");
3643  case CXCursor_TranslationUnit:
3644      return createCXString("TranslationUnit");
3645  case CXCursor_UnexposedAttr:
3646      return createCXString("UnexposedAttr");
3647  case CXCursor_IBActionAttr:
3648      return createCXString("attribute(ibaction)");
3649  case CXCursor_IBOutletAttr:
3650     return createCXString("attribute(iboutlet)");
3651  case CXCursor_IBOutletCollectionAttr:
3652      return createCXString("attribute(iboutletcollection)");
3653  case CXCursor_CXXFinalAttr:
3654      return createCXString("attribute(final)");
3655  case CXCursor_CXXOverrideAttr:
3656      return createCXString("attribute(override)");
3657  case CXCursor_AnnotateAttr:
3658    return createCXString("attribute(annotate)");
3659  case CXCursor_AsmLabelAttr:
3660    return createCXString("asm label");
3661  case CXCursor_PreprocessingDirective:
3662    return createCXString("preprocessing directive");
3663  case CXCursor_MacroDefinition:
3664    return createCXString("macro definition");
3665  case CXCursor_MacroExpansion:
3666    return createCXString("macro expansion");
3667  case CXCursor_InclusionDirective:
3668    return createCXString("inclusion directive");
3669  case CXCursor_Namespace:
3670    return createCXString("Namespace");
3671  case CXCursor_LinkageSpec:
3672    return createCXString("LinkageSpec");
3673  case CXCursor_CXXBaseSpecifier:
3674    return createCXString("C++ base class specifier");
3675  case CXCursor_Constructor:
3676    return createCXString("CXXConstructor");
3677  case CXCursor_Destructor:
3678    return createCXString("CXXDestructor");
3679  case CXCursor_ConversionFunction:
3680    return createCXString("CXXConversion");
3681  case CXCursor_TemplateTypeParameter:
3682    return createCXString("TemplateTypeParameter");
3683  case CXCursor_NonTypeTemplateParameter:
3684    return createCXString("NonTypeTemplateParameter");
3685  case CXCursor_TemplateTemplateParameter:
3686    return createCXString("TemplateTemplateParameter");
3687  case CXCursor_FunctionTemplate:
3688    return createCXString("FunctionTemplate");
3689  case CXCursor_ClassTemplate:
3690    return createCXString("ClassTemplate");
3691  case CXCursor_ClassTemplatePartialSpecialization:
3692    return createCXString("ClassTemplatePartialSpecialization");
3693  case CXCursor_NamespaceAlias:
3694    return createCXString("NamespaceAlias");
3695  case CXCursor_UsingDirective:
3696    return createCXString("UsingDirective");
3697  case CXCursor_UsingDeclaration:
3698    return createCXString("UsingDeclaration");
3699  case CXCursor_TypeAliasDecl:
3700    return createCXString("TypeAliasDecl");
3701  case CXCursor_ObjCSynthesizeDecl:
3702    return createCXString("ObjCSynthesizeDecl");
3703  case CXCursor_ObjCDynamicDecl:
3704    return createCXString("ObjCDynamicDecl");
3705  case CXCursor_CXXAccessSpecifier:
3706    return createCXString("CXXAccessSpecifier");
3707  case CXCursor_ModuleImportDecl:
3708    return createCXString("ModuleImport");
3709  }
3710
3711  llvm_unreachable("Unhandled CXCursorKind");
3712}
3713
3714struct GetCursorData {
3715  SourceLocation TokenBeginLoc;
3716  bool PointsAtMacroArgExpansion;
3717  bool VisitedObjCPropertyImplDecl;
3718  SourceLocation VisitedDeclaratorDeclStartLoc;
3719  CXCursor &BestCursor;
3720
3721  GetCursorData(SourceManager &SM,
3722                SourceLocation tokenBegin, CXCursor &outputCursor)
3723    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3724    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3725    VisitedObjCPropertyImplDecl = false;
3726  }
3727};
3728
3729static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3730                                                CXCursor parent,
3731                                                CXClientData client_data) {
3732  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3733  CXCursor *BestCursor = &Data->BestCursor;
3734
3735  // If we point inside a macro argument we should provide info of what the
3736  // token is so use the actual cursor, don't replace it with a macro expansion
3737  // cursor.
3738  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3739    return CXChildVisit_Recurse;
3740
3741  if (clang_isDeclaration(cursor.kind)) {
3742    // Avoid having the implicit methods override the property decls.
3743    if (const ObjCMethodDecl *MD
3744          = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
3745      if (MD->isImplicit())
3746        return CXChildVisit_Break;
3747
3748    } else if (const ObjCInterfaceDecl *ID
3749                 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3750      // Check that when we have multiple @class references in the same line,
3751      // that later ones do not override the previous ones.
3752      // If we have:
3753      // @class Foo, Bar;
3754      // source ranges for both start at '@', so 'Bar' will end up overriding
3755      // 'Foo' even though the cursor location was at 'Foo'.
3756      if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3757          BestCursor->kind == CXCursor_ObjCClassRef)
3758        if (const ObjCInterfaceDecl *PrevID
3759             = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3760         if (PrevID != ID &&
3761             !PrevID->isThisDeclarationADefinition() &&
3762             !ID->isThisDeclarationADefinition())
3763           return CXChildVisit_Break;
3764        }
3765
3766    } else if (const DeclaratorDecl *DD
3767                    = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3768      SourceLocation StartLoc = DD->getSourceRange().getBegin();
3769      // Check that when we have multiple declarators in the same line,
3770      // that later ones do not override the previous ones.
3771      // If we have:
3772      // int Foo, Bar;
3773      // source ranges for both start at 'int', so 'Bar' will end up overriding
3774      // 'Foo' even though the cursor location was at 'Foo'.
3775      if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3776        return CXChildVisit_Break;
3777      Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3778
3779    } else if (const ObjCPropertyImplDecl *PropImp
3780              = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3781      (void)PropImp;
3782      // Check that when we have multiple @synthesize in the same line,
3783      // that later ones do not override the previous ones.
3784      // If we have:
3785      // @synthesize Foo, Bar;
3786      // source ranges for both start at '@', so 'Bar' will end up overriding
3787      // 'Foo' even though the cursor location was at 'Foo'.
3788      if (Data->VisitedObjCPropertyImplDecl)
3789        return CXChildVisit_Break;
3790      Data->VisitedObjCPropertyImplDecl = true;
3791    }
3792  }
3793
3794  if (clang_isExpression(cursor.kind) &&
3795      clang_isDeclaration(BestCursor->kind)) {
3796    if (const Decl *D = getCursorDecl(*BestCursor)) {
3797      // Avoid having the cursor of an expression replace the declaration cursor
3798      // when the expression source range overlaps the declaration range.
3799      // This can happen for C++ constructor expressions whose range generally
3800      // include the variable declaration, e.g.:
3801      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3802      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3803          D->getLocation() == Data->TokenBeginLoc)
3804        return CXChildVisit_Break;
3805    }
3806  }
3807
3808  // If our current best cursor is the construction of a temporary object,
3809  // don't replace that cursor with a type reference, because we want
3810  // clang_getCursor() to point at the constructor.
3811  if (clang_isExpression(BestCursor->kind) &&
3812      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3813      cursor.kind == CXCursor_TypeRef) {
3814    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3815    // as having the actual point on the type reference.
3816    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3817    return CXChildVisit_Recurse;
3818  }
3819
3820  *BestCursor = cursor;
3821  return CXChildVisit_Recurse;
3822}
3823
3824CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3825  if (!TU)
3826    return clang_getNullCursor();
3827
3828  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3829  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3830
3831  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3832  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3833
3834  LOG_FUNC_SECTION {
3835    CXFile SearchFile;
3836    unsigned SearchLine, SearchColumn;
3837    CXFile ResultFile;
3838    unsigned ResultLine, ResultColumn;
3839    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3840    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3841    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3842
3843    clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3844    clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
3845                               &ResultColumn, 0);
3846    SearchFileName = clang_getFileName(SearchFile);
3847    ResultFileName = clang_getFileName(ResultFile);
3848    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3849    USR = clang_getCursorUSR(Result);
3850    *Log << llvm::format("(%s:%d:%d) = %s",
3851                   clang_getCString(SearchFileName), SearchLine, SearchColumn,
3852                   clang_getCString(KindSpelling))
3853        << llvm::format("(%s:%d:%d):%s%s",
3854                     clang_getCString(ResultFileName), ResultLine, ResultColumn,
3855                     clang_getCString(USR), IsDef);
3856    clang_disposeString(SearchFileName);
3857    clang_disposeString(ResultFileName);
3858    clang_disposeString(KindSpelling);
3859    clang_disposeString(USR);
3860
3861    CXCursor Definition = clang_getCursorDefinition(Result);
3862    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3863      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3864      CXString DefinitionKindSpelling
3865                                = clang_getCursorKindSpelling(Definition.kind);
3866      CXFile DefinitionFile;
3867      unsigned DefinitionLine, DefinitionColumn;
3868      clang_getFileLocation(DefinitionLoc, &DefinitionFile,
3869                                 &DefinitionLine, &DefinitionColumn, 0);
3870      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3871      *Log << llvm::format("  -> %s(%s:%d:%d)",
3872                     clang_getCString(DefinitionKindSpelling),
3873                     clang_getCString(DefinitionFileName),
3874                     DefinitionLine, DefinitionColumn);
3875      clang_disposeString(DefinitionFileName);
3876      clang_disposeString(DefinitionKindSpelling);
3877    }
3878  }
3879
3880  return Result;
3881}
3882
3883CXCursor clang_getNullCursor(void) {
3884  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3885}
3886
3887unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3888  // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
3889  // can't set consistently. For example, when visiting a DeclStmt we will set
3890  // it but we don't set it on the result of clang_getCursorDefinition for
3891  // a reference of the same declaration.
3892  // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
3893  // when visiting a DeclStmt currently, the AST should be enhanced to be able
3894  // to provide that kind of info.
3895  if (clang_isDeclaration(X.kind))
3896    X.data[1] = 0;
3897  if (clang_isDeclaration(Y.kind))
3898    Y.data[1] = 0;
3899
3900  return X == Y;
3901}
3902
3903unsigned clang_hashCursor(CXCursor C) {
3904  unsigned Index = 0;
3905  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3906    Index = 1;
3907
3908  return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
3909                                        std::make_pair(C.kind, C.data[Index]));
3910}
3911
3912unsigned clang_isInvalid(enum CXCursorKind K) {
3913  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3914}
3915
3916unsigned clang_isDeclaration(enum CXCursorKind K) {
3917  return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3918         (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
3919}
3920
3921unsigned clang_isReference(enum CXCursorKind K) {
3922  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3923}
3924
3925unsigned clang_isExpression(enum CXCursorKind K) {
3926  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3927}
3928
3929unsigned clang_isStatement(enum CXCursorKind K) {
3930  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3931}
3932
3933unsigned clang_isAttribute(enum CXCursorKind K) {
3934    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3935}
3936
3937unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3938  return K == CXCursor_TranslationUnit;
3939}
3940
3941unsigned clang_isPreprocessing(enum CXCursorKind K) {
3942  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3943}
3944
3945unsigned clang_isUnexposed(enum CXCursorKind K) {
3946  switch (K) {
3947    case CXCursor_UnexposedDecl:
3948    case CXCursor_UnexposedExpr:
3949    case CXCursor_UnexposedStmt:
3950    case CXCursor_UnexposedAttr:
3951      return true;
3952    default:
3953      return false;
3954  }
3955}
3956
3957CXCursorKind clang_getCursorKind(CXCursor C) {
3958  return C.kind;
3959}
3960
3961CXSourceLocation clang_getCursorLocation(CXCursor C) {
3962  if (clang_isReference(C.kind)) {
3963    switch (C.kind) {
3964    case CXCursor_ObjCSuperClassRef: {
3965      std::pair<const ObjCInterfaceDecl *, SourceLocation> P
3966        = getCursorObjCSuperClassRef(C);
3967      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3968    }
3969
3970    case CXCursor_ObjCProtocolRef: {
3971      std::pair<const ObjCProtocolDecl *, SourceLocation> P
3972        = getCursorObjCProtocolRef(C);
3973      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3974    }
3975
3976    case CXCursor_ObjCClassRef: {
3977      std::pair<const ObjCInterfaceDecl *, SourceLocation> P
3978        = getCursorObjCClassRef(C);
3979      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3980    }
3981
3982    case CXCursor_TypeRef: {
3983      std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3984      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3985    }
3986
3987    case CXCursor_TemplateRef: {
3988      std::pair<const TemplateDecl *, SourceLocation> P =
3989          getCursorTemplateRef(C);
3990      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3991    }
3992
3993    case CXCursor_NamespaceRef: {
3994      std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3995      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3996    }
3997
3998    case CXCursor_MemberRef: {
3999      std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4000      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4001    }
4002
4003    case CXCursor_VariableRef: {
4004      std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4005      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4006    }
4007
4008    case CXCursor_CXXBaseSpecifier: {
4009      const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4010      if (!BaseSpec)
4011        return clang_getNullLocation();
4012
4013      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4014        return cxloc::translateSourceLocation(getCursorContext(C),
4015                                            TSInfo->getTypeLoc().getBeginLoc());
4016
4017      return cxloc::translateSourceLocation(getCursorContext(C),
4018                                        BaseSpec->getLocStart());
4019    }
4020
4021    case CXCursor_LabelRef: {
4022      std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4023      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4024    }
4025
4026    case CXCursor_OverloadedDeclRef:
4027      return cxloc::translateSourceLocation(getCursorContext(C),
4028                                          getCursorOverloadedDeclRef(C).second);
4029
4030    default:
4031      // FIXME: Need a way to enumerate all non-reference cases.
4032      llvm_unreachable("Missed a reference kind");
4033    }
4034  }
4035
4036  if (clang_isExpression(C.kind))
4037    return cxloc::translateSourceLocation(getCursorContext(C),
4038                                   getLocationFromExpr(getCursorExpr(C)));
4039
4040  if (clang_isStatement(C.kind))
4041    return cxloc::translateSourceLocation(getCursorContext(C),
4042                                          getCursorStmt(C)->getLocStart());
4043
4044  if (C.kind == CXCursor_PreprocessingDirective) {
4045    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4046    return cxloc::translateSourceLocation(getCursorContext(C), L);
4047  }
4048
4049  if (C.kind == CXCursor_MacroExpansion) {
4050    SourceLocation L
4051      = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4052    return cxloc::translateSourceLocation(getCursorContext(C), L);
4053  }
4054
4055  if (C.kind == CXCursor_MacroDefinition) {
4056    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4057    return cxloc::translateSourceLocation(getCursorContext(C), L);
4058  }
4059
4060  if (C.kind == CXCursor_InclusionDirective) {
4061    SourceLocation L
4062      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4063    return cxloc::translateSourceLocation(getCursorContext(C), L);
4064  }
4065
4066  if (!clang_isDeclaration(C.kind))
4067    return clang_getNullLocation();
4068
4069  const Decl *D = getCursorDecl(C);
4070  if (!D)
4071    return clang_getNullLocation();
4072
4073  SourceLocation Loc = D->getLocation();
4074  // FIXME: Multiple variables declared in a single declaration
4075  // currently lack the information needed to correctly determine their
4076  // ranges when accounting for the type-specifier.  We use context
4077  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4078  // and if so, whether it is the first decl.
4079  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4080    if (!cxcursor::isFirstInDeclGroup(C))
4081      Loc = VD->getLocation();
4082  }
4083
4084  // For ObjC methods, give the start location of the method name.
4085  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4086    Loc = MD->getSelectorStartLoc();
4087
4088  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4089}
4090
4091} // end extern "C"
4092
4093CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4094  assert(TU);
4095
4096  // Guard against an invalid SourceLocation, or we may assert in one
4097  // of the following calls.
4098  if (SLoc.isInvalid())
4099    return clang_getNullCursor();
4100
4101  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4102
4103  // Translate the given source location to make it point at the beginning of
4104  // the token under the cursor.
4105  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4106                                    CXXUnit->getASTContext().getLangOpts());
4107
4108  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4109  if (SLoc.isValid()) {
4110    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4111    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4112                            /*VisitPreprocessorLast=*/true,
4113                            /*VisitIncludedEntities=*/false,
4114                            SourceLocation(SLoc));
4115    CursorVis.visitFileRegion();
4116  }
4117
4118  return Result;
4119}
4120
4121static SourceRange getRawCursorExtent(CXCursor C) {
4122  if (clang_isReference(C.kind)) {
4123    switch (C.kind) {
4124    case CXCursor_ObjCSuperClassRef:
4125      return  getCursorObjCSuperClassRef(C).second;
4126
4127    case CXCursor_ObjCProtocolRef:
4128      return getCursorObjCProtocolRef(C).second;
4129
4130    case CXCursor_ObjCClassRef:
4131      return getCursorObjCClassRef(C).second;
4132
4133    case CXCursor_TypeRef:
4134      return getCursorTypeRef(C).second;
4135
4136    case CXCursor_TemplateRef:
4137      return getCursorTemplateRef(C).second;
4138
4139    case CXCursor_NamespaceRef:
4140      return getCursorNamespaceRef(C).second;
4141
4142    case CXCursor_MemberRef:
4143      return getCursorMemberRef(C).second;
4144
4145    case CXCursor_CXXBaseSpecifier:
4146      return getCursorCXXBaseSpecifier(C)->getSourceRange();
4147
4148    case CXCursor_LabelRef:
4149      return getCursorLabelRef(C).second;
4150
4151    case CXCursor_OverloadedDeclRef:
4152      return getCursorOverloadedDeclRef(C).second;
4153
4154    case CXCursor_VariableRef:
4155      return getCursorVariableRef(C).second;
4156
4157    default:
4158      // FIXME: Need a way to enumerate all non-reference cases.
4159      llvm_unreachable("Missed a reference kind");
4160    }
4161  }
4162
4163  if (clang_isExpression(C.kind))
4164    return getCursorExpr(C)->getSourceRange();
4165
4166  if (clang_isStatement(C.kind))
4167    return getCursorStmt(C)->getSourceRange();
4168
4169  if (clang_isAttribute(C.kind))
4170    return getCursorAttr(C)->getRange();
4171
4172  if (C.kind == CXCursor_PreprocessingDirective)
4173    return cxcursor::getCursorPreprocessingDirective(C);
4174
4175  if (C.kind == CXCursor_MacroExpansion) {
4176    ASTUnit *TU = getCursorASTUnit(C);
4177    SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4178    return TU->mapRangeFromPreamble(Range);
4179  }
4180
4181  if (C.kind == CXCursor_MacroDefinition) {
4182    ASTUnit *TU = getCursorASTUnit(C);
4183    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4184    return TU->mapRangeFromPreamble(Range);
4185  }
4186
4187  if (C.kind == CXCursor_InclusionDirective) {
4188    ASTUnit *TU = getCursorASTUnit(C);
4189    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4190    return TU->mapRangeFromPreamble(Range);
4191  }
4192
4193  if (C.kind == CXCursor_TranslationUnit) {
4194    ASTUnit *TU = getCursorASTUnit(C);
4195    FileID MainID = TU->getSourceManager().getMainFileID();
4196    SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4197    SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4198    return SourceRange(Start, End);
4199  }
4200
4201  if (clang_isDeclaration(C.kind)) {
4202    const Decl *D = cxcursor::getCursorDecl(C);
4203    if (!D)
4204      return SourceRange();
4205
4206    SourceRange R = D->getSourceRange();
4207    // FIXME: Multiple variables declared in a single declaration
4208    // currently lack the information needed to correctly determine their
4209    // ranges when accounting for the type-specifier.  We use context
4210    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4211    // and if so, whether it is the first decl.
4212    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4213      if (!cxcursor::isFirstInDeclGroup(C))
4214        R.setBegin(VD->getLocation());
4215    }
4216    return R;
4217  }
4218  return SourceRange();
4219}
4220
4221/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4222/// the decl-specifier-seq for declarations.
4223static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4224  if (clang_isDeclaration(C.kind)) {
4225    const Decl *D = cxcursor::getCursorDecl(C);
4226    if (!D)
4227      return SourceRange();
4228
4229    SourceRange R = D->getSourceRange();
4230
4231    // Adjust the start of the location for declarations preceded by
4232    // declaration specifiers.
4233    SourceLocation StartLoc;
4234    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4235      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4236        StartLoc = TI->getTypeLoc().getLocStart();
4237    } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4238      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4239        StartLoc = TI->getTypeLoc().getLocStart();
4240    }
4241
4242    if (StartLoc.isValid() && R.getBegin().isValid() &&
4243        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4244      R.setBegin(StartLoc);
4245
4246    // FIXME: Multiple variables declared in a single declaration
4247    // currently lack the information needed to correctly determine their
4248    // ranges when accounting for the type-specifier.  We use context
4249    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4250    // and if so, whether it is the first decl.
4251    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4252      if (!cxcursor::isFirstInDeclGroup(C))
4253        R.setBegin(VD->getLocation());
4254    }
4255
4256    return R;
4257  }
4258
4259  return getRawCursorExtent(C);
4260}
4261
4262extern "C" {
4263
4264CXSourceRange clang_getCursorExtent(CXCursor C) {
4265  SourceRange R = getRawCursorExtent(C);
4266  if (R.isInvalid())
4267    return clang_getNullRange();
4268
4269  return cxloc::translateSourceRange(getCursorContext(C), R);
4270}
4271
4272CXCursor clang_getCursorReferenced(CXCursor C) {
4273  if (clang_isInvalid(C.kind))
4274    return clang_getNullCursor();
4275
4276  CXTranslationUnit tu = getCursorTU(C);
4277  if (clang_isDeclaration(C.kind)) {
4278    const Decl *D = getCursorDecl(C);
4279    if (!D)
4280      return clang_getNullCursor();
4281    if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4282      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4283    if (const ObjCPropertyImplDecl *PropImpl =
4284            dyn_cast<ObjCPropertyImplDecl>(D))
4285      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4286        return MakeCXCursor(Property, tu);
4287
4288    return C;
4289  }
4290
4291  if (clang_isExpression(C.kind)) {
4292    const Expr *E = getCursorExpr(C);
4293    const Decl *D = getDeclFromExpr(E);
4294    if (D) {
4295      CXCursor declCursor = MakeCXCursor(D, tu);
4296      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4297                                               declCursor);
4298      return declCursor;
4299    }
4300
4301    if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4302      return MakeCursorOverloadedDeclRef(Ovl, tu);
4303
4304    return clang_getNullCursor();
4305  }
4306
4307  if (clang_isStatement(C.kind)) {
4308    Stmt *S = getCursorStmt(C);
4309    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4310      if (LabelDecl *label = Goto->getLabel())
4311        if (LabelStmt *labelS = label->getStmt())
4312        return MakeCXCursor(labelS, getCursorDecl(C), tu);
4313
4314    return clang_getNullCursor();
4315  }
4316
4317  if (C.kind == CXCursor_MacroExpansion) {
4318    if (const MacroDefinition *Def = getCursorMacroExpansion(C).getDefinition())
4319      return MakeMacroDefinitionCursor(Def, tu);
4320  }
4321
4322  if (!clang_isReference(C.kind))
4323    return clang_getNullCursor();
4324
4325  switch (C.kind) {
4326    case CXCursor_ObjCSuperClassRef:
4327      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4328
4329    case CXCursor_ObjCProtocolRef: {
4330      const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4331      if (const ObjCProtocolDecl *Def = Prot->getDefinition())
4332        return MakeCXCursor(Def, tu);
4333
4334      return MakeCXCursor(Prot, tu);
4335    }
4336
4337    case CXCursor_ObjCClassRef: {
4338      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4339      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
4340        return MakeCXCursor(Def, tu);
4341
4342      return MakeCXCursor(Class, tu);
4343    }
4344
4345    case CXCursor_TypeRef:
4346      return MakeCXCursor(getCursorTypeRef(C).first, tu );
4347
4348    case CXCursor_TemplateRef:
4349      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4350
4351    case CXCursor_NamespaceRef:
4352      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4353
4354    case CXCursor_MemberRef:
4355      return MakeCXCursor(getCursorMemberRef(C).first, tu );
4356
4357    case CXCursor_CXXBaseSpecifier: {
4358      const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4359      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4360                                                         tu ));
4361    }
4362
4363    case CXCursor_LabelRef:
4364      // FIXME: We end up faking the "parent" declaration here because we
4365      // don't want to make CXCursor larger.
4366      return MakeCXCursor(getCursorLabelRef(C).first,
4367               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4368                          .getTranslationUnitDecl(),
4369                          tu);
4370
4371    case CXCursor_OverloadedDeclRef:
4372      return C;
4373
4374    case CXCursor_VariableRef:
4375      return MakeCXCursor(getCursorVariableRef(C).first, tu);
4376
4377    default:
4378      // We would prefer to enumerate all non-reference cursor kinds here.
4379      llvm_unreachable("Unhandled reference cursor kind");
4380  }
4381}
4382
4383CXCursor clang_getCursorDefinition(CXCursor C) {
4384  if (clang_isInvalid(C.kind))
4385    return clang_getNullCursor();
4386
4387  CXTranslationUnit TU = getCursorTU(C);
4388
4389  bool WasReference = false;
4390  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4391    C = clang_getCursorReferenced(C);
4392    WasReference = true;
4393  }
4394
4395  if (C.kind == CXCursor_MacroExpansion)
4396    return clang_getCursorReferenced(C);
4397
4398  if (!clang_isDeclaration(C.kind))
4399    return clang_getNullCursor();
4400
4401  const Decl *D = getCursorDecl(C);
4402  if (!D)
4403    return clang_getNullCursor();
4404
4405  switch (D->getKind()) {
4406  // Declaration kinds that don't really separate the notions of
4407  // declaration and definition.
4408  case Decl::Namespace:
4409  case Decl::Typedef:
4410  case Decl::TypeAlias:
4411  case Decl::TypeAliasTemplate:
4412  case Decl::TemplateTypeParm:
4413  case Decl::EnumConstant:
4414  case Decl::Field:
4415  case Decl::IndirectField:
4416  case Decl::ObjCIvar:
4417  case Decl::ObjCAtDefsField:
4418  case Decl::ImplicitParam:
4419  case Decl::ParmVar:
4420  case Decl::NonTypeTemplateParm:
4421  case Decl::TemplateTemplateParm:
4422  case Decl::ObjCCategoryImpl:
4423  case Decl::ObjCImplementation:
4424  case Decl::AccessSpec:
4425  case Decl::LinkageSpec:
4426  case Decl::ObjCPropertyImpl:
4427  case Decl::FileScopeAsm:
4428  case Decl::StaticAssert:
4429  case Decl::Block:
4430  case Decl::Label:  // FIXME: Is this right??
4431  case Decl::ClassScopeFunctionSpecialization:
4432  case Decl::Import:
4433    return C;
4434
4435  // Declaration kinds that don't make any sense here, but are
4436  // nonetheless harmless.
4437  case Decl::TranslationUnit:
4438    break;
4439
4440  // Declaration kinds for which the definition is not resolvable.
4441  case Decl::UnresolvedUsingTypename:
4442  case Decl::UnresolvedUsingValue:
4443    break;
4444
4445  case Decl::UsingDirective:
4446    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4447                        TU);
4448
4449  case Decl::NamespaceAlias:
4450    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4451
4452  case Decl::Enum:
4453  case Decl::Record:
4454  case Decl::CXXRecord:
4455  case Decl::ClassTemplateSpecialization:
4456  case Decl::ClassTemplatePartialSpecialization:
4457    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4458      return MakeCXCursor(Def, TU);
4459    return clang_getNullCursor();
4460
4461  case Decl::Function:
4462  case Decl::CXXMethod:
4463  case Decl::CXXConstructor:
4464  case Decl::CXXDestructor:
4465  case Decl::CXXConversion: {
4466    const FunctionDecl *Def = 0;
4467    if (cast<FunctionDecl>(D)->getBody(Def))
4468      return MakeCXCursor(Def, TU);
4469    return clang_getNullCursor();
4470  }
4471
4472  case Decl::Var: {
4473    // Ask the variable if it has a definition.
4474    if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4475      return MakeCXCursor(Def, TU);
4476    return clang_getNullCursor();
4477  }
4478
4479  case Decl::FunctionTemplate: {
4480    const FunctionDecl *Def = 0;
4481    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4482      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4483    return clang_getNullCursor();
4484  }
4485
4486  case Decl::ClassTemplate: {
4487    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4488                                                            ->getDefinition())
4489      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4490                          TU);
4491    return clang_getNullCursor();
4492  }
4493
4494  case Decl::Using:
4495    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4496                                       D->getLocation(), TU);
4497
4498  case Decl::UsingShadow:
4499    return clang_getCursorDefinition(
4500                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4501                                    TU));
4502
4503  case Decl::ObjCMethod: {
4504    const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4505    if (Method->isThisDeclarationADefinition())
4506      return C;
4507
4508    // Dig out the method definition in the associated
4509    // @implementation, if we have it.
4510    // FIXME: The ASTs should make finding the definition easier.
4511    if (const ObjCInterfaceDecl *Class
4512                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4513      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4514        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4515                                                  Method->isInstanceMethod()))
4516          if (Def->isThisDeclarationADefinition())
4517            return MakeCXCursor(Def, TU);
4518
4519    return clang_getNullCursor();
4520  }
4521
4522  case Decl::ObjCCategory:
4523    if (ObjCCategoryImplDecl *Impl
4524                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4525      return MakeCXCursor(Impl, TU);
4526    return clang_getNullCursor();
4527
4528  case Decl::ObjCProtocol:
4529    if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4530      return MakeCXCursor(Def, TU);
4531    return clang_getNullCursor();
4532
4533  case Decl::ObjCInterface: {
4534    // There are two notions of a "definition" for an Objective-C
4535    // class: the interface and its implementation. When we resolved a
4536    // reference to an Objective-C class, produce the @interface as
4537    // the definition; when we were provided with the interface,
4538    // produce the @implementation as the definition.
4539    const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4540    if (WasReference) {
4541      if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
4542        return MakeCXCursor(Def, TU);
4543    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4544      return MakeCXCursor(Impl, TU);
4545    return clang_getNullCursor();
4546  }
4547
4548  case Decl::ObjCProperty:
4549    // FIXME: We don't really know where to find the
4550    // ObjCPropertyImplDecls that implement this property.
4551    return clang_getNullCursor();
4552
4553  case Decl::ObjCCompatibleAlias:
4554    if (const ObjCInterfaceDecl *Class
4555          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4556      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
4557        return MakeCXCursor(Def, TU);
4558
4559    return clang_getNullCursor();
4560
4561  case Decl::Friend:
4562    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4563      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4564    return clang_getNullCursor();
4565
4566  case Decl::FriendTemplate:
4567    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4568      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4569    return clang_getNullCursor();
4570  }
4571
4572  return clang_getNullCursor();
4573}
4574
4575unsigned clang_isCursorDefinition(CXCursor C) {
4576  if (!clang_isDeclaration(C.kind))
4577    return 0;
4578
4579  return clang_getCursorDefinition(C) == C;
4580}
4581
4582CXCursor clang_getCanonicalCursor(CXCursor C) {
4583  if (!clang_isDeclaration(C.kind))
4584    return C;
4585
4586  if (const Decl *D = getCursorDecl(C)) {
4587    if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4588      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4589        return MakeCXCursor(CatD, getCursorTU(C));
4590
4591    if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4592      if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4593        return MakeCXCursor(IFD, getCursorTU(C));
4594
4595    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4596  }
4597
4598  return C;
4599}
4600
4601int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4602  return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4603}
4604
4605unsigned clang_getNumOverloadedDecls(CXCursor C) {
4606  if (C.kind != CXCursor_OverloadedDeclRef)
4607    return 0;
4608
4609  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4610  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4611    return E->getNumDecls();
4612
4613  if (OverloadedTemplateStorage *S
4614                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4615    return S->size();
4616
4617  const Decl *D = Storage.get<const Decl *>();
4618  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4619    return Using->shadow_size();
4620
4621  return 0;
4622}
4623
4624CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4625  if (cursor.kind != CXCursor_OverloadedDeclRef)
4626    return clang_getNullCursor();
4627
4628  if (index >= clang_getNumOverloadedDecls(cursor))
4629    return clang_getNullCursor();
4630
4631  CXTranslationUnit TU = getCursorTU(cursor);
4632  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4633  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4634    return MakeCXCursor(E->decls_begin()[index], TU);
4635
4636  if (OverloadedTemplateStorage *S
4637                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4638    return MakeCXCursor(S->begin()[index], TU);
4639
4640  const Decl *D = Storage.get<const Decl *>();
4641  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4642    // FIXME: This is, unfortunately, linear time.
4643    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4644    std::advance(Pos, index);
4645    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4646  }
4647
4648  return clang_getNullCursor();
4649}
4650
4651void clang_getDefinitionSpellingAndExtent(CXCursor C,
4652                                          const char **startBuf,
4653                                          const char **endBuf,
4654                                          unsigned *startLine,
4655                                          unsigned *startColumn,
4656                                          unsigned *endLine,
4657                                          unsigned *endColumn) {
4658  assert(getCursorDecl(C) && "CXCursor has null decl");
4659  const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
4660  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4661
4662  SourceManager &SM = FD->getASTContext().getSourceManager();
4663  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4664  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4665  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4666  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4667  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4668  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4669}
4670
4671
4672CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4673                                                unsigned PieceIndex) {
4674  RefNamePieces Pieces;
4675
4676  switch (C.kind) {
4677  case CXCursor_MemberRefExpr:
4678    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4679      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4680                           E->getQualifierLoc().getSourceRange());
4681    break;
4682
4683  case CXCursor_DeclRefExpr:
4684    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4685      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4686                           E->getQualifierLoc().getSourceRange(),
4687                           E->getOptionalExplicitTemplateArgs());
4688    break;
4689
4690  case CXCursor_CallExpr:
4691    if (CXXOperatorCallExpr *OCE =
4692        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4693      Expr *Callee = OCE->getCallee();
4694      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4695        Callee = ICE->getSubExpr();
4696
4697      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4698        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4699                             DRE->getQualifierLoc().getSourceRange());
4700    }
4701    break;
4702
4703  default:
4704    break;
4705  }
4706
4707  if (Pieces.empty()) {
4708    if (PieceIndex == 0)
4709      return clang_getCursorExtent(C);
4710  } else if (PieceIndex < Pieces.size()) {
4711      SourceRange R = Pieces[PieceIndex];
4712      if (R.isValid())
4713        return cxloc::translateSourceRange(getCursorContext(C), R);
4714  }
4715
4716  return clang_getNullRange();
4717}
4718
4719void clang_enableStackTraces(void) {
4720  llvm::sys::PrintStackTraceOnErrorSignal();
4721}
4722
4723void clang_executeOnThread(void (*fn)(void*), void *user_data,
4724                           unsigned stack_size) {
4725  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4726}
4727
4728} // end: extern "C"
4729
4730//===----------------------------------------------------------------------===//
4731// Token-based Operations.
4732//===----------------------------------------------------------------------===//
4733
4734/* CXToken layout:
4735 *   int_data[0]: a CXTokenKind
4736 *   int_data[1]: starting token location
4737 *   int_data[2]: token length
4738 *   int_data[3]: reserved
4739 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4740 *   otherwise unused.
4741 */
4742extern "C" {
4743
4744CXTokenKind clang_getTokenKind(CXToken CXTok) {
4745  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4746}
4747
4748CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4749  switch (clang_getTokenKind(CXTok)) {
4750  case CXToken_Identifier:
4751  case CXToken_Keyword:
4752    // We know we have an IdentifierInfo*, so use that.
4753    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4754                            ->getNameStart());
4755
4756  case CXToken_Literal: {
4757    // We have stashed the starting pointer in the ptr_data field. Use it.
4758    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4759    return createCXString(StringRef(Text, CXTok.int_data[2]));
4760  }
4761
4762  case CXToken_Punctuation:
4763  case CXToken_Comment:
4764    break;
4765  }
4766
4767  // We have to find the starting buffer pointer the hard way, by
4768  // deconstructing the source location.
4769  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4770  if (!CXXUnit)
4771    return createCXString("");
4772
4773  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4774  std::pair<FileID, unsigned> LocInfo
4775    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4776  bool Invalid = false;
4777  StringRef Buffer
4778    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4779  if (Invalid)
4780    return createCXString("");
4781
4782  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4783}
4784
4785CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4786  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4787  if (!CXXUnit)
4788    return clang_getNullLocation();
4789
4790  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4791                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4792}
4793
4794CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4795  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4796  if (!CXXUnit)
4797    return clang_getNullRange();
4798
4799  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4800                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4801}
4802
4803static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4804                      SmallVectorImpl<CXToken> &CXTokens) {
4805  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4806  std::pair<FileID, unsigned> BeginLocInfo
4807    = SourceMgr.getDecomposedLoc(Range.getBegin());
4808  std::pair<FileID, unsigned> EndLocInfo
4809    = SourceMgr.getDecomposedLoc(Range.getEnd());
4810
4811  // Cannot tokenize across files.
4812  if (BeginLocInfo.first != EndLocInfo.first)
4813    return;
4814
4815  // Create a lexer
4816  bool Invalid = false;
4817  StringRef Buffer
4818    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4819  if (Invalid)
4820    return;
4821
4822  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4823            CXXUnit->getASTContext().getLangOpts(),
4824            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4825  Lex.SetCommentRetentionState(true);
4826
4827  // Lex tokens until we hit the end of the range.
4828  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4829  Token Tok;
4830  bool previousWasAt = false;
4831  do {
4832    // Lex the next token
4833    Lex.LexFromRawLexer(Tok);
4834    if (Tok.is(tok::eof))
4835      break;
4836
4837    // Initialize the CXToken.
4838    CXToken CXTok;
4839
4840    //   - Common fields
4841    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4842    CXTok.int_data[2] = Tok.getLength();
4843    CXTok.int_data[3] = 0;
4844
4845    //   - Kind-specific fields
4846    if (Tok.isLiteral()) {
4847      CXTok.int_data[0] = CXToken_Literal;
4848      CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
4849    } else if (Tok.is(tok::raw_identifier)) {
4850      // Lookup the identifier to determine whether we have a keyword.
4851      IdentifierInfo *II
4852        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4853
4854      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4855        CXTok.int_data[0] = CXToken_Keyword;
4856      }
4857      else {
4858        CXTok.int_data[0] = Tok.is(tok::identifier)
4859          ? CXToken_Identifier
4860          : CXToken_Keyword;
4861      }
4862      CXTok.ptr_data = II;
4863    } else if (Tok.is(tok::comment)) {
4864      CXTok.int_data[0] = CXToken_Comment;
4865      CXTok.ptr_data = 0;
4866    } else {
4867      CXTok.int_data[0] = CXToken_Punctuation;
4868      CXTok.ptr_data = 0;
4869    }
4870    CXTokens.push_back(CXTok);
4871    previousWasAt = Tok.is(tok::at);
4872  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4873}
4874
4875void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4876                    CXToken **Tokens, unsigned *NumTokens) {
4877  LOG_FUNC_SECTION {
4878    *Log << TU << ' ' << Range;
4879  }
4880
4881  if (Tokens)
4882    *Tokens = 0;
4883  if (NumTokens)
4884    *NumTokens = 0;
4885
4886  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4887  if (!CXXUnit || !Tokens || !NumTokens)
4888    return;
4889
4890  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4891
4892  SourceRange R = cxloc::translateCXSourceRange(Range);
4893  if (R.isInvalid())
4894    return;
4895
4896  SmallVector<CXToken, 32> CXTokens;
4897  getTokens(CXXUnit, R, CXTokens);
4898
4899  if (CXTokens.empty())
4900    return;
4901
4902  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4903  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4904  *NumTokens = CXTokens.size();
4905}
4906
4907void clang_disposeTokens(CXTranslationUnit TU,
4908                         CXToken *Tokens, unsigned NumTokens) {
4909  free(Tokens);
4910}
4911
4912} // end: extern "C"
4913
4914//===----------------------------------------------------------------------===//
4915// Token annotation APIs.
4916//===----------------------------------------------------------------------===//
4917
4918static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4919                                                     CXCursor parent,
4920                                                     CXClientData client_data);
4921static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4922                                              CXClientData client_data);
4923
4924namespace {
4925class AnnotateTokensWorker {
4926  CXToken *Tokens;
4927  CXCursor *Cursors;
4928  unsigned NumTokens;
4929  unsigned TokIdx;
4930  unsigned PreprocessingTokIdx;
4931  CursorVisitor AnnotateVis;
4932  SourceManager &SrcMgr;
4933  bool HasContextSensitiveKeywords;
4934
4935  struct PostChildrenInfo {
4936    CXCursor Cursor;
4937    SourceRange CursorRange;
4938    unsigned BeforeChildrenTokenIdx;
4939  };
4940  SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
4941
4942  bool MoreTokens() const { return TokIdx < NumTokens; }
4943  unsigned NextToken() const { return TokIdx; }
4944  void AdvanceToken() { ++TokIdx; }
4945  SourceLocation GetTokenLoc(unsigned tokI) {
4946    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4947  }
4948  bool isFunctionMacroToken(unsigned tokI) const {
4949    return Tokens[tokI].int_data[3] != 0;
4950  }
4951  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4952    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4953  }
4954
4955  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4956  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4957                                             SourceRange);
4958
4959public:
4960  AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4961                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4962    : Tokens(tokens), Cursors(cursors),
4963      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4964      AnnotateVis(tu,
4965                  AnnotateTokensVisitor, this,
4966                  /*VisitPreprocessorLast=*/true,
4967                  /*VisitIncludedEntities=*/false,
4968                  RegionOfInterest,
4969                  /*VisitDeclsOnly=*/false,
4970                  AnnotateTokensPostChildrenVisitor),
4971      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4972      HasContextSensitiveKeywords(false) { }
4973
4974  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4975  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4976  bool postVisitChildren(CXCursor cursor);
4977  void AnnotateTokens();
4978
4979  /// \brief Determine whether the annotator saw any cursors that have
4980  /// context-sensitive keywords.
4981  bool hasContextSensitiveKeywords() const {
4982    return HasContextSensitiveKeywords;
4983  }
4984
4985  ~AnnotateTokensWorker() {
4986    assert(PostChildrenInfos.empty());
4987  }
4988};
4989}
4990
4991void AnnotateTokensWorker::AnnotateTokens() {
4992  // Walk the AST within the region of interest, annotating tokens
4993  // along the way.
4994  AnnotateVis.visitFileRegion();
4995}
4996
4997static inline void updateCursorAnnotation(CXCursor &Cursor,
4998                                          const CXCursor &updateC) {
4999  if (clang_isInvalid(updateC.kind) || clang_isPreprocessing(Cursor.kind))
5000    return;
5001  Cursor = updateC;
5002}
5003
5004/// \brief It annotates and advances tokens with a cursor until the comparison
5005//// between the cursor location and the source range is the same as
5006/// \arg compResult.
5007///
5008/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5009/// Pass RangeOverlap to annotate tokens inside a range.
5010void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5011                                               RangeComparisonResult compResult,
5012                                               SourceRange range) {
5013  while (MoreTokens()) {
5014    const unsigned I = NextToken();
5015    if (isFunctionMacroToken(I))
5016      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
5017
5018    SourceLocation TokLoc = GetTokenLoc(I);
5019    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5020      updateCursorAnnotation(Cursors[I], updateC);
5021      AdvanceToken();
5022      continue;
5023    }
5024    break;
5025  }
5026}
5027
5028/// \brief Special annotation handling for macro argument tokens.
5029void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5030                                               CXCursor updateC,
5031                                               RangeComparisonResult compResult,
5032                                               SourceRange range) {
5033  assert(MoreTokens());
5034  assert(isFunctionMacroToken(NextToken()) &&
5035         "Should be called only for macro arg tokens");
5036
5037  // This works differently than annotateAndAdvanceTokens; because expanded
5038  // macro arguments can have arbitrary translation-unit source order, we do not
5039  // advance the token index one by one until a token fails the range test.
5040  // We only advance once past all of the macro arg tokens if all of them
5041  // pass the range test. If one of them fails we keep the token index pointing
5042  // at the start of the macro arg tokens so that the failing token will be
5043  // annotated by a subsequent annotation try.
5044
5045  bool atLeastOneCompFail = false;
5046
5047  unsigned I = NextToken();
5048  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5049    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5050    if (TokLoc.isFileID())
5051      continue; // not macro arg token, it's parens or comma.
5052    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5053      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5054        Cursors[I] = updateC;
5055    } else
5056      atLeastOneCompFail = true;
5057  }
5058
5059  if (!atLeastOneCompFail)
5060    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5061}
5062
5063enum CXChildVisitResult
5064AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5065  SourceRange cursorRange = getRawCursorExtent(cursor);
5066  if (cursorRange.isInvalid())
5067    return CXChildVisit_Recurse;
5068
5069  if (!HasContextSensitiveKeywords) {
5070    // Objective-C properties can have context-sensitive keywords.
5071    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5072      if (const ObjCPropertyDecl *Property
5073                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5074        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5075    }
5076    // Objective-C methods can have context-sensitive keywords.
5077    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5078             cursor.kind == CXCursor_ObjCClassMethodDecl) {
5079      if (const ObjCMethodDecl *Method
5080            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5081        if (Method->getObjCDeclQualifier())
5082          HasContextSensitiveKeywords = true;
5083        else {
5084          for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
5085                                                 PEnd = Method->param_end();
5086               P != PEnd; ++P) {
5087            if ((*P)->getObjCDeclQualifier()) {
5088              HasContextSensitiveKeywords = true;
5089              break;
5090            }
5091          }
5092        }
5093      }
5094    }
5095    // C++ methods can have context-sensitive keywords.
5096    else if (cursor.kind == CXCursor_CXXMethod) {
5097      if (const CXXMethodDecl *Method
5098                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5099        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5100          HasContextSensitiveKeywords = true;
5101      }
5102    }
5103    // C++ classes can have context-sensitive keywords.
5104    else if (cursor.kind == CXCursor_StructDecl ||
5105             cursor.kind == CXCursor_ClassDecl ||
5106             cursor.kind == CXCursor_ClassTemplate ||
5107             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5108      if (const Decl *D = getCursorDecl(cursor))
5109        if (D->hasAttr<FinalAttr>())
5110          HasContextSensitiveKeywords = true;
5111    }
5112  }
5113
5114  if (clang_isPreprocessing(cursor.kind)) {
5115    // Items in the preprocessing record are kept separate from items in
5116    // declarations, so we keep a separate token index.
5117    unsigned SavedTokIdx = TokIdx;
5118    TokIdx = PreprocessingTokIdx;
5119
5120    // Skip tokens up until we catch up to the beginning of the preprocessing
5121    // entry.
5122    while (MoreTokens()) {
5123      const unsigned I = NextToken();
5124      SourceLocation TokLoc = GetTokenLoc(I);
5125      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5126      case RangeBefore:
5127        AdvanceToken();
5128        continue;
5129      case RangeAfter:
5130      case RangeOverlap:
5131        break;
5132      }
5133      break;
5134    }
5135
5136    // Look at all of the tokens within this range.
5137    while (MoreTokens()) {
5138      const unsigned I = NextToken();
5139      SourceLocation TokLoc = GetTokenLoc(I);
5140      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5141      case RangeBefore:
5142        llvm_unreachable("Infeasible");
5143      case RangeAfter:
5144        break;
5145      case RangeOverlap:
5146        // We may have already annotated macro names inside macro definitions.
5147        if (Cursors[I].kind != CXCursor_MacroExpansion)
5148          Cursors[I] = cursor;
5149        AdvanceToken();
5150        // For macro expansions, just note where the beginning of the macro
5151        // expansion occurs.
5152        if (cursor.kind == CXCursor_MacroExpansion)
5153          break;
5154        continue;
5155      }
5156      break;
5157    }
5158
5159    // Save the preprocessing token index; restore the non-preprocessing
5160    // token index.
5161    PreprocessingTokIdx = TokIdx;
5162    TokIdx = SavedTokIdx;
5163    return CXChildVisit_Recurse;
5164  }
5165
5166  if (cursorRange.isInvalid())
5167    return CXChildVisit_Continue;
5168
5169  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5170  const enum CXCursorKind K = clang_getCursorKind(parent);
5171  const CXCursor updateC =
5172    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5173     ? clang_getNullCursor() : parent;
5174
5175  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5176
5177  // Avoid having the cursor of an expression "overwrite" the annotation of the
5178  // variable declaration that it belongs to.
5179  // This can happen for C++ constructor expressions whose range generally
5180  // include the variable declaration, e.g.:
5181  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5182  if (clang_isExpression(cursorK)) {
5183    Expr *E = getCursorExpr(cursor);
5184    if (Decl *D = getCursorParentDecl(cursor)) {
5185      const unsigned I = NextToken();
5186      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5187          E->getLocStart() == D->getLocation() &&
5188          E->getLocStart() == GetTokenLoc(I)) {
5189        updateCursorAnnotation(Cursors[I], updateC);
5190        AdvanceToken();
5191      }
5192    }
5193  }
5194
5195  // Before recursing into the children keep some state that we are going
5196  // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5197  // extra work after the child nodes are visited.
5198  // Note that we don't call VisitChildren here to avoid traversing statements
5199  // code-recursively which can blow the stack.
5200
5201  PostChildrenInfo Info;
5202  Info.Cursor = cursor;
5203  Info.CursorRange = cursorRange;
5204  Info.BeforeChildrenTokenIdx = NextToken();
5205  PostChildrenInfos.push_back(Info);
5206
5207  return CXChildVisit_Recurse;
5208}
5209
5210bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5211  if (PostChildrenInfos.empty())
5212    return false;
5213  const PostChildrenInfo &Info = PostChildrenInfos.back();
5214  if (!clang_equalCursors(Info.Cursor, cursor))
5215    return false;
5216
5217  const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5218  const unsigned AfterChildren = NextToken();
5219  SourceRange cursorRange = Info.CursorRange;
5220
5221  // Scan the tokens that are at the end of the cursor, but are not captured
5222  // but the child cursors.
5223  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5224
5225  // Scan the tokens that are at the beginning of the cursor, but are not
5226  // capture by the child cursors.
5227  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5228    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5229      break;
5230
5231    Cursors[I] = cursor;
5232  }
5233
5234  PostChildrenInfos.pop_back();
5235  return false;
5236}
5237
5238static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5239                                                     CXCursor parent,
5240                                                     CXClientData client_data) {
5241  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5242}
5243
5244static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5245                                              CXClientData client_data) {
5246  return static_cast<AnnotateTokensWorker*>(client_data)->
5247                                                      postVisitChildren(cursor);
5248}
5249
5250namespace {
5251
5252/// \brief Uses the macro expansions in the preprocessing record to find
5253/// and mark tokens that are macro arguments. This info is used by the
5254/// AnnotateTokensWorker.
5255class MarkMacroArgTokensVisitor {
5256  SourceManager &SM;
5257  CXToken *Tokens;
5258  unsigned NumTokens;
5259  unsigned CurIdx;
5260
5261public:
5262  MarkMacroArgTokensVisitor(SourceManager &SM,
5263                            CXToken *tokens, unsigned numTokens)
5264    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5265
5266  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5267    if (cursor.kind != CXCursor_MacroExpansion)
5268      return CXChildVisit_Continue;
5269
5270    SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
5271    if (macroRange.getBegin() == macroRange.getEnd())
5272      return CXChildVisit_Continue; // it's not a function macro.
5273
5274    for (; CurIdx < NumTokens; ++CurIdx) {
5275      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5276                                        macroRange.getBegin()))
5277        break;
5278    }
5279
5280    if (CurIdx == NumTokens)
5281      return CXChildVisit_Break;
5282
5283    for (; CurIdx < NumTokens; ++CurIdx) {
5284      SourceLocation tokLoc = getTokenLoc(CurIdx);
5285      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5286        break;
5287
5288      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5289    }
5290
5291    if (CurIdx == NumTokens)
5292      return CXChildVisit_Break;
5293
5294    return CXChildVisit_Continue;
5295  }
5296
5297private:
5298  SourceLocation getTokenLoc(unsigned tokI) {
5299    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5300  }
5301
5302  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5303    // The third field is reserved and currently not used. Use it here
5304    // to mark macro arg expanded tokens with their expanded locations.
5305    Tokens[tokI].int_data[3] = loc.getRawEncoding();
5306  }
5307};
5308
5309} // end anonymous namespace
5310
5311static CXChildVisitResult
5312MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5313                                  CXClientData client_data) {
5314  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5315                                                                     parent);
5316}
5317
5318namespace {
5319  struct clang_annotateTokens_Data {
5320    CXTranslationUnit TU;
5321    ASTUnit *CXXUnit;
5322    CXToken *Tokens;
5323    unsigned NumTokens;
5324    CXCursor *Cursors;
5325  };
5326}
5327
5328/// \brief Used by \c annotatePreprocessorTokens.
5329/// \returns true if lexing was finished, false otherwise.
5330static bool lexNext(Lexer &Lex, Token &Tok,
5331                   unsigned &NextIdx, unsigned NumTokens) {
5332  if (NextIdx >= NumTokens)
5333    return true;
5334
5335  ++NextIdx;
5336  Lex.LexFromRawLexer(Tok);
5337  if (Tok.is(tok::eof))
5338    return true;
5339
5340  return false;
5341}
5342
5343static void annotatePreprocessorTokens(CXTranslationUnit TU,
5344                                       SourceRange RegionOfInterest,
5345                                       CXCursor *Cursors,
5346                                       CXToken *Tokens,
5347                                       unsigned NumTokens) {
5348  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5349
5350  Preprocessor &PP = CXXUnit->getPreprocessor();
5351  SourceManager &SourceMgr = CXXUnit->getSourceManager();
5352  std::pair<FileID, unsigned> BeginLocInfo
5353    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5354  std::pair<FileID, unsigned> EndLocInfo
5355    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5356
5357  if (BeginLocInfo.first != EndLocInfo.first)
5358    return;
5359
5360  StringRef Buffer;
5361  bool Invalid = false;
5362  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5363  if (Buffer.empty() || Invalid)
5364    return;
5365
5366  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5367            CXXUnit->getASTContext().getLangOpts(),
5368            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5369            Buffer.end());
5370  Lex.SetCommentRetentionState(true);
5371
5372  unsigned NextIdx = 0;
5373  // Lex tokens in raw mode until we hit the end of the range, to avoid
5374  // entering #includes or expanding macros.
5375  while (true) {
5376    Token Tok;
5377    if (lexNext(Lex, Tok, NextIdx, NumTokens))
5378      break;
5379    unsigned TokIdx = NextIdx-1;
5380    assert(Tok.getLocation() ==
5381             SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
5382
5383  reprocess:
5384    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5385      // We have found a preprocessing directive. Annotate the tokens
5386      // appropriately.
5387      //
5388      // FIXME: Some simple tests here could identify macro definitions and
5389      // #undefs, to provide specific cursor kinds for those.
5390
5391      SourceLocation BeginLoc = Tok.getLocation();
5392      if (lexNext(Lex, Tok, NextIdx, NumTokens))
5393        break;
5394
5395      MacroInfo *MI = 0;
5396      if (Tok.is(tok::raw_identifier) &&
5397          StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == "define") {
5398        if (lexNext(Lex, Tok, NextIdx, NumTokens))
5399          break;
5400
5401        if (Tok.is(tok::raw_identifier)) {
5402          StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
5403          IdentifierInfo &II = PP.getIdentifierTable().get(Name);
5404          SourceLocation MappedTokLoc =
5405              CXXUnit->mapLocationToPreamble(Tok.getLocation());
5406          MI = getMacroInfo(II, MappedTokLoc, TU);
5407        }
5408      }
5409
5410      bool finished = false;
5411      do {
5412        if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
5413          finished = true;
5414          break;
5415        }
5416        // If we are in a macro definition, check if the token was ever a
5417        // macro name and annotate it if that's the case.
5418        if (MI) {
5419          SourceLocation SaveLoc = Tok.getLocation();
5420          Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
5421          MacroDefinition *MacroDef = checkForMacroInMacroDefinition(MI,Tok,TU);
5422          Tok.setLocation(SaveLoc);
5423          if (MacroDef)
5424            Cursors[NextIdx-1] = MakeMacroExpansionCursor(MacroDef,
5425                                                         Tok.getLocation(), TU);
5426        }
5427      } while (!Tok.isAtStartOfLine());
5428
5429      unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
5430      assert(TokIdx <= LastIdx);
5431      SourceLocation EndLoc =
5432          SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
5433      CXCursor Cursor =
5434          MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
5435
5436      for (; TokIdx <= LastIdx; ++TokIdx)
5437        updateCursorAnnotation(Cursors[TokIdx], Cursor);
5438
5439      if (finished)
5440        break;
5441      goto reprocess;
5442    }
5443  }
5444}
5445
5446// This gets run a separate thread to avoid stack blowout.
5447static void clang_annotateTokensImpl(void *UserData) {
5448  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5449  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5450  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5451  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5452  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5453
5454  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5455  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5456    setThreadBackgroundPriority();
5457
5458  // Determine the region of interest, which contains all of the tokens.
5459  SourceRange RegionOfInterest;
5460  RegionOfInterest.setBegin(
5461    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5462  RegionOfInterest.setEnd(
5463    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5464                                                         Tokens[NumTokens-1])));
5465
5466  // Relex the tokens within the source range to look for preprocessing
5467  // directives.
5468  annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
5469
5470  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5471    // Search and mark tokens that are macro argument expansions.
5472    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5473                                      Tokens, NumTokens);
5474    CursorVisitor MacroArgMarker(TU,
5475                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5476                                 /*VisitPreprocessorLast=*/true,
5477                                 /*VisitIncludedEntities=*/false,
5478                                 RegionOfInterest);
5479    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5480  }
5481
5482  // Annotate all of the source locations in the region of interest that map to
5483  // a specific cursor.
5484  AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
5485
5486  // FIXME: We use a ridiculous stack size here because the data-recursion
5487  // algorithm uses a large stack frame than the non-data recursive version,
5488  // and AnnotationTokensWorker currently transforms the data-recursion
5489  // algorithm back into a traditional recursion by explicitly calling
5490  // VisitChildren().  We will need to remove this explicit recursive call.
5491  W.AnnotateTokens();
5492
5493  // If we ran into any entities that involve context-sensitive keywords,
5494  // take another pass through the tokens to mark them as such.
5495  if (W.hasContextSensitiveKeywords()) {
5496    for (unsigned I = 0; I != NumTokens; ++I) {
5497      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5498        continue;
5499
5500      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5501        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5502        if (const ObjCPropertyDecl *Property
5503            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5504          if (Property->getPropertyAttributesAsWritten() != 0 &&
5505              llvm::StringSwitch<bool>(II->getName())
5506              .Case("readonly", true)
5507              .Case("assign", true)
5508              .Case("unsafe_unretained", true)
5509              .Case("readwrite", true)
5510              .Case("retain", true)
5511              .Case("copy", true)
5512              .Case("nonatomic", true)
5513              .Case("atomic", true)
5514              .Case("getter", true)
5515              .Case("setter", true)
5516              .Case("strong", true)
5517              .Case("weak", true)
5518              .Default(false))
5519            Tokens[I].int_data[0] = CXToken_Keyword;
5520        }
5521        continue;
5522      }
5523
5524      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5525          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5526        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5527        if (llvm::StringSwitch<bool>(II->getName())
5528            .Case("in", true)
5529            .Case("out", true)
5530            .Case("inout", true)
5531            .Case("oneway", true)
5532            .Case("bycopy", true)
5533            .Case("byref", true)
5534            .Default(false))
5535          Tokens[I].int_data[0] = CXToken_Keyword;
5536        continue;
5537      }
5538
5539      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5540          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5541        Tokens[I].int_data[0] = CXToken_Keyword;
5542        continue;
5543      }
5544    }
5545  }
5546}
5547
5548extern "C" {
5549
5550void clang_annotateTokens(CXTranslationUnit TU,
5551                          CXToken *Tokens, unsigned NumTokens,
5552                          CXCursor *Cursors) {
5553  if (NumTokens == 0 || !Tokens || !Cursors) {
5554    LOG_FUNC_SECTION { *Log << "<null input>"; }
5555    return;
5556  }
5557
5558  LOG_FUNC_SECTION {
5559    *Log << TU << ' ';
5560    CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
5561    CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
5562    *Log << clang_getRange(bloc, eloc);
5563  }
5564
5565  // Any token we don't specifically annotate will have a NULL cursor.
5566  CXCursor C = clang_getNullCursor();
5567  for (unsigned I = 0; I != NumTokens; ++I)
5568    Cursors[I] = C;
5569
5570  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5571  if (!CXXUnit)
5572    return;
5573
5574  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5575
5576  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5577  llvm::CrashRecoveryContext CRC;
5578  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5579                 GetSafetyThreadStackSize() * 2)) {
5580    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5581  }
5582}
5583
5584} // end: extern "C"
5585
5586//===----------------------------------------------------------------------===//
5587// Operations for querying linkage of a cursor.
5588//===----------------------------------------------------------------------===//
5589
5590extern "C" {
5591CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5592  if (!clang_isDeclaration(cursor.kind))
5593    return CXLinkage_Invalid;
5594
5595  const Decl *D = cxcursor::getCursorDecl(cursor);
5596  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5597    switch (ND->getLinkage()) {
5598      case NoLinkage: return CXLinkage_NoLinkage;
5599      case InternalLinkage: return CXLinkage_Internal;
5600      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5601      case ExternalLinkage: return CXLinkage_External;
5602    };
5603
5604  return CXLinkage_Invalid;
5605}
5606} // end: extern "C"
5607
5608//===----------------------------------------------------------------------===//
5609// Operations for querying language of a cursor.
5610//===----------------------------------------------------------------------===//
5611
5612static CXLanguageKind getDeclLanguage(const Decl *D) {
5613  if (!D)
5614    return CXLanguage_C;
5615
5616  switch (D->getKind()) {
5617    default:
5618      break;
5619    case Decl::ImplicitParam:
5620    case Decl::ObjCAtDefsField:
5621    case Decl::ObjCCategory:
5622    case Decl::ObjCCategoryImpl:
5623    case Decl::ObjCCompatibleAlias:
5624    case Decl::ObjCImplementation:
5625    case Decl::ObjCInterface:
5626    case Decl::ObjCIvar:
5627    case Decl::ObjCMethod:
5628    case Decl::ObjCProperty:
5629    case Decl::ObjCPropertyImpl:
5630    case Decl::ObjCProtocol:
5631      return CXLanguage_ObjC;
5632    case Decl::CXXConstructor:
5633    case Decl::CXXConversion:
5634    case Decl::CXXDestructor:
5635    case Decl::CXXMethod:
5636    case Decl::CXXRecord:
5637    case Decl::ClassTemplate:
5638    case Decl::ClassTemplatePartialSpecialization:
5639    case Decl::ClassTemplateSpecialization:
5640    case Decl::Friend:
5641    case Decl::FriendTemplate:
5642    case Decl::FunctionTemplate:
5643    case Decl::LinkageSpec:
5644    case Decl::Namespace:
5645    case Decl::NamespaceAlias:
5646    case Decl::NonTypeTemplateParm:
5647    case Decl::StaticAssert:
5648    case Decl::TemplateTemplateParm:
5649    case Decl::TemplateTypeParm:
5650    case Decl::UnresolvedUsingTypename:
5651    case Decl::UnresolvedUsingValue:
5652    case Decl::Using:
5653    case Decl::UsingDirective:
5654    case Decl::UsingShadow:
5655      return CXLanguage_CPlusPlus;
5656  }
5657
5658  return CXLanguage_C;
5659}
5660
5661extern "C" {
5662
5663enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5664  if (clang_isDeclaration(cursor.kind))
5665    if (const Decl *D = cxcursor::getCursorDecl(cursor)) {
5666      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5667        return CXAvailability_Available;
5668
5669      switch (D->getAvailability()) {
5670      case AR_Available:
5671      case AR_NotYetIntroduced:
5672        return CXAvailability_Available;
5673
5674      case AR_Deprecated:
5675        return CXAvailability_Deprecated;
5676
5677      case AR_Unavailable:
5678        return CXAvailability_NotAvailable;
5679      }
5680    }
5681
5682  return CXAvailability_Available;
5683}
5684
5685static CXVersion convertVersion(VersionTuple In) {
5686  CXVersion Out = { -1, -1, -1 };
5687  if (In.empty())
5688    return Out;
5689
5690  Out.Major = In.getMajor();
5691
5692  if (llvm::Optional<unsigned> Minor = In.getMinor())
5693    Out.Minor = *Minor;
5694  else
5695    return Out;
5696
5697  if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5698    Out.Subminor = *Subminor;
5699
5700  return Out;
5701}
5702
5703int clang_getCursorPlatformAvailability(CXCursor cursor,
5704                                        int *always_deprecated,
5705                                        CXString *deprecated_message,
5706                                        int *always_unavailable,
5707                                        CXString *unavailable_message,
5708                                        CXPlatformAvailability *availability,
5709                                        int availability_size) {
5710  if (always_deprecated)
5711    *always_deprecated = 0;
5712  if (deprecated_message)
5713    *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5714  if (always_unavailable)
5715    *always_unavailable = 0;
5716  if (unavailable_message)
5717    *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5718
5719  if (!clang_isDeclaration(cursor.kind))
5720    return 0;
5721
5722  const Decl *D = cxcursor::getCursorDecl(cursor);
5723  if (!D)
5724    return 0;
5725
5726  int N = 0;
5727  for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5728       ++A) {
5729    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5730      if (always_deprecated)
5731        *always_deprecated = 1;
5732      if (deprecated_message)
5733        *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5734      continue;
5735    }
5736
5737    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5738      if (always_unavailable)
5739        *always_unavailable = 1;
5740      if (unavailable_message) {
5741        *unavailable_message
5742          = cxstring::createCXString(Unavailable->getMessage());
5743      }
5744      continue;
5745    }
5746
5747    if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5748      if (N < availability_size) {
5749        availability[N].Platform
5750          = cxstring::createCXString(Avail->getPlatform()->getName());
5751        availability[N].Introduced = convertVersion(Avail->getIntroduced());
5752        availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5753        availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5754        availability[N].Unavailable = Avail->getUnavailable();
5755        availability[N].Message = cxstring::createCXString(Avail->getMessage());
5756      }
5757      ++N;
5758    }
5759  }
5760
5761  return N;
5762}
5763
5764void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5765  clang_disposeString(availability->Platform);
5766  clang_disposeString(availability->Message);
5767}
5768
5769CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5770  if (clang_isDeclaration(cursor.kind))
5771    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5772
5773  return CXLanguage_Invalid;
5774}
5775
5776 /// \brief If the given cursor is the "templated" declaration
5777 /// descibing a class or function template, return the class or
5778 /// function template.
5779static const Decl *maybeGetTemplateCursor(const Decl *D) {
5780  if (!D)
5781    return 0;
5782
5783  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5784    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5785      return FunTmpl;
5786
5787  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5788    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5789      return ClassTmpl;
5790
5791  return D;
5792}
5793
5794CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5795  if (clang_isDeclaration(cursor.kind)) {
5796    if (const Decl *D = getCursorDecl(cursor)) {
5797      const DeclContext *DC = D->getDeclContext();
5798      if (!DC)
5799        return clang_getNullCursor();
5800
5801      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5802                          getCursorTU(cursor));
5803    }
5804  }
5805
5806  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5807    if (const Decl *D = getCursorDecl(cursor))
5808      return MakeCXCursor(D, getCursorTU(cursor));
5809  }
5810
5811  return clang_getNullCursor();
5812}
5813
5814CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5815  if (clang_isDeclaration(cursor.kind)) {
5816    if (const Decl *D = getCursorDecl(cursor)) {
5817      const DeclContext *DC = D->getLexicalDeclContext();
5818      if (!DC)
5819        return clang_getNullCursor();
5820
5821      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5822                          getCursorTU(cursor));
5823    }
5824  }
5825
5826  // FIXME: Note that we can't easily compute the lexical context of a
5827  // statement or expression, so we return nothing.
5828  return clang_getNullCursor();
5829}
5830
5831CXFile clang_getIncludedFile(CXCursor cursor) {
5832  if (cursor.kind != CXCursor_InclusionDirective)
5833    return 0;
5834
5835  const InclusionDirective *ID = getCursorInclusionDirective(cursor);
5836  return const_cast<FileEntry *>(ID->getFile());
5837}
5838
5839CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5840  if (!clang_isDeclaration(C.kind))
5841    return clang_getNullRange();
5842
5843  const Decl *D = getCursorDecl(C);
5844  ASTContext &Context = getCursorContext(C);
5845  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5846  if (!RC)
5847    return clang_getNullRange();
5848
5849  return cxloc::translateSourceRange(Context, RC->getSourceRange());
5850}
5851
5852CXString clang_Cursor_getRawCommentText(CXCursor C) {
5853  if (!clang_isDeclaration(C.kind))
5854    return createCXString((const char *) NULL);
5855
5856  const Decl *D = getCursorDecl(C);
5857  ASTContext &Context = getCursorContext(C);
5858  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5859  StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5860                           StringRef();
5861
5862  // Don't duplicate the string because RawText points directly into source
5863  // code.
5864  return createCXString(RawText, false);
5865}
5866
5867CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5868  if (!clang_isDeclaration(C.kind))
5869    return createCXString((const char *) NULL);
5870
5871  const Decl *D = getCursorDecl(C);
5872  const ASTContext &Context = getCursorContext(C);
5873  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5874
5875  if (RC) {
5876    StringRef BriefText = RC->getBriefText(Context);
5877
5878    // Don't duplicate the string because RawComment ensures that this memory
5879    // will not go away.
5880    return createCXString(BriefText, false);
5881  }
5882
5883  return createCXString((const char *) NULL);
5884}
5885
5886CXComment clang_Cursor_getParsedComment(CXCursor C) {
5887  if (!clang_isDeclaration(C.kind))
5888    return cxcomment::createCXComment(NULL, NULL);
5889
5890  const Decl *D = getCursorDecl(C);
5891  const ASTContext &Context = getCursorContext(C);
5892  const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
5893
5894  return cxcomment::createCXComment(FC, getCursorTU(C));
5895}
5896
5897CXModule clang_Cursor_getModule(CXCursor C) {
5898  if (C.kind == CXCursor_ModuleImportDecl) {
5899    if (const ImportDecl *ImportD =
5900            dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5901      return ImportD->getImportedModule();
5902  }
5903
5904  return 0;
5905}
5906
5907CXModule clang_Module_getParent(CXModule CXMod) {
5908  if (!CXMod)
5909    return 0;
5910  Module *Mod = static_cast<Module*>(CXMod);
5911  return Mod->Parent;
5912}
5913
5914CXString clang_Module_getName(CXModule CXMod) {
5915  if (!CXMod)
5916    return createCXString("");
5917  Module *Mod = static_cast<Module*>(CXMod);
5918  return createCXString(Mod->Name);
5919}
5920
5921CXString clang_Module_getFullName(CXModule CXMod) {
5922  if (!CXMod)
5923    return createCXString("");
5924  Module *Mod = static_cast<Module*>(CXMod);
5925  return createCXString(Mod->getFullModuleName());
5926}
5927
5928unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5929  if (!CXMod)
5930    return 0;
5931  Module *Mod = static_cast<Module*>(CXMod);
5932  return Mod->TopHeaders.size();
5933}
5934
5935CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5936  if (!CXMod)
5937    return 0;
5938  Module *Mod = static_cast<Module*>(CXMod);
5939
5940  if (Index < Mod->TopHeaders.size())
5941    return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5942
5943  return 0;
5944}
5945
5946} // end: extern "C"
5947
5948//===----------------------------------------------------------------------===//
5949// C++ AST instrospection.
5950//===----------------------------------------------------------------------===//
5951
5952extern "C" {
5953unsigned clang_CXXMethod_isStatic(CXCursor C) {
5954  if (!clang_isDeclaration(C.kind))
5955    return 0;
5956
5957  const CXXMethodDecl *Method = 0;
5958  const Decl *D = cxcursor::getCursorDecl(C);
5959  if (const FunctionTemplateDecl *FunTmpl =
5960          dyn_cast_or_null<FunctionTemplateDecl>(D))
5961    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5962  else
5963    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5964  return (Method && Method->isStatic()) ? 1 : 0;
5965}
5966
5967unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5968  if (!clang_isDeclaration(C.kind))
5969    return 0;
5970
5971  const CXXMethodDecl *Method = 0;
5972  const Decl *D = cxcursor::getCursorDecl(C);
5973  if (const FunctionTemplateDecl *FunTmpl =
5974          dyn_cast_or_null<FunctionTemplateDecl>(D))
5975    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5976  else
5977    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5978  return (Method && Method->isVirtual()) ? 1 : 0;
5979}
5980} // end: extern "C"
5981
5982//===----------------------------------------------------------------------===//
5983// Attribute introspection.
5984//===----------------------------------------------------------------------===//
5985
5986extern "C" {
5987CXType clang_getIBOutletCollectionType(CXCursor C) {
5988  if (C.kind != CXCursor_IBOutletCollectionAttr)
5989    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5990
5991  IBOutletCollectionAttr *A =
5992    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5993
5994  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5995}
5996} // end: extern "C"
5997
5998//===----------------------------------------------------------------------===//
5999// Inspecting memory usage.
6000//===----------------------------------------------------------------------===//
6001
6002typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
6003
6004static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
6005                                              enum CXTUResourceUsageKind k,
6006                                              unsigned long amount) {
6007  CXTUResourceUsageEntry entry = { k, amount };
6008  entries.push_back(entry);
6009}
6010
6011extern "C" {
6012
6013const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
6014  const char *str = "";
6015  switch (kind) {
6016    case CXTUResourceUsage_AST:
6017      str = "ASTContext: expressions, declarations, and types";
6018      break;
6019    case CXTUResourceUsage_Identifiers:
6020      str = "ASTContext: identifiers";
6021      break;
6022    case CXTUResourceUsage_Selectors:
6023      str = "ASTContext: selectors";
6024      break;
6025    case CXTUResourceUsage_GlobalCompletionResults:
6026      str = "Code completion: cached global results";
6027      break;
6028    case CXTUResourceUsage_SourceManagerContentCache:
6029      str = "SourceManager: content cache allocator";
6030      break;
6031    case CXTUResourceUsage_AST_SideTables:
6032      str = "ASTContext: side tables";
6033      break;
6034    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
6035      str = "SourceManager: malloc'ed memory buffers";
6036      break;
6037    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
6038      str = "SourceManager: mmap'ed memory buffers";
6039      break;
6040    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6041      str = "ExternalASTSource: malloc'ed memory buffers";
6042      break;
6043    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6044      str = "ExternalASTSource: mmap'ed memory buffers";
6045      break;
6046    case CXTUResourceUsage_Preprocessor:
6047      str = "Preprocessor: malloc'ed memory";
6048      break;
6049    case CXTUResourceUsage_PreprocessingRecord:
6050      str = "Preprocessor: PreprocessingRecord";
6051      break;
6052    case CXTUResourceUsage_SourceManager_DataStructures:
6053      str = "SourceManager: data structures and tables";
6054      break;
6055    case CXTUResourceUsage_Preprocessor_HeaderSearch:
6056      str = "Preprocessor: header search tables";
6057      break;
6058  }
6059  return str;
6060}
6061
6062CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
6063  if (!TU) {
6064    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
6065    return usage;
6066  }
6067
6068  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
6069  OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
6070  ASTContext &astContext = astUnit->getASTContext();
6071
6072  // How much memory is used by AST nodes and types?
6073  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
6074    (unsigned long) astContext.getASTAllocatedMemory());
6075
6076  // How much memory is used by identifiers?
6077  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
6078    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6079
6080  // How much memory is used for selectors?
6081  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
6082    (unsigned long) astContext.Selectors.getTotalMemory());
6083
6084  // How much memory is used by ASTContext's side tables?
6085  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6086    (unsigned long) astContext.getSideTableAllocatedMemory());
6087
6088  // How much memory is used for caching global code completion results?
6089  unsigned long completionBytes = 0;
6090  if (GlobalCodeCompletionAllocator *completionAllocator =
6091      astUnit->getCachedCompletionAllocator().getPtr()) {
6092    completionBytes = completionAllocator->getTotalMemory();
6093  }
6094  createCXTUResourceUsageEntry(*entries,
6095                               CXTUResourceUsage_GlobalCompletionResults,
6096                               completionBytes);
6097
6098  // How much memory is being used by SourceManager's content cache?
6099  createCXTUResourceUsageEntry(*entries,
6100          CXTUResourceUsage_SourceManagerContentCache,
6101          (unsigned long) astContext.getSourceManager().getContentCacheSize());
6102
6103  // How much memory is being used by the MemoryBuffer's in SourceManager?
6104  const SourceManager::MemoryBufferSizes &srcBufs =
6105    astUnit->getSourceManager().getMemoryBufferSizes();
6106
6107  createCXTUResourceUsageEntry(*entries,
6108                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6109                               (unsigned long) srcBufs.malloc_bytes);
6110  createCXTUResourceUsageEntry(*entries,
6111                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
6112                               (unsigned long) srcBufs.mmap_bytes);
6113  createCXTUResourceUsageEntry(*entries,
6114                               CXTUResourceUsage_SourceManager_DataStructures,
6115                               (unsigned long) astContext.getSourceManager()
6116                                .getDataStructureSizes());
6117
6118  // How much memory is being used by the ExternalASTSource?
6119  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6120    const ExternalASTSource::MemoryBufferSizes &sizes =
6121      esrc->getMemoryBufferSizes();
6122
6123    createCXTUResourceUsageEntry(*entries,
6124      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6125                                 (unsigned long) sizes.malloc_bytes);
6126    createCXTUResourceUsageEntry(*entries,
6127      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6128                                 (unsigned long) sizes.mmap_bytes);
6129  }
6130
6131  // How much memory is being used by the Preprocessor?
6132  Preprocessor &pp = astUnit->getPreprocessor();
6133  createCXTUResourceUsageEntry(*entries,
6134                               CXTUResourceUsage_Preprocessor,
6135                               pp.getTotalMemory());
6136
6137  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6138    createCXTUResourceUsageEntry(*entries,
6139                                 CXTUResourceUsage_PreprocessingRecord,
6140                                 pRec->getTotalMemory());
6141  }
6142
6143  createCXTUResourceUsageEntry(*entries,
6144                               CXTUResourceUsage_Preprocessor_HeaderSearch,
6145                               pp.getHeaderSearchInfo().getTotalMemory());
6146
6147  CXTUResourceUsage usage = { (void*) entries.get(),
6148                            (unsigned) entries->size(),
6149                            entries->size() ? &(*entries)[0] : 0 };
6150  entries.take();
6151  return usage;
6152}
6153
6154void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
6155  if (usage.data)
6156    delete (MemUsageEntries*) usage.data;
6157}
6158
6159} // end extern "C"
6160
6161void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6162  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6163  for (unsigned I = 0; I != Usage.numEntries; ++I)
6164    fprintf(stderr, "  %s: %lu\n",
6165            clang_getTUResourceUsageName(Usage.entries[I].kind),
6166            Usage.entries[I].amount);
6167
6168  clang_disposeCXTUResourceUsage(Usage);
6169}
6170
6171//===----------------------------------------------------------------------===//
6172// Misc. utility functions.
6173//===----------------------------------------------------------------------===//
6174
6175/// Default to using an 8 MB stack size on "safety" threads.
6176static unsigned SafetyStackThreadSize = 8 << 20;
6177
6178namespace clang {
6179
6180bool RunSafely(llvm::CrashRecoveryContext &CRC,
6181               void (*Fn)(void*), void *UserData,
6182               unsigned Size) {
6183  if (!Size)
6184    Size = GetSafetyThreadStackSize();
6185  if (Size)
6186    return CRC.RunSafelyOnThread(Fn, UserData, Size);
6187  return CRC.RunSafely(Fn, UserData);
6188}
6189
6190unsigned GetSafetyThreadStackSize() {
6191  return SafetyStackThreadSize;
6192}
6193
6194void SetSafetyThreadStackSize(unsigned Value) {
6195  SafetyStackThreadSize = Value;
6196}
6197
6198}
6199
6200void clang::setThreadBackgroundPriority() {
6201  if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6202    return;
6203
6204  // FIXME: Move to llvm/Support and make it cross-platform.
6205#ifdef __APPLE__
6206  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6207#endif
6208}
6209
6210void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6211  if (!Unit)
6212    return;
6213
6214  for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6215                                  DEnd = Unit->stored_diag_end();
6216       D != DEnd; ++D) {
6217    CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6218    CXString Msg = clang_formatDiagnostic(&Diag,
6219                                clang_defaultDiagnosticDisplayOptions());
6220    fprintf(stderr, "%s\n", clang_getCString(Msg));
6221    clang_disposeString(Msg);
6222  }
6223#ifdef LLVM_ON_WIN32
6224  // On Windows, force a flush, since there may be multiple copies of
6225  // stderr and stdout in the file system, all with different buffers
6226  // but writing to the same device.
6227  fflush(stderr);
6228#endif
6229}
6230
6231MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
6232                                 SourceLocation MacroDefLoc,
6233                                 CXTranslationUnit TU){
6234  if (MacroDefLoc.isInvalid() || !TU)
6235    return 0;
6236  if (!II.hadMacroDefinition())
6237    return 0;
6238
6239  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6240  Preprocessor &PP = Unit->getPreprocessor();
6241  MacroInfo *MI = PP.getMacroInfoHistory(&II);
6242  while (MI) {
6243    if (MacroDefLoc == MI->getDefinitionLoc())
6244      return MI;
6245    MI = MI->getPreviousDefinition();
6246  }
6247
6248  return 0;
6249}
6250
6251const MacroInfo *cxindex::getMacroInfo(const MacroDefinition *MacroDef,
6252                                       CXTranslationUnit TU) {
6253  if (!MacroDef || !TU)
6254    return 0;
6255  const IdentifierInfo *II = MacroDef->getName();
6256  if (!II)
6257    return 0;
6258
6259  return getMacroInfo(*II, MacroDef->getLocation(), TU);
6260}
6261
6262MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6263                                                         const Token &Tok,
6264                                                         CXTranslationUnit TU) {
6265  if (!MI || !TU)
6266    return 0;
6267  if (Tok.isNot(tok::raw_identifier))
6268    return 0;
6269
6270  if (MI->getNumTokens() == 0)
6271    return 0;
6272  SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
6273                       MI->getDefinitionEndLoc());
6274  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6275
6276  // Check that the token is inside the definition and not its argument list.
6277  SourceManager &SM = Unit->getSourceManager();
6278  if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
6279    return 0;
6280  if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
6281    return 0;
6282
6283  Preprocessor &PP = Unit->getPreprocessor();
6284  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
6285  if (!PPRec)
6286    return 0;
6287
6288  StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
6289  IdentifierInfo &II = PP.getIdentifierTable().get(Name);
6290  if (!II.hadMacroDefinition())
6291    return 0;
6292
6293  // Check that the identifier is not one of the macro arguments.
6294  if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
6295    return 0;
6296
6297  MacroInfo *InnerMI = PP.getMacroInfoHistory(&II);
6298  if (!InnerMI)
6299    return 0;
6300
6301  return PPRec->findMacroDefinition(InnerMI);
6302}
6303
6304MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6305                                                         SourceLocation Loc,
6306                                                         CXTranslationUnit TU) {
6307  if (Loc.isInvalid() || !MI || !TU)
6308    return 0;
6309
6310  if (MI->getNumTokens() == 0)
6311    return 0;
6312  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6313  Preprocessor &PP = Unit->getPreprocessor();
6314  if (!PP.getPreprocessingRecord())
6315    return 0;
6316  Loc = Unit->getSourceManager().getSpellingLoc(Loc);
6317  Token Tok;
6318  if (PP.getRawToken(Loc, Tok))
6319    return 0;
6320
6321  return checkForMacroInMacroDefinition(MI, Tok, TU);
6322}
6323
6324extern "C" {
6325
6326CXString clang_getClangVersion() {
6327  return createCXString(getClangFullVersion());
6328}
6329
6330} // end: extern "C"
6331
6332Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
6333  if (TU) {
6334    if (ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData)) {
6335      LogOS << '<' << Unit->getMainFileName() << '>';
6336      return *this;
6337    }
6338  }
6339
6340  LogOS << "<NULL TU>";
6341  return *this;
6342}
6343
6344Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
6345  CXFile File;
6346  unsigned Line, Column;
6347  clang_getFileLocation(Loc, &File, &Line, &Column, 0);
6348  CXString FileName = clang_getFileName(File);
6349  *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
6350  clang_disposeString(FileName);
6351  return *this;
6352}
6353
6354Logger &cxindex::Logger::operator<<(CXSourceRange range) {
6355  CXSourceLocation BLoc = clang_getRangeStart(range);
6356  CXSourceLocation ELoc = clang_getRangeEnd(range);
6357
6358  CXFile BFile;
6359  unsigned BLine, BColumn;
6360  clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, 0);
6361
6362  CXFile EFile;
6363  unsigned ELine, EColumn;
6364  clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, 0);
6365
6366  CXString BFileName = clang_getFileName(BFile);
6367  if (BFile == EFile) {
6368    *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
6369                         BLine, BColumn, ELine, EColumn);
6370  } else {
6371    CXString EFileName = clang_getFileName(EFile);
6372    *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
6373                          BLine, BColumn)
6374          << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
6375                          ELine, EColumn);
6376    clang_disposeString(EFileName);
6377  }
6378  clang_disposeString(BFileName);
6379  return *this;
6380}
6381
6382Logger &cxindex::Logger::operator<<(CXString Str) {
6383  *this << clang_getCString(Str);
6384  return *this;
6385}
6386
6387Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
6388  LogOS << Fmt;
6389  return *this;
6390}
6391
6392cxindex::Logger::~Logger() {
6393  LogOS.flush();
6394
6395  llvm::sys::ScopedLock L(EnableMultithreadingMutex);
6396
6397  static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
6398
6399  raw_ostream &OS = llvm::errs();
6400  OS << "[libclang:" << Name << ':';
6401
6402  // FIXME: Portability.
6403#if HAVE_PTHREAD_H && __APPLE__
6404  mach_port_t tid = pthread_mach_thread_np(pthread_self());
6405  OS << tid << ':';
6406#endif
6407
6408  llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
6409  OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
6410  OS << Msg.str() << '\n';
6411
6412  if (Trace) {
6413    llvm::sys::PrintStackTrace(stderr);
6414    OS << "--------------------------------------------------\n";
6415  }
6416}
6417