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