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