CIndex.cpp revision 1836db0f2c7527ac11af0044ab89150f9aaf22e1
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  llvm_unreachable("Invalid CXChildVisitResult!");
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(SM.getFileLoc(R.getBegin()));
197    if (FID != SM.getFileID(SM.getFileLoc(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    if (TagDecl *TD = dyn_cast<TagDecl>(D))
301      if (!TD->isFreeStanding())
302        continue;
303
304    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
305    if (CompRes == RangeBefore)
306      continue;
307    if (CompRes == RangeAfter)
308      break;
309
310    assert(CompRes == RangeOverlap);
311    VisitedAtLeastOnce = true;
312
313    if (isa<ObjCContainerDecl>(D)) {
314      FileDI_current = &DIt;
315      FileDE_current = DE;
316    } else {
317      FileDI_current = 0;
318    }
319
320    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
321      break;
322  }
323
324  if (VisitedAtLeastOnce)
325    return;
326
327  // No Decls overlapped with the range. Move up the lexical context until there
328  // is a context that contains the range or we reach the translation unit
329  // level.
330  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
331                                         : (*(DIt-1))->getLexicalDeclContext();
332
333  while (DC && !DC->isTranslationUnit()) {
334    Decl *D = cast<Decl>(DC);
335    SourceRange CurDeclRange = D->getSourceRange();
336    if (CurDeclRange.isInvalid())
337      break;
338
339    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
340      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
341      break;
342    }
343
344    DC = D->getLexicalDeclContext();
345  }
346}
347
348bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
349  if (!AU->getPreprocessor().getPreprocessingRecord())
350    return false;
351
352  PreprocessingRecord &PPRec
353    = *AU->getPreprocessor().getPreprocessingRecord();
354  SourceManager &SM = AU->getSourceManager();
355
356  if (RegionOfInterest.isValid()) {
357    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
358    SourceLocation B = MappedRange.getBegin();
359    SourceLocation E = MappedRange.getEnd();
360
361    if (AU->isInPreambleFileID(B)) {
362      if (SM.isLoadedSourceLocation(E))
363        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
364                                                 PPRec, *this);
365
366      // Beginning of range lies in the preamble but it also extends beyond
367      // it into the main file. Split the range into 2 parts, one covering
368      // the preamble and another covering the main file. This allows subsequent
369      // calls to visitPreprocessedEntitiesInRange to accept a source range that
370      // lies in the same FileID, allowing it to skip preprocessed entities that
371      // do not come from the same FileID.
372      bool breaked =
373        visitPreprocessedEntitiesInRange(
374                                   SourceRange(B, AU->getEndOfPreambleFileID()),
375                                          PPRec, *this);
376      if (breaked) return true;
377      return visitPreprocessedEntitiesInRange(
378                                    SourceRange(AU->getStartOfMainFileID(), E),
379                                        PPRec, *this);
380    }
381
382    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
383  }
384
385  bool OnlyLocalDecls
386    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
387
388  if (OnlyLocalDecls)
389    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
390                                     PPRec);
391
392  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
393}
394
395template<typename InputIterator>
396bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
397                                              InputIterator Last,
398                                              PreprocessingRecord &PPRec,
399                                              FileID FID) {
400  for (; First != Last; ++First) {
401    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
402      continue;
403
404    PreprocessedEntity *PPE = *First;
405    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
406      if (Visit(MakeMacroExpansionCursor(ME, TU)))
407        return true;
408
409      continue;
410    }
411
412    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
413      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
414        return true;
415
416      continue;
417    }
418
419    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
420      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
421        return true;
422
423      continue;
424    }
425  }
426
427  return false;
428}
429
430/// \brief Visit the children of the given cursor.
431///
432/// \returns true if the visitation should be aborted, false if it
433/// should continue.
434bool CursorVisitor::VisitChildren(CXCursor Cursor) {
435  if (clang_isReference(Cursor.kind) &&
436      Cursor.kind != CXCursor_CXXBaseSpecifier) {
437    // By definition, references have no children.
438    return false;
439  }
440
441  // Set the Parent field to Cursor, then back to its old value once we're
442  // done.
443  SetParentRAII SetParent(Parent, StmtParent, Cursor);
444
445  if (clang_isDeclaration(Cursor.kind)) {
446    Decl *D = getCursorDecl(Cursor);
447    if (!D)
448      return false;
449
450    return VisitAttributes(D) || Visit(D);
451  }
452
453  if (clang_isStatement(Cursor.kind)) {
454    if (Stmt *S = getCursorStmt(Cursor))
455      return Visit(S);
456
457    return false;
458  }
459
460  if (clang_isExpression(Cursor.kind)) {
461    if (Expr *E = getCursorExpr(Cursor))
462      return Visit(E);
463
464    return false;
465  }
466
467  if (clang_isTranslationUnit(Cursor.kind)) {
468    CXTranslationUnit tu = getCursorTU(Cursor);
469    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
470
471    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
472    for (unsigned I = 0; I != 2; ++I) {
473      if (VisitOrder[I]) {
474        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
475            RegionOfInterest.isInvalid()) {
476          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
477                                        TLEnd = CXXUnit->top_level_end();
478               TL != TLEnd; ++TL) {
479            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
480              return true;
481          }
482        } else if (VisitDeclContext(
483                                CXXUnit->getASTContext().getTranslationUnitDecl()))
484          return true;
485        continue;
486      }
487
488      // Walk the preprocessing record.
489      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
490        visitPreprocessedEntitiesInRegion();
491    }
492
493    return false;
494  }
495
496  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
497    if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
498      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
499        return Visit(BaseTSInfo->getTypeLoc());
500      }
501    }
502  }
503
504  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
505    IBOutletCollectionAttr *A =
506      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
507    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
508      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
509                                                    A->getInterfaceLoc(), TU));
510  }
511
512  // Nothing to visit at the moment.
513  return false;
514}
515
516bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
517  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
518    if (Visit(TSInfo->getTypeLoc()))
519        return true;
520
521  if (Stmt *Body = B->getBody())
522    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
523
524  return false;
525}
526
527llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
528  if (RegionOfInterest.isValid()) {
529    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
530    if (Range.isInvalid())
531      return llvm::Optional<bool>();
532
533    switch (CompareRegionOfInterest(Range)) {
534    case RangeBefore:
535      // This declaration comes before the region of interest; skip it.
536      return llvm::Optional<bool>();
537
538    case RangeAfter:
539      // This declaration comes after the region of interest; we're done.
540      return false;
541
542    case RangeOverlap:
543      // This declaration overlaps the region of interest; visit it.
544      break;
545    }
546  }
547  return true;
548}
549
550bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
551  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
552
553  // FIXME: Eventually remove.  This part of a hack to support proper
554  // iteration over all Decls contained lexically within an ObjC container.
555  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
556  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
557
558  for ( ; I != E; ++I) {
559    Decl *D = *I;
560    if (D->getLexicalDeclContext() != DC)
561      continue;
562    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
563
564    // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
565    // declarations is a mismatch with the compiler semantics.
566    if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
567      ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
568      if (!ID->isThisDeclarationADefinition())
569        Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
570
571    } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
572      ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
573      if (!PD->isThisDeclarationADefinition())
574        Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
575    }
576
577    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
578    if (!V.hasValue())
579      continue;
580    if (!V.getValue())
581      return false;
582    if (Visit(Cursor, true))
583      return true;
584  }
585  return false;
586}
587
588bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
589  llvm_unreachable("Translation units are visited directly by Visit()");
590}
591
592bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
593  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594    return Visit(TSInfo->getTypeLoc());
595
596  return false;
597}
598
599bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
600  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
601    return Visit(TSInfo->getTypeLoc());
602
603  return false;
604}
605
606bool CursorVisitor::VisitTagDecl(TagDecl *D) {
607  return VisitDeclContext(D);
608}
609
610bool CursorVisitor::VisitClassTemplateSpecializationDecl(
611                                          ClassTemplateSpecializationDecl *D) {
612  bool ShouldVisitBody = false;
613  switch (D->getSpecializationKind()) {
614  case TSK_Undeclared:
615  case TSK_ImplicitInstantiation:
616    // Nothing to visit
617    return false;
618
619  case TSK_ExplicitInstantiationDeclaration:
620  case TSK_ExplicitInstantiationDefinition:
621    break;
622
623  case TSK_ExplicitSpecialization:
624    ShouldVisitBody = true;
625    break;
626  }
627
628  // Visit the template arguments used in the specialization.
629  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
630    TypeLoc TL = SpecType->getTypeLoc();
631    if (TemplateSpecializationTypeLoc *TSTLoc
632          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
633      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
634        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
635          return true;
636    }
637  }
638
639  if (ShouldVisitBody && VisitCXXRecordDecl(D))
640    return true;
641
642  return false;
643}
644
645bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
646                                   ClassTemplatePartialSpecializationDecl *D) {
647  // FIXME: Visit the "outer" template parameter lists on the TagDecl
648  // before visiting these template parameters.
649  if (VisitTemplateParameters(D->getTemplateParameters()))
650    return true;
651
652  // Visit the partial specialization arguments.
653  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
654  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
655    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
656      return true;
657
658  return VisitCXXRecordDecl(D);
659}
660
661bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
662  // Visit the default argument.
663  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
664    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
665      if (Visit(DefArg->getTypeLoc()))
666        return true;
667
668  return false;
669}
670
671bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
672  if (Expr *Init = D->getInitExpr())
673    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
674  return false;
675}
676
677bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
678  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
679    if (Visit(TSInfo->getTypeLoc()))
680      return true;
681
682  // Visit the nested-name-specifier, if present.
683  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
684    if (VisitNestedNameSpecifierLoc(QualifierLoc))
685      return true;
686
687  return false;
688}
689
690/// \brief Compare two base or member initializers based on their source order.
691static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
692  CXXCtorInitializer const * const *X
693    = static_cast<CXXCtorInitializer const * const *>(Xp);
694  CXXCtorInitializer const * const *Y
695    = static_cast<CXXCtorInitializer const * const *>(Yp);
696
697  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
698    return -1;
699  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
700    return 1;
701  else
702    return 0;
703}
704
705bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
706  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
707    // Visit the function declaration's syntactic components in the order
708    // written. This requires a bit of work.
709    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
710    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
711
712    // If we have a function declared directly (without the use of a typedef),
713    // visit just the return type. Otherwise, just visit the function's type
714    // now.
715    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
716        (!FTL && Visit(TL)))
717      return true;
718
719    // Visit the nested-name-specifier, if present.
720    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
721      if (VisitNestedNameSpecifierLoc(QualifierLoc))
722        return true;
723
724    // Visit the declaration name.
725    if (VisitDeclarationNameInfo(ND->getNameInfo()))
726      return true;
727
728    // FIXME: Visit explicitly-specified template arguments!
729
730    // Visit the function parameters, if we have a function type.
731    if (FTL && VisitFunctionTypeLoc(*FTL, true))
732      return true;
733
734    // FIXME: Attributes?
735  }
736
737  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
738    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
739      // Find the initializers that were written in the source.
740      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
741      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
742                                          IEnd = Constructor->init_end();
743           I != IEnd; ++I) {
744        if (!(*I)->isWritten())
745          continue;
746
747        WrittenInits.push_back(*I);
748      }
749
750      // Sort the initializers in source order
751      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
752                           &CompareCXXCtorInitializers);
753
754      // Visit the initializers in source order
755      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
756        CXXCtorInitializer *Init = WrittenInits[I];
757        if (Init->isAnyMemberInitializer()) {
758          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
759                                        Init->getMemberLocation(), TU)))
760            return true;
761        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
762          if (Visit(TInfo->getTypeLoc()))
763            return true;
764        }
765
766        // Visit the initializer value.
767        if (Expr *Initializer = Init->getInit())
768          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
769            return true;
770      }
771    }
772
773    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
774      return true;
775  }
776
777  return false;
778}
779
780bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
781  if (VisitDeclaratorDecl(D))
782    return true;
783
784  if (Expr *BitWidth = D->getBitWidth())
785    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
786
787  return false;
788}
789
790bool CursorVisitor::VisitVarDecl(VarDecl *D) {
791  if (VisitDeclaratorDecl(D))
792    return true;
793
794  if (Expr *Init = D->getInit())
795    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
796
797  return false;
798}
799
800bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
801  if (VisitDeclaratorDecl(D))
802    return true;
803
804  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
805    if (Expr *DefArg = D->getDefaultArgument())
806      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
807
808  return false;
809}
810
811bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
812  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
813  // before visiting these template parameters.
814  if (VisitTemplateParameters(D->getTemplateParameters()))
815    return true;
816
817  return VisitFunctionDecl(D->getTemplatedDecl());
818}
819
820bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
821  // FIXME: Visit the "outer" template parameter lists on the TagDecl
822  // before visiting these template parameters.
823  if (VisitTemplateParameters(D->getTemplateParameters()))
824    return true;
825
826  return VisitCXXRecordDecl(D->getTemplatedDecl());
827}
828
829bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
830  if (VisitTemplateParameters(D->getTemplateParameters()))
831    return true;
832
833  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
834      VisitTemplateArgumentLoc(D->getDefaultArgument()))
835    return true;
836
837  return false;
838}
839
840bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
841  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
842    if (Visit(TSInfo->getTypeLoc()))
843      return true;
844
845  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
846       PEnd = ND->param_end();
847       P != PEnd; ++P) {
848    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
849      return true;
850  }
851
852  if (ND->isThisDeclarationADefinition() &&
853      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
854    return true;
855
856  return false;
857}
858
859template <typename DeclIt>
860static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
861                                      SourceManager &SM, SourceLocation EndLoc,
862                                      SmallVectorImpl<Decl *> &Decls) {
863  DeclIt next = *DI_current;
864  while (++next != DE_current) {
865    Decl *D_next = *next;
866    if (!D_next)
867      break;
868    SourceLocation L = D_next->getLocStart();
869    if (!L.isValid())
870      break;
871    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
872      *DI_current = next;
873      Decls.push_back(D_next);
874      continue;
875    }
876    break;
877  }
878}
879
880namespace {
881  struct ContainerDeclsSort {
882    SourceManager &SM;
883    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
884    bool operator()(Decl *A, Decl *B) {
885      SourceLocation L_A = A->getLocStart();
886      SourceLocation L_B = B->getLocStart();
887      assert(L_A.isValid() && L_B.isValid());
888      return SM.isBeforeInTranslationUnit(L_A, L_B);
889    }
890  };
891}
892
893bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
894  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
895  // an @implementation can lexically contain Decls that are not properly
896  // nested in the AST.  When we identify such cases, we need to retrofit
897  // this nesting here.
898  if (!DI_current && !FileDI_current)
899    return VisitDeclContext(D);
900
901  // Scan the Decls that immediately come after the container
902  // in the current DeclContext.  If any fall within the
903  // container's lexical region, stash them into a vector
904  // for later processing.
905  SmallVector<Decl *, 24> DeclsInContainer;
906  SourceLocation EndLoc = D->getSourceRange().getEnd();
907  SourceManager &SM = AU->getSourceManager();
908  if (EndLoc.isValid()) {
909    if (DI_current) {
910      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
911                                DeclsInContainer);
912    } else {
913      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
914                                DeclsInContainer);
915    }
916  }
917
918  // The common case.
919  if (DeclsInContainer.empty())
920    return VisitDeclContext(D);
921
922  // Get all the Decls in the DeclContext, and sort them with the
923  // additional ones we've collected.  Then visit them.
924  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
925       I!=E; ++I) {
926    Decl *subDecl = *I;
927    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
928        subDecl->getLocStart().isInvalid())
929      continue;
930    DeclsInContainer.push_back(subDecl);
931  }
932
933  // Now sort the Decls so that they appear in lexical order.
934  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
935            ContainerDeclsSort(SM));
936
937  // Now visit the decls.
938  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
939         E = DeclsInContainer.end(); I != E; ++I) {
940    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
941    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
942    if (!V.hasValue())
943      continue;
944    if (!V.getValue())
945      return false;
946    if (Visit(Cursor, true))
947      return true;
948  }
949  return false;
950}
951
952bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
953  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
954                                   TU)))
955    return true;
956
957  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
958  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
959         E = ND->protocol_end(); I != E; ++I, ++PL)
960    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
961      return true;
962
963  return VisitObjCContainerDecl(ND);
964}
965
966bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
967  if (!PID->isThisDeclarationADefinition())
968    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
969
970  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
971  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
972       E = PID->protocol_end(); I != E; ++I, ++PL)
973    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
974      return true;
975
976  return VisitObjCContainerDecl(PID);
977}
978
979bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
980  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
981    return true;
982
983  // FIXME: This implements a workaround with @property declarations also being
984  // installed in the DeclContext for the @interface.  Eventually this code
985  // should be removed.
986  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
987  if (!CDecl || !CDecl->IsClassExtension())
988    return false;
989
990  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
991  if (!ID)
992    return false;
993
994  IdentifierInfo *PropertyId = PD->getIdentifier();
995  ObjCPropertyDecl *prevDecl =
996    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
997
998  if (!prevDecl)
999    return false;
1000
1001  // Visit synthesized methods since they will be skipped when visiting
1002  // the @interface.
1003  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1004    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1005      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1006        return true;
1007
1008  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1009    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1010      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1011        return true;
1012
1013  return false;
1014}
1015
1016bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1017  if (!D->isThisDeclarationADefinition()) {
1018    // Forward declaration is treated like a reference.
1019    return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1020  }
1021
1022  // Issue callbacks for super class.
1023  if (D->getSuperClass() &&
1024      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1025                                        D->getSuperClassLoc(),
1026                                        TU)))
1027    return true;
1028
1029  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1030  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1031         E = D->protocol_end(); I != E; ++I, ++PL)
1032    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1033      return true;
1034
1035  return VisitObjCContainerDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1039  return VisitObjCContainerDecl(D);
1040}
1041
1042bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1043  // 'ID' could be null when dealing with invalid code.
1044  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1045    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1046      return true;
1047
1048  return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1052#if 0
1053  // Issue callbacks for super class.
1054  // FIXME: No source location information!
1055  if (D->getSuperClass() &&
1056      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1057                                        D->getSuperClassLoc(),
1058                                        TU)))
1059    return true;
1060#endif
1061
1062  return VisitObjCImplDecl(D);
1063}
1064
1065bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1066  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1067    return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1068
1069  return false;
1070}
1071
1072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073  return VisitDeclContext(D);
1074}
1075
1076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1077  // Visit nested-name-specifier.
1078  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1079    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1080      return true;
1081
1082  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083                                      D->getTargetNameLoc(), TU));
1084}
1085
1086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1087  // Visit nested-name-specifier.
1088  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1089    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1090      return true;
1091  }
1092
1093  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1094    return true;
1095
1096  return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
1099bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1100  // Visit nested-name-specifier.
1101  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1103      return true;
1104
1105  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1106                                      D->getIdentLocation(), TU));
1107}
1108
1109bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1110  // Visit nested-name-specifier.
1111  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1112    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1113      return true;
1114  }
1115
1116  return VisitDeclarationNameInfo(D->getNameInfo());
1117}
1118
1119bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1120                                               UnresolvedUsingTypenameDecl *D) {
1121  // Visit nested-name-specifier.
1122  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1124      return true;
1125
1126  return false;
1127}
1128
1129bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1130  switch (Name.getName().getNameKind()) {
1131  case clang::DeclarationName::Identifier:
1132  case clang::DeclarationName::CXXLiteralOperatorName:
1133  case clang::DeclarationName::CXXOperatorName:
1134  case clang::DeclarationName::CXXUsingDirective:
1135    return false;
1136
1137  case clang::DeclarationName::CXXConstructorName:
1138  case clang::DeclarationName::CXXDestructorName:
1139  case clang::DeclarationName::CXXConversionFunctionName:
1140    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1141      return Visit(TSInfo->getTypeLoc());
1142    return false;
1143
1144  case clang::DeclarationName::ObjCZeroArgSelector:
1145  case clang::DeclarationName::ObjCOneArgSelector:
1146  case clang::DeclarationName::ObjCMultiArgSelector:
1147    // FIXME: Per-identifier location info?
1148    return false;
1149  }
1150
1151  llvm_unreachable("Invalid DeclarationName::Kind!");
1152}
1153
1154bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1155                                             SourceRange Range) {
1156  // FIXME: This whole routine is a hack to work around the lack of proper
1157  // source information in nested-name-specifiers (PR5791). Since we do have
1158  // a beginning source location, we can visit the first component of the
1159  // nested-name-specifier, if it's a single-token component.
1160  if (!NNS)
1161    return false;
1162
1163  // Get the first component in the nested-name-specifier.
1164  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1165    NNS = Prefix;
1166
1167  switch (NNS->getKind()) {
1168  case NestedNameSpecifier::Namespace:
1169    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170                                        TU));
1171
1172  case NestedNameSpecifier::NamespaceAlias:
1173    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1174                                        Range.getBegin(), TU));
1175
1176  case NestedNameSpecifier::TypeSpec: {
1177    // If the type has a form where we know that the beginning of the source
1178    // range matches up with a reference cursor. Visit the appropriate reference
1179    // cursor.
1180    const Type *T = NNS->getAsType();
1181    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1182      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1183    if (const TagType *Tag = dyn_cast<TagType>(T))
1184      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1185    if (const TemplateSpecializationType *TST
1186                                      = dyn_cast<TemplateSpecializationType>(T))
1187      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1188    break;
1189  }
1190
1191  case NestedNameSpecifier::TypeSpecWithTemplate:
1192  case NestedNameSpecifier::Global:
1193  case NestedNameSpecifier::Identifier:
1194    break;
1195  }
1196
1197  return false;
1198}
1199
1200bool
1201CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1202  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1203  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1204    Qualifiers.push_back(Qualifier);
1205
1206  while (!Qualifiers.empty()) {
1207    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1208    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1209    switch (NNS->getKind()) {
1210    case NestedNameSpecifier::Namespace:
1211      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1212                                       Q.getLocalBeginLoc(),
1213                                       TU)))
1214        return true;
1215
1216      break;
1217
1218    case NestedNameSpecifier::NamespaceAlias:
1219      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1220                                       Q.getLocalBeginLoc(),
1221                                       TU)))
1222        return true;
1223
1224      break;
1225
1226    case NestedNameSpecifier::TypeSpec:
1227    case NestedNameSpecifier::TypeSpecWithTemplate:
1228      if (Visit(Q.getTypeLoc()))
1229        return true;
1230
1231      break;
1232
1233    case NestedNameSpecifier::Global:
1234    case NestedNameSpecifier::Identifier:
1235      break;
1236    }
1237  }
1238
1239  return false;
1240}
1241
1242bool CursorVisitor::VisitTemplateParameters(
1243                                          const TemplateParameterList *Params) {
1244  if (!Params)
1245    return false;
1246
1247  for (TemplateParameterList::const_iterator P = Params->begin(),
1248                                          PEnd = Params->end();
1249       P != PEnd; ++P) {
1250    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1251      return true;
1252  }
1253
1254  return false;
1255}
1256
1257bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1258  switch (Name.getKind()) {
1259  case TemplateName::Template:
1260    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1261
1262  case TemplateName::OverloadedTemplate:
1263    // Visit the overloaded template set.
1264    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1265      return true;
1266
1267    return false;
1268
1269  case TemplateName::DependentTemplate:
1270    // FIXME: Visit nested-name-specifier.
1271    return false;
1272
1273  case TemplateName::QualifiedTemplate:
1274    // FIXME: Visit nested-name-specifier.
1275    return Visit(MakeCursorTemplateRef(
1276                                  Name.getAsQualifiedTemplateName()->getDecl(),
1277                                       Loc, TU));
1278
1279  case TemplateName::SubstTemplateTemplateParm:
1280    return Visit(MakeCursorTemplateRef(
1281                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1282                                       Loc, TU));
1283
1284  case TemplateName::SubstTemplateTemplateParmPack:
1285    return Visit(MakeCursorTemplateRef(
1286                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1287                                       Loc, TU));
1288  }
1289
1290  llvm_unreachable("Invalid TemplateName::Kind!");
1291}
1292
1293bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1294  switch (TAL.getArgument().getKind()) {
1295  case TemplateArgument::Null:
1296  case TemplateArgument::Integral:
1297  case TemplateArgument::Pack:
1298    return false;
1299
1300  case TemplateArgument::Type:
1301    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1302      return Visit(TSInfo->getTypeLoc());
1303    return false;
1304
1305  case TemplateArgument::Declaration:
1306    if (Expr *E = TAL.getSourceDeclExpression())
1307      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1308    return false;
1309
1310  case TemplateArgument::Expression:
1311    if (Expr *E = TAL.getSourceExpression())
1312      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1313    return false;
1314
1315  case TemplateArgument::Template:
1316  case TemplateArgument::TemplateExpansion:
1317    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1318      return true;
1319
1320    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1321                             TAL.getTemplateNameLoc());
1322  }
1323
1324  llvm_unreachable("Invalid TemplateArgument::Kind!");
1325}
1326
1327bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1328  return VisitDeclContext(D);
1329}
1330
1331bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1332  return Visit(TL.getUnqualifiedLoc());
1333}
1334
1335bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1336  ASTContext &Context = AU->getASTContext();
1337
1338  // Some builtin types (such as Objective-C's "id", "sel", and
1339  // "Class") have associated declarations. Create cursors for those.
1340  QualType VisitType;
1341  switch (TL.getTypePtr()->getKind()) {
1342
1343  case BuiltinType::Void:
1344  case BuiltinType::NullPtr:
1345  case BuiltinType::Dependent:
1346#define BUILTIN_TYPE(Id, SingletonId)
1347#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1348#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1349#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#include "clang/AST/BuiltinTypes.def"
1352    break;
1353
1354  case BuiltinType::ObjCId:
1355    VisitType = Context.getObjCIdType();
1356    break;
1357
1358  case BuiltinType::ObjCClass:
1359    VisitType = Context.getObjCClassType();
1360    break;
1361
1362  case BuiltinType::ObjCSel:
1363    VisitType = Context.getObjCSelType();
1364    break;
1365  }
1366
1367  if (!VisitType.isNull()) {
1368    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1369      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1370                                     TU));
1371  }
1372
1373  return false;
1374}
1375
1376bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1377  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1378}
1379
1380bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1381  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1382}
1383
1384bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1385  if (TL.isDefinition())
1386    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1387
1388  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1389}
1390
1391bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1392  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1393}
1394
1395bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1396  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1397    return true;
1398
1399  return false;
1400}
1401
1402bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1403  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1404    return true;
1405
1406  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1407    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1408                                        TU)))
1409      return true;
1410  }
1411
1412  return false;
1413}
1414
1415bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1416  return Visit(TL.getPointeeLoc());
1417}
1418
1419bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1420  return Visit(TL.getInnerLoc());
1421}
1422
1423bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1424  return Visit(TL.getPointeeLoc());
1425}
1426
1427bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1428  return Visit(TL.getPointeeLoc());
1429}
1430
1431bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1432  return Visit(TL.getPointeeLoc());
1433}
1434
1435bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1436  return Visit(TL.getPointeeLoc());
1437}
1438
1439bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1440  return Visit(TL.getPointeeLoc());
1441}
1442
1443bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1444  return Visit(TL.getModifiedLoc());
1445}
1446
1447bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1448                                         bool SkipResultType) {
1449  if (!SkipResultType && Visit(TL.getResultLoc()))
1450    return true;
1451
1452  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1453    if (Decl *D = TL.getArg(I))
1454      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1455        return true;
1456
1457  return false;
1458}
1459
1460bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1461  if (Visit(TL.getElementLoc()))
1462    return true;
1463
1464  if (Expr *Size = TL.getSizeExpr())
1465    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1466
1467  return false;
1468}
1469
1470bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1471                                             TemplateSpecializationTypeLoc TL) {
1472  // Visit the template name.
1473  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1474                        TL.getTemplateNameLoc()))
1475    return true;
1476
1477  // Visit the template arguments.
1478  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1479    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1480      return true;
1481
1482  return false;
1483}
1484
1485bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1486  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1487}
1488
1489bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1490  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1491    return Visit(TSInfo->getTypeLoc());
1492
1493  return false;
1494}
1495
1496bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1497  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1498    return Visit(TSInfo->getTypeLoc());
1499
1500  return false;
1501}
1502
1503bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1504  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1505    return true;
1506
1507  return false;
1508}
1509
1510bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1511                                    DependentTemplateSpecializationTypeLoc TL) {
1512  // Visit the nested-name-specifier, if there is one.
1513  if (TL.getQualifierLoc() &&
1514      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1515    return true;
1516
1517  // Visit the template arguments.
1518  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1519    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1520      return true;
1521
1522  return false;
1523}
1524
1525bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1526  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1527    return true;
1528
1529  return Visit(TL.getNamedTypeLoc());
1530}
1531
1532bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1533  return Visit(TL.getPatternLoc());
1534}
1535
1536bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1537  if (Expr *E = TL.getUnderlyingExpr())
1538    return Visit(MakeCXCursor(E, StmtParent, TU));
1539
1540  return false;
1541}
1542
1543bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1544  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1545}
1546
1547bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1548  return Visit(TL.getValueLoc());
1549}
1550
1551#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1552bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1553  return Visit##PARENT##Loc(TL); \
1554}
1555
1556DEFAULT_TYPELOC_IMPL(Complex, Type)
1557DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1558DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1559DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1562DEFAULT_TYPELOC_IMPL(Vector, Type)
1563DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1564DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1565DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1566DEFAULT_TYPELOC_IMPL(Record, TagType)
1567DEFAULT_TYPELOC_IMPL(Enum, TagType)
1568DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1569DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1570DEFAULT_TYPELOC_IMPL(Auto, Type)
1571
1572bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1573  // Visit the nested-name-specifier, if present.
1574  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1575    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1576      return true;
1577
1578  if (D->isCompleteDefinition()) {
1579    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1580         E = D->bases_end(); I != E; ++I) {
1581      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1582        return true;
1583    }
1584  }
1585
1586  return VisitTagDecl(D);
1587}
1588
1589bool CursorVisitor::VisitAttributes(Decl *D) {
1590  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1591       i != e; ++i)
1592    if (Visit(MakeCXCursor(*i, D, TU)))
1593        return true;
1594
1595  return false;
1596}
1597
1598//===----------------------------------------------------------------------===//
1599// Data-recursive visitor methods.
1600//===----------------------------------------------------------------------===//
1601
1602namespace {
1603#define DEF_JOB(NAME, DATA, KIND)\
1604class NAME : public VisitorJob {\
1605public:\
1606  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1607  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1608  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1609};
1610
1611DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1612DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1613DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1614DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1615DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1616        ExplicitTemplateArgsVisitKind)
1617DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1618#undef DEF_JOB
1619
1620class DeclVisit : public VisitorJob {
1621public:
1622  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1623    VisitorJob(parent, VisitorJob::DeclVisitKind,
1624               d, isFirst ? (void*) 1 : (void*) 0) {}
1625  static bool classof(const VisitorJob *VJ) {
1626    return VJ->getKind() == DeclVisitKind;
1627  }
1628  Decl *get() const { return static_cast<Decl*>(data[0]); }
1629  bool isFirst() const { return data[1] ? true : false; }
1630};
1631class TypeLocVisit : public VisitorJob {
1632public:
1633  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1634    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1635               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1636
1637  static bool classof(const VisitorJob *VJ) {
1638    return VJ->getKind() == TypeLocVisitKind;
1639  }
1640
1641  TypeLoc get() const {
1642    QualType T = QualType::getFromOpaquePtr(data[0]);
1643    return TypeLoc(T, data[1]);
1644  }
1645};
1646
1647class LabelRefVisit : public VisitorJob {
1648public:
1649  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1650    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1651                 labelLoc.getPtrEncoding()) {}
1652
1653  static bool classof(const VisitorJob *VJ) {
1654    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1655  }
1656  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1657  SourceLocation getLoc() const {
1658    return SourceLocation::getFromPtrEncoding(data[1]); }
1659};
1660
1661class NestedNameSpecifierLocVisit : public VisitorJob {
1662public:
1663  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1664    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1665                 Qualifier.getNestedNameSpecifier(),
1666                 Qualifier.getOpaqueData()) { }
1667
1668  static bool classof(const VisitorJob *VJ) {
1669    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1670  }
1671
1672  NestedNameSpecifierLoc get() const {
1673    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1674                                  data[1]);
1675  }
1676};
1677
1678class DeclarationNameInfoVisit : public VisitorJob {
1679public:
1680  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1681    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1682  static bool classof(const VisitorJob *VJ) {
1683    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1684  }
1685  DeclarationNameInfo get() const {
1686    Stmt *S = static_cast<Stmt*>(data[0]);
1687    switch (S->getStmtClass()) {
1688    default:
1689      llvm_unreachable("Unhandled Stmt");
1690    case clang::Stmt::MSDependentExistsStmtClass:
1691      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1692    case Stmt::CXXDependentScopeMemberExprClass:
1693      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1694    case Stmt::DependentScopeDeclRefExprClass:
1695      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1696    }
1697  }
1698};
1699class MemberRefVisit : public VisitorJob {
1700public:
1701  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1702    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1703                 L.getPtrEncoding()) {}
1704  static bool classof(const VisitorJob *VJ) {
1705    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1706  }
1707  FieldDecl *get() const {
1708    return static_cast<FieldDecl*>(data[0]);
1709  }
1710  SourceLocation getLoc() const {
1711    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1712  }
1713};
1714class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1715  VisitorWorkList &WL;
1716  CXCursor Parent;
1717public:
1718  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1719    : WL(wl), Parent(parent) {}
1720
1721  void VisitAddrLabelExpr(AddrLabelExpr *E);
1722  void VisitBlockExpr(BlockExpr *B);
1723  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1724  void VisitCompoundStmt(CompoundStmt *S);
1725  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1726  void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1727  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1728  void VisitCXXNewExpr(CXXNewExpr *E);
1729  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1730  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1731  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1732  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1733  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1734  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1735  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1736  void VisitCXXCatchStmt(CXXCatchStmt *S);
1737  void VisitDeclRefExpr(DeclRefExpr *D);
1738  void VisitDeclStmt(DeclStmt *S);
1739  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1740  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1741  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1742  void VisitForStmt(ForStmt *FS);
1743  void VisitGotoStmt(GotoStmt *GS);
1744  void VisitIfStmt(IfStmt *If);
1745  void VisitInitListExpr(InitListExpr *IE);
1746  void VisitMemberExpr(MemberExpr *M);
1747  void VisitOffsetOfExpr(OffsetOfExpr *E);
1748  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1749  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1750  void VisitOverloadExpr(OverloadExpr *E);
1751  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1752  void VisitStmt(Stmt *S);
1753  void VisitSwitchStmt(SwitchStmt *S);
1754  void VisitWhileStmt(WhileStmt *W);
1755  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1756  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1757  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1758  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1759  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1760  void VisitVAArgExpr(VAArgExpr *E);
1761  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1762  void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1763  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1764
1765private:
1766  void AddDeclarationNameInfo(Stmt *S);
1767  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1768  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1769  void AddMemberRef(FieldDecl *D, SourceLocation L);
1770  void AddStmt(Stmt *S);
1771  void AddDecl(Decl *D, bool isFirst = true);
1772  void AddTypeLoc(TypeSourceInfo *TI);
1773  void EnqueueChildren(Stmt *S);
1774};
1775} // end anonyous namespace
1776
1777void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1778  // 'S' should always be non-null, since it comes from the
1779  // statement we are visiting.
1780  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1781}
1782
1783void
1784EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1785  if (Qualifier)
1786    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1787}
1788
1789void EnqueueVisitor::AddStmt(Stmt *S) {
1790  if (S)
1791    WL.push_back(StmtVisit(S, Parent));
1792}
1793void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1794  if (D)
1795    WL.push_back(DeclVisit(D, Parent, isFirst));
1796}
1797void EnqueueVisitor::
1798  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1799  if (A)
1800    WL.push_back(ExplicitTemplateArgsVisit(
1801                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1802}
1803void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1804  if (D)
1805    WL.push_back(MemberRefVisit(D, L, Parent));
1806}
1807void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1808  if (TI)
1809    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1810 }
1811void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1812  unsigned size = WL.size();
1813  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1814    AddStmt(*Child);
1815  }
1816  if (size == WL.size())
1817    return;
1818  // Now reverse the entries we just added.  This will match the DFS
1819  // ordering performed by the worklist.
1820  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1821  std::reverse(I, E);
1822}
1823void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1824  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1825}
1826void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1827  AddDecl(B->getBlockDecl());
1828}
1829void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1830  EnqueueChildren(E);
1831  AddTypeLoc(E->getTypeSourceInfo());
1832}
1833void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1834  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1835        E = S->body_rend(); I != E; ++I) {
1836    AddStmt(*I);
1837  }
1838}
1839void EnqueueVisitor::
1840VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1841  AddStmt(S->getSubStmt());
1842  AddDeclarationNameInfo(S);
1843  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1844    AddNestedNameSpecifierLoc(QualifierLoc);
1845}
1846
1847void EnqueueVisitor::
1848VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1849  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1850  AddDeclarationNameInfo(E);
1851  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1852    AddNestedNameSpecifierLoc(QualifierLoc);
1853  if (!E->isImplicitAccess())
1854    AddStmt(E->getBase());
1855}
1856void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1857  // Enqueue the initializer or constructor arguments.
1858  for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1859    AddStmt(E->getConstructorArg(I-1));
1860  // Enqueue the array size, if any.
1861  AddStmt(E->getArraySize());
1862  // Enqueue the allocated type.
1863  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1864  // Enqueue the placement arguments.
1865  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1866    AddStmt(E->getPlacementArg(I-1));
1867}
1868void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1869  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1870    AddStmt(CE->getArg(I-1));
1871  AddStmt(CE->getCallee());
1872  AddStmt(CE->getArg(0));
1873}
1874void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1875  // Visit the name of the type being destroyed.
1876  AddTypeLoc(E->getDestroyedTypeInfo());
1877  // Visit the scope type that looks disturbingly like the nested-name-specifier
1878  // but isn't.
1879  AddTypeLoc(E->getScopeTypeInfo());
1880  // Visit the nested-name-specifier.
1881  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1882    AddNestedNameSpecifierLoc(QualifierLoc);
1883  // Visit base expression.
1884  AddStmt(E->getBase());
1885}
1886void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1887  AddTypeLoc(E->getTypeSourceInfo());
1888}
1889void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1890  EnqueueChildren(E);
1891  AddTypeLoc(E->getTypeSourceInfo());
1892}
1893void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1894  EnqueueChildren(E);
1895  if (E->isTypeOperand())
1896    AddTypeLoc(E->getTypeOperandSourceInfo());
1897}
1898
1899void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1900                                                     *E) {
1901  EnqueueChildren(E);
1902  AddTypeLoc(E->getTypeSourceInfo());
1903}
1904void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1905  EnqueueChildren(E);
1906  if (E->isTypeOperand())
1907    AddTypeLoc(E->getTypeOperandSourceInfo());
1908}
1909
1910void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1911  EnqueueChildren(S);
1912  AddDecl(S->getExceptionDecl());
1913}
1914
1915void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1916  if (DR->hasExplicitTemplateArgs()) {
1917    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1918  }
1919  WL.push_back(DeclRefExprParts(DR, Parent));
1920}
1921void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1922  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1923  AddDeclarationNameInfo(E);
1924  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1925}
1926void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1927  unsigned size = WL.size();
1928  bool isFirst = true;
1929  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1930       D != DEnd; ++D) {
1931    AddDecl(*D, isFirst);
1932    isFirst = false;
1933  }
1934  if (size == WL.size())
1935    return;
1936  // Now reverse the entries we just added.  This will match the DFS
1937  // ordering performed by the worklist.
1938  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1939  std::reverse(I, E);
1940}
1941void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1942  AddStmt(E->getInit());
1943  typedef DesignatedInitExpr::Designator Designator;
1944  for (DesignatedInitExpr::reverse_designators_iterator
1945         D = E->designators_rbegin(), DEnd = E->designators_rend();
1946         D != DEnd; ++D) {
1947    if (D->isFieldDesignator()) {
1948      if (FieldDecl *Field = D->getField())
1949        AddMemberRef(Field, D->getFieldLoc());
1950      continue;
1951    }
1952    if (D->isArrayDesignator()) {
1953      AddStmt(E->getArrayIndex(*D));
1954      continue;
1955    }
1956    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1957    AddStmt(E->getArrayRangeEnd(*D));
1958    AddStmt(E->getArrayRangeStart(*D));
1959  }
1960}
1961void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1962  EnqueueChildren(E);
1963  AddTypeLoc(E->getTypeInfoAsWritten());
1964}
1965void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1966  AddStmt(FS->getBody());
1967  AddStmt(FS->getInc());
1968  AddStmt(FS->getCond());
1969  AddDecl(FS->getConditionVariable());
1970  AddStmt(FS->getInit());
1971}
1972void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1973  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1974}
1975void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1976  AddStmt(If->getElse());
1977  AddStmt(If->getThen());
1978  AddStmt(If->getCond());
1979  AddDecl(If->getConditionVariable());
1980}
1981void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1982  // We care about the syntactic form of the initializer list, only.
1983  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1984    IE = Syntactic;
1985  EnqueueChildren(IE);
1986}
1987void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1988  WL.push_back(MemberExprParts(M, Parent));
1989
1990  // If the base of the member access expression is an implicit 'this', don't
1991  // visit it.
1992  // FIXME: If we ever want to show these implicit accesses, this will be
1993  // unfortunate. However, clang_getCursor() relies on this behavior.
1994  if (!M->isImplicitAccess())
1995    AddStmt(M->getBase());
1996}
1997void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1998  AddTypeLoc(E->getEncodedTypeSourceInfo());
1999}
2000void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2001  EnqueueChildren(M);
2002  AddTypeLoc(M->getClassReceiverTypeInfo());
2003}
2004void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2005  // Visit the components of the offsetof expression.
2006  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2007    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2008    const OffsetOfNode &Node = E->getComponent(I-1);
2009    switch (Node.getKind()) {
2010    case OffsetOfNode::Array:
2011      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2012      break;
2013    case OffsetOfNode::Field:
2014      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2015      break;
2016    case OffsetOfNode::Identifier:
2017    case OffsetOfNode::Base:
2018      continue;
2019    }
2020  }
2021  // Visit the type into which we're computing the offset.
2022  AddTypeLoc(E->getTypeSourceInfo());
2023}
2024void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2025  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2026  WL.push_back(OverloadExprParts(E, Parent));
2027}
2028void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2029                                              UnaryExprOrTypeTraitExpr *E) {
2030  EnqueueChildren(E);
2031  if (E->isArgumentType())
2032    AddTypeLoc(E->getArgumentTypeInfo());
2033}
2034void EnqueueVisitor::VisitStmt(Stmt *S) {
2035  EnqueueChildren(S);
2036}
2037void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2038  AddStmt(S->getBody());
2039  AddStmt(S->getCond());
2040  AddDecl(S->getConditionVariable());
2041}
2042
2043void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2044  AddStmt(W->getBody());
2045  AddStmt(W->getCond());
2046  AddDecl(W->getConditionVariable());
2047}
2048
2049void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2050  AddTypeLoc(E->getQueriedTypeSourceInfo());
2051}
2052
2053void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2054  AddTypeLoc(E->getRhsTypeSourceInfo());
2055  AddTypeLoc(E->getLhsTypeSourceInfo());
2056}
2057
2058void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2059  AddTypeLoc(E->getQueriedTypeSourceInfo());
2060}
2061
2062void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2063  EnqueueChildren(E);
2064}
2065
2066void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2067  VisitOverloadExpr(U);
2068  if (!U->isImplicitAccess())
2069    AddStmt(U->getBase());
2070}
2071void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2072  AddStmt(E->getSubExpr());
2073  AddTypeLoc(E->getWrittenTypeInfo());
2074}
2075void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2076  WL.push_back(SizeOfPackExprParts(E, Parent));
2077}
2078void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2079  // If the opaque value has a source expression, just transparently
2080  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2081  if (Expr *SourceExpr = E->getSourceExpr())
2082    return Visit(SourceExpr);
2083}
2084void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2085  // Treat the expression like its syntactic form.
2086  Visit(E->getSyntacticForm());
2087}
2088
2089void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2090  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2091}
2092
2093bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2094  if (RegionOfInterest.isValid()) {
2095    SourceRange Range = getRawCursorExtent(C);
2096    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2097      return false;
2098  }
2099  return true;
2100}
2101
2102bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2103  while (!WL.empty()) {
2104    // Dequeue the worklist item.
2105    VisitorJob LI = WL.back();
2106    WL.pop_back();
2107
2108    // Set the Parent field, then back to its old value once we're done.
2109    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2110
2111    switch (LI.getKind()) {
2112      case VisitorJob::DeclVisitKind: {
2113        Decl *D = cast<DeclVisit>(&LI)->get();
2114        if (!D)
2115          continue;
2116
2117        // For now, perform default visitation for Decls.
2118        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2119                               cast<DeclVisit>(&LI)->isFirst())))
2120            return true;
2121
2122        continue;
2123      }
2124      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2125        const ASTTemplateArgumentListInfo *ArgList =
2126          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2127        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2128               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2129               Arg != ArgEnd; ++Arg) {
2130          if (VisitTemplateArgumentLoc(*Arg))
2131            return true;
2132        }
2133        continue;
2134      }
2135      case VisitorJob::TypeLocVisitKind: {
2136        // Perform default visitation for TypeLocs.
2137        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2138          return true;
2139        continue;
2140      }
2141      case VisitorJob::LabelRefVisitKind: {
2142        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2143        if (LabelStmt *stmt = LS->getStmt()) {
2144          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2145                                       TU))) {
2146            return true;
2147          }
2148        }
2149        continue;
2150      }
2151
2152      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2153        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2154        if (VisitNestedNameSpecifierLoc(V->get()))
2155          return true;
2156        continue;
2157      }
2158
2159      case VisitorJob::DeclarationNameInfoVisitKind: {
2160        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2161                                     ->get()))
2162          return true;
2163        continue;
2164      }
2165      case VisitorJob::MemberRefVisitKind: {
2166        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2167        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2168          return true;
2169        continue;
2170      }
2171      case VisitorJob::StmtVisitKind: {
2172        Stmt *S = cast<StmtVisit>(&LI)->get();
2173        if (!S)
2174          continue;
2175
2176        // Update the current cursor.
2177        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2178        if (!IsInRegionOfInterest(Cursor))
2179          continue;
2180        switch (Visitor(Cursor, Parent, ClientData)) {
2181          case CXChildVisit_Break: return true;
2182          case CXChildVisit_Continue: break;
2183          case CXChildVisit_Recurse:
2184            EnqueueWorkList(WL, S);
2185            break;
2186        }
2187        continue;
2188      }
2189      case VisitorJob::MemberExprPartsKind: {
2190        // Handle the other pieces in the MemberExpr besides the base.
2191        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2192
2193        // Visit the nested-name-specifier
2194        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2195          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2196            return true;
2197
2198        // Visit the declaration name.
2199        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2200          return true;
2201
2202        // Visit the explicitly-specified template arguments, if any.
2203        if (M->hasExplicitTemplateArgs()) {
2204          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2205               *ArgEnd = Arg + M->getNumTemplateArgs();
2206               Arg != ArgEnd; ++Arg) {
2207            if (VisitTemplateArgumentLoc(*Arg))
2208              return true;
2209          }
2210        }
2211        continue;
2212      }
2213      case VisitorJob::DeclRefExprPartsKind: {
2214        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2215        // Visit nested-name-specifier, if present.
2216        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2217          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2218            return true;
2219        // Visit declaration name.
2220        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2221          return true;
2222        continue;
2223      }
2224      case VisitorJob::OverloadExprPartsKind: {
2225        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2226        // Visit the nested-name-specifier.
2227        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2228          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2229            return true;
2230        // Visit the declaration name.
2231        if (VisitDeclarationNameInfo(O->getNameInfo()))
2232          return true;
2233        // Visit the overloaded declaration reference.
2234        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2235          return true;
2236        continue;
2237      }
2238      case VisitorJob::SizeOfPackExprPartsKind: {
2239        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2240        NamedDecl *Pack = E->getPack();
2241        if (isa<TemplateTypeParmDecl>(Pack)) {
2242          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2243                                      E->getPackLoc(), TU)))
2244            return true;
2245
2246          continue;
2247        }
2248
2249        if (isa<TemplateTemplateParmDecl>(Pack)) {
2250          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2251                                          E->getPackLoc(), TU)))
2252            return true;
2253
2254          continue;
2255        }
2256
2257        // Non-type template parameter packs and function parameter packs are
2258        // treated like DeclRefExpr cursors.
2259        continue;
2260      }
2261    }
2262  }
2263  return false;
2264}
2265
2266bool CursorVisitor::Visit(Stmt *S) {
2267  VisitorWorkList *WL = 0;
2268  if (!WorkListFreeList.empty()) {
2269    WL = WorkListFreeList.back();
2270    WL->clear();
2271    WorkListFreeList.pop_back();
2272  }
2273  else {
2274    WL = new VisitorWorkList();
2275    WorkListCache.push_back(WL);
2276  }
2277  EnqueueWorkList(*WL, S);
2278  bool result = RunVisitorWorkList(*WL);
2279  WorkListFreeList.push_back(WL);
2280  return result;
2281}
2282
2283namespace {
2284typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2285RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2286                          const DeclarationNameInfo &NI,
2287                          const SourceRange &QLoc,
2288                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2289  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2290  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2291  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2292
2293  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2294
2295  RefNamePieces Pieces;
2296
2297  if (WantQualifier && QLoc.isValid())
2298    Pieces.push_back(QLoc);
2299
2300  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2301    Pieces.push_back(NI.getLoc());
2302
2303  if (WantTemplateArgs && TemplateArgs)
2304    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2305                                 TemplateArgs->RAngleLoc));
2306
2307  if (Kind == DeclarationName::CXXOperatorName) {
2308    Pieces.push_back(SourceLocation::getFromRawEncoding(
2309                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2310    Pieces.push_back(SourceLocation::getFromRawEncoding(
2311                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2312  }
2313
2314  if (WantSinglePiece) {
2315    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2316    Pieces.clear();
2317    Pieces.push_back(R);
2318  }
2319
2320  return Pieces;
2321}
2322}
2323
2324//===----------------------------------------------------------------------===//
2325// Misc. API hooks.
2326//===----------------------------------------------------------------------===//
2327
2328static llvm::sys::Mutex EnableMultithreadingMutex;
2329static bool EnabledMultithreading;
2330
2331static void fatal_error_handler(void *user_data, const std::string& reason) {
2332  // Write the result out to stderr avoiding errs() because raw_ostreams can
2333  // call report_fatal_error.
2334  fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2335  ::abort();
2336}
2337
2338extern "C" {
2339CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2340                          int displayDiagnostics) {
2341  // Disable pretty stack trace functionality, which will otherwise be a very
2342  // poor citizen of the world and set up all sorts of signal handlers.
2343  llvm::DisablePrettyStackTrace = true;
2344
2345  // We use crash recovery to make some of our APIs more reliable, implicitly
2346  // enable it.
2347  llvm::CrashRecoveryContext::Enable();
2348
2349  // Enable support for multithreading in LLVM.
2350  {
2351    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2352    if (!EnabledMultithreading) {
2353      llvm::install_fatal_error_handler(fatal_error_handler, 0);
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}
3402
3403struct GetCursorData {
3404  SourceLocation TokenBeginLoc;
3405  bool PointsAtMacroArgExpansion;
3406  CXCursor &BestCursor;
3407
3408  GetCursorData(SourceManager &SM,
3409                SourceLocation tokenBegin, CXCursor &outputCursor)
3410    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3411    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3412  }
3413};
3414
3415static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3416                                                CXCursor parent,
3417                                                CXClientData client_data) {
3418  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3419  CXCursor *BestCursor = &Data->BestCursor;
3420
3421  // If we point inside a macro argument we should provide info of what the
3422  // token is so use the actual cursor, don't replace it with a macro expansion
3423  // cursor.
3424  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3425    return CXChildVisit_Recurse;
3426
3427  if (clang_isDeclaration(cursor.kind)) {
3428    // Avoid having the implicit methods override the property decls.
3429    if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
3430      if (MD->isImplicit())
3431        return CXChildVisit_Break;
3432  }
3433
3434  if (clang_isExpression(cursor.kind) &&
3435      clang_isDeclaration(BestCursor->kind)) {
3436    if (Decl *D = getCursorDecl(*BestCursor)) {
3437      // Avoid having the cursor of an expression replace the declaration cursor
3438      // when the expression source range overlaps the declaration range.
3439      // This can happen for C++ constructor expressions whose range generally
3440      // include the variable declaration, e.g.:
3441      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3442      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3443          D->getLocation() == Data->TokenBeginLoc)
3444        return CXChildVisit_Break;
3445    }
3446  }
3447
3448  // If our current best cursor is the construction of a temporary object,
3449  // don't replace that cursor with a type reference, because we want
3450  // clang_getCursor() to point at the constructor.
3451  if (clang_isExpression(BestCursor->kind) &&
3452      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3453      cursor.kind == CXCursor_TypeRef) {
3454    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3455    // as having the actual point on the type reference.
3456    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3457    return CXChildVisit_Recurse;
3458  }
3459
3460  *BestCursor = cursor;
3461  return CXChildVisit_Recurse;
3462}
3463
3464CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3465  if (!TU)
3466    return clang_getNullCursor();
3467
3468  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3469  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3470
3471  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3472  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3473
3474  bool Logging = getenv("LIBCLANG_LOGGING");
3475  if (Logging) {
3476    CXFile SearchFile;
3477    unsigned SearchLine, SearchColumn;
3478    CXFile ResultFile;
3479    unsigned ResultLine, ResultColumn;
3480    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3481    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3482    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3483
3484    clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3485    clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3486                               &ResultColumn, 0);
3487    SearchFileName = clang_getFileName(SearchFile);
3488    ResultFileName = clang_getFileName(ResultFile);
3489    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3490    USR = clang_getCursorUSR(Result);
3491    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3492            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3493            clang_getCString(KindSpelling),
3494            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3495            clang_getCString(USR), IsDef);
3496    clang_disposeString(SearchFileName);
3497    clang_disposeString(ResultFileName);
3498    clang_disposeString(KindSpelling);
3499    clang_disposeString(USR);
3500
3501    CXCursor Definition = clang_getCursorDefinition(Result);
3502    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3503      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3504      CXString DefinitionKindSpelling
3505                                = clang_getCursorKindSpelling(Definition.kind);
3506      CXFile DefinitionFile;
3507      unsigned DefinitionLine, DefinitionColumn;
3508      clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3509                                 &DefinitionLine, &DefinitionColumn, 0);
3510      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3511      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3512              clang_getCString(DefinitionKindSpelling),
3513              clang_getCString(DefinitionFileName),
3514              DefinitionLine, DefinitionColumn);
3515      clang_disposeString(DefinitionFileName);
3516      clang_disposeString(DefinitionKindSpelling);
3517    }
3518  }
3519
3520  return Result;
3521}
3522
3523CXCursor clang_getNullCursor(void) {
3524  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3525}
3526
3527unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3528  return X == Y;
3529}
3530
3531unsigned clang_hashCursor(CXCursor C) {
3532  unsigned Index = 0;
3533  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3534    Index = 1;
3535
3536  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3537                                        std::make_pair(C.kind, C.data[Index]));
3538}
3539
3540unsigned clang_isInvalid(enum CXCursorKind K) {
3541  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3542}
3543
3544unsigned clang_isDeclaration(enum CXCursorKind K) {
3545  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3546}
3547
3548unsigned clang_isReference(enum CXCursorKind K) {
3549  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3550}
3551
3552unsigned clang_isExpression(enum CXCursorKind K) {
3553  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3554}
3555
3556unsigned clang_isStatement(enum CXCursorKind K) {
3557  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3558}
3559
3560unsigned clang_isAttribute(enum CXCursorKind K) {
3561    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3562}
3563
3564unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3565  return K == CXCursor_TranslationUnit;
3566}
3567
3568unsigned clang_isPreprocessing(enum CXCursorKind K) {
3569  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3570}
3571
3572unsigned clang_isUnexposed(enum CXCursorKind K) {
3573  switch (K) {
3574    case CXCursor_UnexposedDecl:
3575    case CXCursor_UnexposedExpr:
3576    case CXCursor_UnexposedStmt:
3577    case CXCursor_UnexposedAttr:
3578      return true;
3579    default:
3580      return false;
3581  }
3582}
3583
3584CXCursorKind clang_getCursorKind(CXCursor C) {
3585  return C.kind;
3586}
3587
3588CXSourceLocation clang_getCursorLocation(CXCursor C) {
3589  if (clang_isReference(C.kind)) {
3590    switch (C.kind) {
3591    case CXCursor_ObjCSuperClassRef: {
3592      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3593        = getCursorObjCSuperClassRef(C);
3594      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3595    }
3596
3597    case CXCursor_ObjCProtocolRef: {
3598      std::pair<ObjCProtocolDecl *, SourceLocation> P
3599        = getCursorObjCProtocolRef(C);
3600      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3601    }
3602
3603    case CXCursor_ObjCClassRef: {
3604      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3605        = getCursorObjCClassRef(C);
3606      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3607    }
3608
3609    case CXCursor_TypeRef: {
3610      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3611      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3612    }
3613
3614    case CXCursor_TemplateRef: {
3615      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3616      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3617    }
3618
3619    case CXCursor_NamespaceRef: {
3620      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3621      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3622    }
3623
3624    case CXCursor_MemberRef: {
3625      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3626      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3627    }
3628
3629    case CXCursor_CXXBaseSpecifier: {
3630      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3631      if (!BaseSpec)
3632        return clang_getNullLocation();
3633
3634      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3635        return cxloc::translateSourceLocation(getCursorContext(C),
3636                                            TSInfo->getTypeLoc().getBeginLoc());
3637
3638      return cxloc::translateSourceLocation(getCursorContext(C),
3639                                        BaseSpec->getSourceRange().getBegin());
3640    }
3641
3642    case CXCursor_LabelRef: {
3643      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3644      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3645    }
3646
3647    case CXCursor_OverloadedDeclRef:
3648      return cxloc::translateSourceLocation(getCursorContext(C),
3649                                          getCursorOverloadedDeclRef(C).second);
3650
3651    default:
3652      // FIXME: Need a way to enumerate all non-reference cases.
3653      llvm_unreachable("Missed a reference kind");
3654    }
3655  }
3656
3657  if (clang_isExpression(C.kind))
3658    return cxloc::translateSourceLocation(getCursorContext(C),
3659                                   getLocationFromExpr(getCursorExpr(C)));
3660
3661  if (clang_isStatement(C.kind))
3662    return cxloc::translateSourceLocation(getCursorContext(C),
3663                                          getCursorStmt(C)->getLocStart());
3664
3665  if (C.kind == CXCursor_PreprocessingDirective) {
3666    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3667    return cxloc::translateSourceLocation(getCursorContext(C), L);
3668  }
3669
3670  if (C.kind == CXCursor_MacroExpansion) {
3671    SourceLocation L
3672      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3673    return cxloc::translateSourceLocation(getCursorContext(C), L);
3674  }
3675
3676  if (C.kind == CXCursor_MacroDefinition) {
3677    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3678    return cxloc::translateSourceLocation(getCursorContext(C), L);
3679  }
3680
3681  if (C.kind == CXCursor_InclusionDirective) {
3682    SourceLocation L
3683      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3684    return cxloc::translateSourceLocation(getCursorContext(C), L);
3685  }
3686
3687  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3688    return clang_getNullLocation();
3689
3690  Decl *D = getCursorDecl(C);
3691  if (!D)
3692    return clang_getNullLocation();
3693
3694  SourceLocation Loc = D->getLocation();
3695  // FIXME: Multiple variables declared in a single declaration
3696  // currently lack the information needed to correctly determine their
3697  // ranges when accounting for the type-specifier.  We use context
3698  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3699  // and if so, whether it is the first decl.
3700  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3701    if (!cxcursor::isFirstInDeclGroup(C))
3702      Loc = VD->getLocation();
3703  }
3704
3705  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3706}
3707
3708} // end extern "C"
3709
3710CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3711  assert(TU);
3712
3713  // Guard against an invalid SourceLocation, or we may assert in one
3714  // of the following calls.
3715  if (SLoc.isInvalid())
3716    return clang_getNullCursor();
3717
3718  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3719
3720  // Translate the given source location to make it point at the beginning of
3721  // the token under the cursor.
3722  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3723                                    CXXUnit->getASTContext().getLangOptions());
3724
3725  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3726  if (SLoc.isValid()) {
3727    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3728    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3729                            /*VisitPreprocessorLast=*/true,
3730                            /*VisitIncludedEntities=*/false,
3731                            SourceLocation(SLoc));
3732    CursorVis.visitFileRegion();
3733  }
3734
3735  return Result;
3736}
3737
3738static SourceRange getRawCursorExtent(CXCursor C) {
3739  if (clang_isReference(C.kind)) {
3740    switch (C.kind) {
3741    case CXCursor_ObjCSuperClassRef:
3742      return  getCursorObjCSuperClassRef(C).second;
3743
3744    case CXCursor_ObjCProtocolRef:
3745      return getCursorObjCProtocolRef(C).second;
3746
3747    case CXCursor_ObjCClassRef:
3748      return getCursorObjCClassRef(C).second;
3749
3750    case CXCursor_TypeRef:
3751      return getCursorTypeRef(C).second;
3752
3753    case CXCursor_TemplateRef:
3754      return getCursorTemplateRef(C).second;
3755
3756    case CXCursor_NamespaceRef:
3757      return getCursorNamespaceRef(C).second;
3758
3759    case CXCursor_MemberRef:
3760      return getCursorMemberRef(C).second;
3761
3762    case CXCursor_CXXBaseSpecifier:
3763      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3764
3765    case CXCursor_LabelRef:
3766      return getCursorLabelRef(C).second;
3767
3768    case CXCursor_OverloadedDeclRef:
3769      return getCursorOverloadedDeclRef(C).second;
3770
3771    default:
3772      // FIXME: Need a way to enumerate all non-reference cases.
3773      llvm_unreachable("Missed a reference kind");
3774    }
3775  }
3776
3777  if (clang_isExpression(C.kind))
3778    return getCursorExpr(C)->getSourceRange();
3779
3780  if (clang_isStatement(C.kind))
3781    return getCursorStmt(C)->getSourceRange();
3782
3783  if (clang_isAttribute(C.kind))
3784    return getCursorAttr(C)->getRange();
3785
3786  if (C.kind == CXCursor_PreprocessingDirective)
3787    return cxcursor::getCursorPreprocessingDirective(C);
3788
3789  if (C.kind == CXCursor_MacroExpansion) {
3790    ASTUnit *TU = getCursorASTUnit(C);
3791    SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3792    return TU->mapRangeFromPreamble(Range);
3793  }
3794
3795  if (C.kind == CXCursor_MacroDefinition) {
3796    ASTUnit *TU = getCursorASTUnit(C);
3797    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3798    return TU->mapRangeFromPreamble(Range);
3799  }
3800
3801  if (C.kind == CXCursor_InclusionDirective) {
3802    ASTUnit *TU = getCursorASTUnit(C);
3803    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3804    return TU->mapRangeFromPreamble(Range);
3805  }
3806
3807  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3808    Decl *D = cxcursor::getCursorDecl(C);
3809    if (!D)
3810      return SourceRange();
3811
3812    SourceRange R = D->getSourceRange();
3813    // FIXME: Multiple variables declared in a single declaration
3814    // currently lack the information needed to correctly determine their
3815    // ranges when accounting for the type-specifier.  We use context
3816    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3817    // and if so, whether it is the first decl.
3818    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3819      if (!cxcursor::isFirstInDeclGroup(C))
3820        R.setBegin(VD->getLocation());
3821    }
3822    return R;
3823  }
3824  return SourceRange();
3825}
3826
3827/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3828/// the decl-specifier-seq for declarations.
3829static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3830  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3831    Decl *D = cxcursor::getCursorDecl(C);
3832    if (!D)
3833      return SourceRange();
3834
3835    SourceRange R = D->getSourceRange();
3836
3837    // Adjust the start of the location for declarations preceded by
3838    // declaration specifiers.
3839    SourceLocation StartLoc;
3840    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3841      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3842        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3843    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3844      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3845        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3846    }
3847
3848    if (StartLoc.isValid() && R.getBegin().isValid() &&
3849        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3850      R.setBegin(StartLoc);
3851
3852    // FIXME: Multiple variables declared in a single declaration
3853    // currently lack the information needed to correctly determine their
3854    // ranges when accounting for the type-specifier.  We use context
3855    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3856    // and if so, whether it is the first decl.
3857    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3858      if (!cxcursor::isFirstInDeclGroup(C))
3859        R.setBegin(VD->getLocation());
3860    }
3861
3862    return R;
3863  }
3864
3865  return getRawCursorExtent(C);
3866}
3867
3868extern "C" {
3869
3870CXSourceRange clang_getCursorExtent(CXCursor C) {
3871  SourceRange R = getRawCursorExtent(C);
3872  if (R.isInvalid())
3873    return clang_getNullRange();
3874
3875  return cxloc::translateSourceRange(getCursorContext(C), R);
3876}
3877
3878CXCursor clang_getCursorReferenced(CXCursor C) {
3879  if (clang_isInvalid(C.kind))
3880    return clang_getNullCursor();
3881
3882  CXTranslationUnit tu = getCursorTU(C);
3883  if (clang_isDeclaration(C.kind)) {
3884    Decl *D = getCursorDecl(C);
3885    if (!D)
3886      return clang_getNullCursor();
3887    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3888      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
3889    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3890      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3891        return MakeCXCursor(Property, tu);
3892
3893    return C;
3894  }
3895
3896  if (clang_isExpression(C.kind)) {
3897    Expr *E = getCursorExpr(C);
3898    Decl *D = getDeclFromExpr(E);
3899    if (D) {
3900      CXCursor declCursor = MakeCXCursor(D, tu);
3901      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3902                                               declCursor);
3903      return declCursor;
3904    }
3905
3906    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3907      return MakeCursorOverloadedDeclRef(Ovl, tu);
3908
3909    return clang_getNullCursor();
3910  }
3911
3912  if (clang_isStatement(C.kind)) {
3913    Stmt *S = getCursorStmt(C);
3914    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3915      if (LabelDecl *label = Goto->getLabel())
3916        if (LabelStmt *labelS = label->getStmt())
3917        return MakeCXCursor(labelS, getCursorDecl(C), tu);
3918
3919    return clang_getNullCursor();
3920  }
3921
3922  if (C.kind == CXCursor_MacroExpansion) {
3923    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
3924      return MakeMacroDefinitionCursor(Def, tu);
3925  }
3926
3927  if (!clang_isReference(C.kind))
3928    return clang_getNullCursor();
3929
3930  switch (C.kind) {
3931    case CXCursor_ObjCSuperClassRef:
3932      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
3933
3934    case CXCursor_ObjCProtocolRef: {
3935      ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
3936      if (ObjCProtocolDecl *Def = Prot->getDefinition())
3937        return MakeCXCursor(Def, tu);
3938
3939      return MakeCXCursor(Prot, tu);
3940    }
3941
3942    case CXCursor_ObjCClassRef: {
3943      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3944      if (ObjCInterfaceDecl *Def = Class->getDefinition())
3945        return MakeCXCursor(Def, tu);
3946
3947      return MakeCXCursor(Class, tu);
3948    }
3949
3950    case CXCursor_TypeRef:
3951      return MakeCXCursor(getCursorTypeRef(C).first, tu );
3952
3953    case CXCursor_TemplateRef:
3954      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
3955
3956    case CXCursor_NamespaceRef:
3957      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
3958
3959    case CXCursor_MemberRef:
3960      return MakeCXCursor(getCursorMemberRef(C).first, tu );
3961
3962    case CXCursor_CXXBaseSpecifier: {
3963      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3964      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3965                                                         tu ));
3966    }
3967
3968    case CXCursor_LabelRef:
3969      // FIXME: We end up faking the "parent" declaration here because we
3970      // don't want to make CXCursor larger.
3971      return MakeCXCursor(getCursorLabelRef(C).first,
3972               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3973                          .getTranslationUnitDecl(),
3974                          tu);
3975
3976    case CXCursor_OverloadedDeclRef:
3977      return C;
3978
3979    default:
3980      // We would prefer to enumerate all non-reference cursor kinds here.
3981      llvm_unreachable("Unhandled reference cursor kind");
3982  }
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 (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4132      return MakeCXCursor(Def, TU);
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    ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4142    if (WasReference) {
4143      if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4144        return MakeCXCursor(Def, TU);
4145    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4146      return MakeCXCursor(Impl, TU);
4147    return clang_getNullCursor();
4148  }
4149
4150  case Decl::ObjCProperty:
4151    // FIXME: We don't really know where to find the
4152    // ObjCPropertyImplDecls that implement this property.
4153    return clang_getNullCursor();
4154
4155  case Decl::ObjCCompatibleAlias:
4156    if (ObjCInterfaceDecl *Class
4157          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4158      if (ObjCInterfaceDecl *Def = Class->getDefinition())
4159        return MakeCXCursor(Def, TU);
4160
4161    return clang_getNullCursor();
4162
4163  case Decl::Friend:
4164    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4165      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4166    return clang_getNullCursor();
4167
4168  case Decl::FriendTemplate:
4169    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4170      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4171    return clang_getNullCursor();
4172  }
4173
4174  return clang_getNullCursor();
4175}
4176
4177unsigned clang_isCursorDefinition(CXCursor C) {
4178  if (!clang_isDeclaration(C.kind))
4179    return 0;
4180
4181  return clang_getCursorDefinition(C) == C;
4182}
4183
4184CXCursor clang_getCanonicalCursor(CXCursor C) {
4185  if (!clang_isDeclaration(C.kind))
4186    return C;
4187
4188  if (Decl *D = getCursorDecl(C)) {
4189    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4190      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4191        return MakeCXCursor(CatD, getCursorTU(C));
4192
4193    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4194      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4195        return MakeCXCursor(IFD, getCursorTU(C));
4196
4197    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4198  }
4199
4200  return C;
4201}
4202
4203unsigned clang_getNumOverloadedDecls(CXCursor C) {
4204  if (C.kind != CXCursor_OverloadedDeclRef)
4205    return 0;
4206
4207  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4208  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4209    return E->getNumDecls();
4210
4211  if (OverloadedTemplateStorage *S
4212                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4213    return S->size();
4214
4215  Decl *D = Storage.get<Decl*>();
4216  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4217    return Using->shadow_size();
4218
4219  return 0;
4220}
4221
4222CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4223  if (cursor.kind != CXCursor_OverloadedDeclRef)
4224    return clang_getNullCursor();
4225
4226  if (index >= clang_getNumOverloadedDecls(cursor))
4227    return clang_getNullCursor();
4228
4229  CXTranslationUnit TU = getCursorTU(cursor);
4230  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4231  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4232    return MakeCXCursor(E->decls_begin()[index], TU);
4233
4234  if (OverloadedTemplateStorage *S
4235                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4236    return MakeCXCursor(S->begin()[index], TU);
4237
4238  Decl *D = Storage.get<Decl*>();
4239  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4240    // FIXME: This is, unfortunately, linear time.
4241    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4242    std::advance(Pos, index);
4243    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4244  }
4245
4246  return clang_getNullCursor();
4247}
4248
4249void clang_getDefinitionSpellingAndExtent(CXCursor C,
4250                                          const char **startBuf,
4251                                          const char **endBuf,
4252                                          unsigned *startLine,
4253                                          unsigned *startColumn,
4254                                          unsigned *endLine,
4255                                          unsigned *endColumn) {
4256  assert(getCursorDecl(C) && "CXCursor has null decl");
4257  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4258  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4259  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4260
4261  SourceManager &SM = FD->getASTContext().getSourceManager();
4262  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4263  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4264  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4265  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4266  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4267  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4268}
4269
4270
4271CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4272                                                unsigned PieceIndex) {
4273  RefNamePieces Pieces;
4274
4275  switch (C.kind) {
4276  case CXCursor_MemberRefExpr:
4277    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4278      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4279                           E->getQualifierLoc().getSourceRange());
4280    break;
4281
4282  case CXCursor_DeclRefExpr:
4283    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4284      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4285                           E->getQualifierLoc().getSourceRange(),
4286                           E->getOptionalExplicitTemplateArgs());
4287    break;
4288
4289  case CXCursor_CallExpr:
4290    if (CXXOperatorCallExpr *OCE =
4291        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4292      Expr *Callee = OCE->getCallee();
4293      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4294        Callee = ICE->getSubExpr();
4295
4296      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4297        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4298                             DRE->getQualifierLoc().getSourceRange());
4299    }
4300    break;
4301
4302  default:
4303    break;
4304  }
4305
4306  if (Pieces.empty()) {
4307    if (PieceIndex == 0)
4308      return clang_getCursorExtent(C);
4309  } else if (PieceIndex < Pieces.size()) {
4310      SourceRange R = Pieces[PieceIndex];
4311      if (R.isValid())
4312        return cxloc::translateSourceRange(getCursorContext(C), R);
4313  }
4314
4315  return clang_getNullRange();
4316}
4317
4318void clang_enableStackTraces(void) {
4319  llvm::sys::PrintStackTraceOnErrorSignal();
4320}
4321
4322void clang_executeOnThread(void (*fn)(void*), void *user_data,
4323                           unsigned stack_size) {
4324  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4325}
4326
4327} // end: extern "C"
4328
4329//===----------------------------------------------------------------------===//
4330// Token-based Operations.
4331//===----------------------------------------------------------------------===//
4332
4333/* CXToken layout:
4334 *   int_data[0]: a CXTokenKind
4335 *   int_data[1]: starting token location
4336 *   int_data[2]: token length
4337 *   int_data[3]: reserved
4338 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4339 *   otherwise unused.
4340 */
4341extern "C" {
4342
4343CXTokenKind clang_getTokenKind(CXToken CXTok) {
4344  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4345}
4346
4347CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4348  switch (clang_getTokenKind(CXTok)) {
4349  case CXToken_Identifier:
4350  case CXToken_Keyword:
4351    // We know we have an IdentifierInfo*, so use that.
4352    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4353                            ->getNameStart());
4354
4355  case CXToken_Literal: {
4356    // We have stashed the starting pointer in the ptr_data field. Use it.
4357    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4358    return createCXString(StringRef(Text, CXTok.int_data[2]));
4359  }
4360
4361  case CXToken_Punctuation:
4362  case CXToken_Comment:
4363    break;
4364  }
4365
4366  // We have to find the starting buffer pointer the hard way, by
4367  // deconstructing the source location.
4368  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4369  if (!CXXUnit)
4370    return createCXString("");
4371
4372  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4373  std::pair<FileID, unsigned> LocInfo
4374    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4375  bool Invalid = false;
4376  StringRef Buffer
4377    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4378  if (Invalid)
4379    return createCXString("");
4380
4381  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4382}
4383
4384CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4385  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4386  if (!CXXUnit)
4387    return clang_getNullLocation();
4388
4389  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4390                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4391}
4392
4393CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4394  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4395  if (!CXXUnit)
4396    return clang_getNullRange();
4397
4398  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4399                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4400}
4401
4402static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4403                      SmallVectorImpl<CXToken> &CXTokens) {
4404  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4405  std::pair<FileID, unsigned> BeginLocInfo
4406    = SourceMgr.getDecomposedLoc(Range.getBegin());
4407  std::pair<FileID, unsigned> EndLocInfo
4408    = SourceMgr.getDecomposedLoc(Range.getEnd());
4409
4410  // Cannot tokenize across files.
4411  if (BeginLocInfo.first != EndLocInfo.first)
4412    return;
4413
4414  // Create a lexer
4415  bool Invalid = false;
4416  StringRef Buffer
4417    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4418  if (Invalid)
4419    return;
4420
4421  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4422            CXXUnit->getASTContext().getLangOptions(),
4423            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4424  Lex.SetCommentRetentionState(true);
4425
4426  // Lex tokens until we hit the end of the range.
4427  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4428  Token Tok;
4429  bool previousWasAt = false;
4430  do {
4431    // Lex the next token
4432    Lex.LexFromRawLexer(Tok);
4433    if (Tok.is(tok::eof))
4434      break;
4435
4436    // Initialize the CXToken.
4437    CXToken CXTok;
4438
4439    //   - Common fields
4440    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4441    CXTok.int_data[2] = Tok.getLength();
4442    CXTok.int_data[3] = 0;
4443
4444    //   - Kind-specific fields
4445    if (Tok.isLiteral()) {
4446      CXTok.int_data[0] = CXToken_Literal;
4447      CXTok.ptr_data = (void *)Tok.getLiteralData();
4448    } else if (Tok.is(tok::raw_identifier)) {
4449      // Lookup the identifier to determine whether we have a keyword.
4450      IdentifierInfo *II
4451        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4452
4453      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4454        CXTok.int_data[0] = CXToken_Keyword;
4455      }
4456      else {
4457        CXTok.int_data[0] = Tok.is(tok::identifier)
4458          ? CXToken_Identifier
4459          : CXToken_Keyword;
4460      }
4461      CXTok.ptr_data = II;
4462    } else if (Tok.is(tok::comment)) {
4463      CXTok.int_data[0] = CXToken_Comment;
4464      CXTok.ptr_data = 0;
4465    } else {
4466      CXTok.int_data[0] = CXToken_Punctuation;
4467      CXTok.ptr_data = 0;
4468    }
4469    CXTokens.push_back(CXTok);
4470    previousWasAt = Tok.is(tok::at);
4471  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4472}
4473
4474void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4475                    CXToken **Tokens, unsigned *NumTokens) {
4476  if (Tokens)
4477    *Tokens = 0;
4478  if (NumTokens)
4479    *NumTokens = 0;
4480
4481  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4482  if (!CXXUnit || !Tokens || !NumTokens)
4483    return;
4484
4485  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4486
4487  SourceRange R = cxloc::translateCXSourceRange(Range);
4488  if (R.isInvalid())
4489    return;
4490
4491  SmallVector<CXToken, 32> CXTokens;
4492  getTokens(CXXUnit, R, CXTokens);
4493
4494  if (CXTokens.empty())
4495    return;
4496
4497  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4498  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4499  *NumTokens = CXTokens.size();
4500}
4501
4502void clang_disposeTokens(CXTranslationUnit TU,
4503                         CXToken *Tokens, unsigned NumTokens) {
4504  free(Tokens);
4505}
4506
4507} // end: extern "C"
4508
4509//===----------------------------------------------------------------------===//
4510// Token annotation APIs.
4511//===----------------------------------------------------------------------===//
4512
4513typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4514static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4515                                                     CXCursor parent,
4516                                                     CXClientData client_data);
4517namespace {
4518class AnnotateTokensWorker {
4519  AnnotateTokensData &Annotated;
4520  CXToken *Tokens;
4521  CXCursor *Cursors;
4522  unsigned NumTokens;
4523  unsigned TokIdx;
4524  unsigned PreprocessingTokIdx;
4525  CursorVisitor AnnotateVis;
4526  SourceManager &SrcMgr;
4527  bool HasContextSensitiveKeywords;
4528
4529  bool MoreTokens() const { return TokIdx < NumTokens; }
4530  unsigned NextToken() const { return TokIdx; }
4531  void AdvanceToken() { ++TokIdx; }
4532  SourceLocation GetTokenLoc(unsigned tokI) {
4533    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4534  }
4535  bool isFunctionMacroToken(unsigned tokI) const {
4536    return Tokens[tokI].int_data[3] != 0;
4537  }
4538  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4539    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4540  }
4541
4542  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4543  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4544                                             SourceRange);
4545
4546public:
4547  AnnotateTokensWorker(AnnotateTokensData &annotated,
4548                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4549                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4550    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4551      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4552      AnnotateVis(tu,
4553                  AnnotateTokensVisitor, this,
4554                  /*VisitPreprocessorLast=*/true,
4555                  /*VisitIncludedEntities=*/false,
4556                  RegionOfInterest),
4557      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4558      HasContextSensitiveKeywords(false) { }
4559
4560  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4561  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4562  void AnnotateTokens();
4563
4564  /// \brief Determine whether the annotator saw any cursors that have
4565  /// context-sensitive keywords.
4566  bool hasContextSensitiveKeywords() const {
4567    return HasContextSensitiveKeywords;
4568  }
4569};
4570}
4571
4572void AnnotateTokensWorker::AnnotateTokens() {
4573  // Walk the AST within the region of interest, annotating tokens
4574  // along the way.
4575  AnnotateVis.visitFileRegion();
4576
4577  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4578    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4579    if (Pos != Annotated.end() &&
4580        (clang_isInvalid(Cursors[I].kind) ||
4581         Pos->second.kind != CXCursor_PreprocessingDirective))
4582      Cursors[I] = Pos->second;
4583  }
4584
4585  // Finish up annotating any tokens left.
4586  if (!MoreTokens())
4587    return;
4588
4589  const CXCursor &C = clang_getNullCursor();
4590  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4591    if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4592      continue;
4593
4594    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4595    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4596  }
4597}
4598
4599/// \brief It annotates and advances tokens with a cursor until the comparison
4600//// between the cursor location and the source range is the same as
4601/// \arg compResult.
4602///
4603/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4604/// Pass RangeOverlap to annotate tokens inside a range.
4605void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4606                                               RangeComparisonResult compResult,
4607                                               SourceRange range) {
4608  while (MoreTokens()) {
4609    const unsigned I = NextToken();
4610    if (isFunctionMacroToken(I))
4611      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4612
4613    SourceLocation TokLoc = GetTokenLoc(I);
4614    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4615      Cursors[I] = updateC;
4616      AdvanceToken();
4617      continue;
4618    }
4619    break;
4620  }
4621}
4622
4623/// \brief Special annotation handling for macro argument tokens.
4624void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4625                                               CXCursor updateC,
4626                                               RangeComparisonResult compResult,
4627                                               SourceRange range) {
4628  assert(MoreTokens());
4629  assert(isFunctionMacroToken(NextToken()) &&
4630         "Should be called only for macro arg tokens");
4631
4632  // This works differently than annotateAndAdvanceTokens; because expanded
4633  // macro arguments can have arbitrary translation-unit source order, we do not
4634  // advance the token index one by one until a token fails the range test.
4635  // We only advance once past all of the macro arg tokens if all of them
4636  // pass the range test. If one of them fails we keep the token index pointing
4637  // at the start of the macro arg tokens so that the failing token will be
4638  // annotated by a subsequent annotation try.
4639
4640  bool atLeastOneCompFail = false;
4641
4642  unsigned I = NextToken();
4643  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4644    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4645    if (TokLoc.isFileID())
4646      continue; // not macro arg token, it's parens or comma.
4647    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4648      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4649        Cursors[I] = updateC;
4650    } else
4651      atLeastOneCompFail = true;
4652  }
4653
4654  if (!atLeastOneCompFail)
4655    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4656}
4657
4658enum CXChildVisitResult
4659AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4660  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4661  SourceRange cursorRange = getRawCursorExtent(cursor);
4662  if (cursorRange.isInvalid())
4663    return CXChildVisit_Recurse;
4664
4665  if (!HasContextSensitiveKeywords) {
4666    // Objective-C properties can have context-sensitive keywords.
4667    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4668      if (ObjCPropertyDecl *Property
4669                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4670        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4671    }
4672    // Objective-C methods can have context-sensitive keywords.
4673    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4674             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4675      if (ObjCMethodDecl *Method
4676            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4677        if (Method->getObjCDeclQualifier())
4678          HasContextSensitiveKeywords = true;
4679        else {
4680          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4681                                           PEnd = Method->param_end();
4682               P != PEnd; ++P) {
4683            if ((*P)->getObjCDeclQualifier()) {
4684              HasContextSensitiveKeywords = true;
4685              break;
4686            }
4687          }
4688        }
4689      }
4690    }
4691    // C++ methods can have context-sensitive keywords.
4692    else if (cursor.kind == CXCursor_CXXMethod) {
4693      if (CXXMethodDecl *Method
4694                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4695        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4696          HasContextSensitiveKeywords = true;
4697      }
4698    }
4699    // C++ classes can have context-sensitive keywords.
4700    else if (cursor.kind == CXCursor_StructDecl ||
4701             cursor.kind == CXCursor_ClassDecl ||
4702             cursor.kind == CXCursor_ClassTemplate ||
4703             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4704      if (Decl *D = getCursorDecl(cursor))
4705        if (D->hasAttr<FinalAttr>())
4706          HasContextSensitiveKeywords = true;
4707    }
4708  }
4709
4710  if (clang_isPreprocessing(cursor.kind)) {
4711    // For macro expansions, just note where the beginning of the macro
4712    // expansion occurs.
4713    if (cursor.kind == CXCursor_MacroExpansion) {
4714      Annotated[Loc.int_data] = cursor;
4715      return CXChildVisit_Recurse;
4716    }
4717
4718    // Items in the preprocessing record are kept separate from items in
4719    // declarations, so we keep a separate token index.
4720    unsigned SavedTokIdx = TokIdx;
4721    TokIdx = PreprocessingTokIdx;
4722
4723    // Skip tokens up until we catch up to the beginning of the preprocessing
4724    // entry.
4725    while (MoreTokens()) {
4726      const unsigned I = NextToken();
4727      SourceLocation TokLoc = GetTokenLoc(I);
4728      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4729      case RangeBefore:
4730        AdvanceToken();
4731        continue;
4732      case RangeAfter:
4733      case RangeOverlap:
4734        break;
4735      }
4736      break;
4737    }
4738
4739    // Look at all of the tokens within this range.
4740    while (MoreTokens()) {
4741      const unsigned I = NextToken();
4742      SourceLocation TokLoc = GetTokenLoc(I);
4743      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4744      case RangeBefore:
4745        llvm_unreachable("Infeasible");
4746      case RangeAfter:
4747        break;
4748      case RangeOverlap:
4749        Cursors[I] = cursor;
4750        AdvanceToken();
4751        continue;
4752      }
4753      break;
4754    }
4755
4756    // Save the preprocessing token index; restore the non-preprocessing
4757    // token index.
4758    PreprocessingTokIdx = TokIdx;
4759    TokIdx = SavedTokIdx;
4760    return CXChildVisit_Recurse;
4761  }
4762
4763  if (cursorRange.isInvalid())
4764    return CXChildVisit_Continue;
4765
4766  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4767
4768  // Adjust the annotated range based specific declarations.
4769  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4770  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4771    Decl *D = cxcursor::getCursorDecl(cursor);
4772
4773    SourceLocation StartLoc;
4774    if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
4775      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4776        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4777    } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
4778      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4779        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4780    }
4781
4782    if (StartLoc.isValid() && L.isValid() &&
4783        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4784      cursorRange.setBegin(StartLoc);
4785  }
4786
4787  // If the location of the cursor occurs within a macro instantiation, record
4788  // the spelling location of the cursor in our annotation map.  We can then
4789  // paper over the token labelings during a post-processing step to try and
4790  // get cursor mappings for tokens that are the *arguments* of a macro
4791  // instantiation.
4792  if (L.isMacroID()) {
4793    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4794    // Only invalidate the old annotation if it isn't part of a preprocessing
4795    // directive.  Here we assume that the default construction of CXCursor
4796    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4797    // this isn't the case, we can fix by doing lookup + insertion.
4798
4799    CXCursor &oldC = Annotated[rawEncoding];
4800    if (!clang_isPreprocessing(oldC.kind))
4801      oldC = cursor;
4802  }
4803
4804  const enum CXCursorKind K = clang_getCursorKind(parent);
4805  const CXCursor updateC =
4806    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4807     ? clang_getNullCursor() : parent;
4808
4809  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
4810
4811  // Avoid having the cursor of an expression "overwrite" the annotation of the
4812  // variable declaration that it belongs to.
4813  // This can happen for C++ constructor expressions whose range generally
4814  // include the variable declaration, e.g.:
4815  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4816  if (clang_isExpression(cursorK)) {
4817    Expr *E = getCursorExpr(cursor);
4818    if (Decl *D = getCursorParentDecl(cursor)) {
4819      const unsigned I = NextToken();
4820      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4821          E->getLocStart() == D->getLocation() &&
4822          E->getLocStart() == GetTokenLoc(I)) {
4823        Cursors[I] = updateC;
4824        AdvanceToken();
4825      }
4826    }
4827  }
4828
4829  // Visit children to get their cursor information.
4830  const unsigned BeforeChildren = NextToken();
4831  VisitChildren(cursor);
4832  const unsigned AfterChildren = NextToken();
4833
4834  // Scan the tokens that are at the end of the cursor, but are not captured
4835  // but the child cursors.
4836  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
4837
4838  // Scan the tokens that are at the beginning of the cursor, but are not
4839  // capture by the child cursors.
4840  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4841    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4842      break;
4843
4844    Cursors[I] = cursor;
4845  }
4846
4847  return CXChildVisit_Continue;
4848}
4849
4850static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4851                                                     CXCursor parent,
4852                                                     CXClientData client_data) {
4853  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4854}
4855
4856namespace {
4857
4858/// \brief Uses the macro expansions in the preprocessing record to find
4859/// and mark tokens that are macro arguments. This info is used by the
4860/// AnnotateTokensWorker.
4861class MarkMacroArgTokensVisitor {
4862  SourceManager &SM;
4863  CXToken *Tokens;
4864  unsigned NumTokens;
4865  unsigned CurIdx;
4866
4867public:
4868  MarkMacroArgTokensVisitor(SourceManager &SM,
4869                            CXToken *tokens, unsigned numTokens)
4870    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4871
4872  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4873    if (cursor.kind != CXCursor_MacroExpansion)
4874      return CXChildVisit_Continue;
4875
4876    SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4877    if (macroRange.getBegin() == macroRange.getEnd())
4878      return CXChildVisit_Continue; // it's not a function macro.
4879
4880    for (; CurIdx < NumTokens; ++CurIdx) {
4881      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4882                                        macroRange.getBegin()))
4883        break;
4884    }
4885
4886    if (CurIdx == NumTokens)
4887      return CXChildVisit_Break;
4888
4889    for (; CurIdx < NumTokens; ++CurIdx) {
4890      SourceLocation tokLoc = getTokenLoc(CurIdx);
4891      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4892        break;
4893
4894      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
4895    }
4896
4897    if (CurIdx == NumTokens)
4898      return CXChildVisit_Break;
4899
4900    return CXChildVisit_Continue;
4901  }
4902
4903private:
4904  SourceLocation getTokenLoc(unsigned tokI) {
4905    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4906  }
4907
4908  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
4909    // The third field is reserved and currently not used. Use it here
4910    // to mark macro arg expanded tokens with their expanded locations.
4911    Tokens[tokI].int_data[3] = loc.getRawEncoding();
4912  }
4913};
4914
4915} // end anonymous namespace
4916
4917static CXChildVisitResult
4918MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4919                                  CXClientData client_data) {
4920  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4921                                                                     parent);
4922}
4923
4924namespace {
4925  struct clang_annotateTokens_Data {
4926    CXTranslationUnit TU;
4927    ASTUnit *CXXUnit;
4928    CXToken *Tokens;
4929    unsigned NumTokens;
4930    CXCursor *Cursors;
4931  };
4932}
4933
4934static void annotatePreprocessorTokens(CXTranslationUnit TU,
4935                                       SourceRange RegionOfInterest,
4936                                       AnnotateTokensData &Annotated) {
4937  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4938
4939  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4940  std::pair<FileID, unsigned> BeginLocInfo
4941    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4942  std::pair<FileID, unsigned> EndLocInfo
4943    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4944
4945  if (BeginLocInfo.first != EndLocInfo.first)
4946    return;
4947
4948  StringRef Buffer;
4949  bool Invalid = false;
4950  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4951  if (Buffer.empty() || Invalid)
4952    return;
4953
4954  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4955            CXXUnit->getASTContext().getLangOptions(),
4956            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4957            Buffer.end());
4958  Lex.SetCommentRetentionState(true);
4959
4960  // Lex tokens in raw mode until we hit the end of the range, to avoid
4961  // entering #includes or expanding macros.
4962  while (true) {
4963    Token Tok;
4964    Lex.LexFromRawLexer(Tok);
4965
4966  reprocess:
4967    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4968      // We have found a preprocessing directive. Gobble it up so that we
4969      // don't see it while preprocessing these tokens later, but keep track
4970      // of all of the token locations inside this preprocessing directive so
4971      // that we can annotate them appropriately.
4972      //
4973      // FIXME: Some simple tests here could identify macro definitions and
4974      // #undefs, to provide specific cursor kinds for those.
4975      SmallVector<SourceLocation, 32> Locations;
4976      do {
4977        Locations.push_back(Tok.getLocation());
4978        Lex.LexFromRawLexer(Tok);
4979      } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4980
4981      using namespace cxcursor;
4982      CXCursor Cursor
4983      = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4984                                                     Locations.back()),
4985                                         TU);
4986      for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4987        Annotated[Locations[I].getRawEncoding()] = Cursor;
4988      }
4989
4990      if (Tok.isAtStartOfLine())
4991        goto reprocess;
4992
4993      continue;
4994    }
4995
4996    if (Tok.is(tok::eof))
4997      break;
4998  }
4999}
5000
5001// This gets run a separate thread to avoid stack blowout.
5002static void clang_annotateTokensImpl(void *UserData) {
5003  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5004  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5005  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5006  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5007  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5008
5009  // Determine the region of interest, which contains all of the tokens.
5010  SourceRange RegionOfInterest;
5011  RegionOfInterest.setBegin(
5012    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5013  RegionOfInterest.setEnd(
5014    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5015                                                         Tokens[NumTokens-1])));
5016
5017  // A mapping from the source locations found when re-lexing or traversing the
5018  // region of interest to the corresponding cursors.
5019  AnnotateTokensData Annotated;
5020
5021  // Relex the tokens within the source range to look for preprocessing
5022  // directives.
5023  annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5024
5025  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5026    // Search and mark tokens that are macro argument expansions.
5027    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5028                                      Tokens, NumTokens);
5029    CursorVisitor MacroArgMarker(TU,
5030                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5031                                 /*VisitPreprocessorLast=*/true,
5032                                 /*VisitIncludedEntities=*/false,
5033                                 RegionOfInterest);
5034    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5035  }
5036
5037  // Annotate all of the source locations in the region of interest that map to
5038  // a specific cursor.
5039  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5040                         TU, RegionOfInterest);
5041
5042  // FIXME: We use a ridiculous stack size here because the data-recursion
5043  // algorithm uses a large stack frame than the non-data recursive version,
5044  // and AnnotationTokensWorker currently transforms the data-recursion
5045  // algorithm back into a traditional recursion by explicitly calling
5046  // VisitChildren().  We will need to remove this explicit recursive call.
5047  W.AnnotateTokens();
5048
5049  // If we ran into any entities that involve context-sensitive keywords,
5050  // take another pass through the tokens to mark them as such.
5051  if (W.hasContextSensitiveKeywords()) {
5052    for (unsigned I = 0; I != NumTokens; ++I) {
5053      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5054        continue;
5055
5056      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5057        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5058        if (ObjCPropertyDecl *Property
5059            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5060          if (Property->getPropertyAttributesAsWritten() != 0 &&
5061              llvm::StringSwitch<bool>(II->getName())
5062              .Case("readonly", true)
5063              .Case("assign", true)
5064              .Case("unsafe_unretained", true)
5065              .Case("readwrite", true)
5066              .Case("retain", true)
5067              .Case("copy", true)
5068              .Case("nonatomic", true)
5069              .Case("atomic", true)
5070              .Case("getter", true)
5071              .Case("setter", true)
5072              .Case("strong", true)
5073              .Case("weak", true)
5074              .Default(false))
5075            Tokens[I].int_data[0] = CXToken_Keyword;
5076        }
5077        continue;
5078      }
5079
5080      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5081          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5082        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5083        if (llvm::StringSwitch<bool>(II->getName())
5084            .Case("in", true)
5085            .Case("out", true)
5086            .Case("inout", true)
5087            .Case("oneway", true)
5088            .Case("bycopy", true)
5089            .Case("byref", true)
5090            .Default(false))
5091          Tokens[I].int_data[0] = CXToken_Keyword;
5092        continue;
5093      }
5094
5095      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5096          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5097        Tokens[I].int_data[0] = CXToken_Keyword;
5098        continue;
5099      }
5100    }
5101  }
5102}
5103
5104extern "C" {
5105
5106void clang_annotateTokens(CXTranslationUnit TU,
5107                          CXToken *Tokens, unsigned NumTokens,
5108                          CXCursor *Cursors) {
5109
5110  if (NumTokens == 0 || !Tokens || !Cursors)
5111    return;
5112
5113  // Any token we don't specifically annotate will have a NULL cursor.
5114  CXCursor C = clang_getNullCursor();
5115  for (unsigned I = 0; I != NumTokens; ++I)
5116    Cursors[I] = C;
5117
5118  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5119  if (!CXXUnit)
5120    return;
5121
5122  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5123
5124  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5125  llvm::CrashRecoveryContext CRC;
5126  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5127                 GetSafetyThreadStackSize() * 2)) {
5128    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5129  }
5130}
5131
5132} // end: extern "C"
5133
5134//===----------------------------------------------------------------------===//
5135// Operations for querying linkage of a cursor.
5136//===----------------------------------------------------------------------===//
5137
5138extern "C" {
5139CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5140  if (!clang_isDeclaration(cursor.kind))
5141    return CXLinkage_Invalid;
5142
5143  Decl *D = cxcursor::getCursorDecl(cursor);
5144  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5145    switch (ND->getLinkage()) {
5146      case NoLinkage: return CXLinkage_NoLinkage;
5147      case InternalLinkage: return CXLinkage_Internal;
5148      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5149      case ExternalLinkage: return CXLinkage_External;
5150    };
5151
5152  return CXLinkage_Invalid;
5153}
5154} // end: extern "C"
5155
5156//===----------------------------------------------------------------------===//
5157// Operations for querying language of a cursor.
5158//===----------------------------------------------------------------------===//
5159
5160static CXLanguageKind getDeclLanguage(const Decl *D) {
5161  if (!D)
5162    return CXLanguage_C;
5163
5164  switch (D->getKind()) {
5165    default:
5166      break;
5167    case Decl::ImplicitParam:
5168    case Decl::ObjCAtDefsField:
5169    case Decl::ObjCCategory:
5170    case Decl::ObjCCategoryImpl:
5171    case Decl::ObjCCompatibleAlias:
5172    case Decl::ObjCImplementation:
5173    case Decl::ObjCInterface:
5174    case Decl::ObjCIvar:
5175    case Decl::ObjCMethod:
5176    case Decl::ObjCProperty:
5177    case Decl::ObjCPropertyImpl:
5178    case Decl::ObjCProtocol:
5179      return CXLanguage_ObjC;
5180    case Decl::CXXConstructor:
5181    case Decl::CXXConversion:
5182    case Decl::CXXDestructor:
5183    case Decl::CXXMethod:
5184    case Decl::CXXRecord:
5185    case Decl::ClassTemplate:
5186    case Decl::ClassTemplatePartialSpecialization:
5187    case Decl::ClassTemplateSpecialization:
5188    case Decl::Friend:
5189    case Decl::FriendTemplate:
5190    case Decl::FunctionTemplate:
5191    case Decl::LinkageSpec:
5192    case Decl::Namespace:
5193    case Decl::NamespaceAlias:
5194    case Decl::NonTypeTemplateParm:
5195    case Decl::StaticAssert:
5196    case Decl::TemplateTemplateParm:
5197    case Decl::TemplateTypeParm:
5198    case Decl::UnresolvedUsingTypename:
5199    case Decl::UnresolvedUsingValue:
5200    case Decl::Using:
5201    case Decl::UsingDirective:
5202    case Decl::UsingShadow:
5203      return CXLanguage_CPlusPlus;
5204  }
5205
5206  return CXLanguage_C;
5207}
5208
5209extern "C" {
5210
5211enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5212  if (clang_isDeclaration(cursor.kind))
5213    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5214      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5215        return CXAvailability_Available;
5216
5217      switch (D->getAvailability()) {
5218      case AR_Available:
5219      case AR_NotYetIntroduced:
5220        return CXAvailability_Available;
5221
5222      case AR_Deprecated:
5223        return CXAvailability_Deprecated;
5224
5225      case AR_Unavailable:
5226        return CXAvailability_NotAvailable;
5227      }
5228    }
5229
5230  return CXAvailability_Available;
5231}
5232
5233CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5234  if (clang_isDeclaration(cursor.kind))
5235    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5236
5237  return CXLanguage_Invalid;
5238}
5239
5240 /// \brief If the given cursor is the "templated" declaration
5241 /// descibing a class or function template, return the class or
5242 /// function template.
5243static Decl *maybeGetTemplateCursor(Decl *D) {
5244  if (!D)
5245    return 0;
5246
5247  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5248    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5249      return FunTmpl;
5250
5251  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5252    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5253      return ClassTmpl;
5254
5255  return D;
5256}
5257
5258CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5259  if (clang_isDeclaration(cursor.kind)) {
5260    if (Decl *D = getCursorDecl(cursor)) {
5261      DeclContext *DC = D->getDeclContext();
5262      if (!DC)
5263        return clang_getNullCursor();
5264
5265      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5266                          getCursorTU(cursor));
5267    }
5268  }
5269
5270  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5271    if (Decl *D = getCursorDecl(cursor))
5272      return MakeCXCursor(D, getCursorTU(cursor));
5273  }
5274
5275  return clang_getNullCursor();
5276}
5277
5278CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5279  if (clang_isDeclaration(cursor.kind)) {
5280    if (Decl *D = getCursorDecl(cursor)) {
5281      DeclContext *DC = D->getLexicalDeclContext();
5282      if (!DC)
5283        return clang_getNullCursor();
5284
5285      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5286                          getCursorTU(cursor));
5287    }
5288  }
5289
5290  // FIXME: Note that we can't easily compute the lexical context of a
5291  // statement or expression, so we return nothing.
5292  return clang_getNullCursor();
5293}
5294
5295void clang_getOverriddenCursors(CXCursor cursor,
5296                                CXCursor **overridden,
5297                                unsigned *num_overridden) {
5298  if (overridden)
5299    *overridden = 0;
5300  if (num_overridden)
5301    *num_overridden = 0;
5302  if (!overridden || !num_overridden)
5303    return;
5304
5305  SmallVector<CXCursor, 8> Overridden;
5306  cxcursor::getOverriddenCursors(cursor, Overridden);
5307
5308  // Don't allocate memory if we have no overriden cursors.
5309  if (Overridden.size() == 0)
5310    return;
5311
5312  *num_overridden = Overridden.size();
5313  *overridden = new CXCursor [Overridden.size()];
5314  std::copy(Overridden.begin(), Overridden.end(), *overridden);
5315}
5316
5317void clang_disposeOverriddenCursors(CXCursor *overridden) {
5318  delete [] overridden;
5319}
5320
5321CXFile clang_getIncludedFile(CXCursor cursor) {
5322  if (cursor.kind != CXCursor_InclusionDirective)
5323    return 0;
5324
5325  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5326  return (void *)ID->getFile();
5327}
5328
5329} // end: extern "C"
5330
5331
5332//===----------------------------------------------------------------------===//
5333// C++ AST instrospection.
5334//===----------------------------------------------------------------------===//
5335
5336extern "C" {
5337unsigned clang_CXXMethod_isStatic(CXCursor C) {
5338  if (!clang_isDeclaration(C.kind))
5339    return 0;
5340
5341  CXXMethodDecl *Method = 0;
5342  Decl *D = cxcursor::getCursorDecl(C);
5343  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5344    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5345  else
5346    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5347  return (Method && Method->isStatic()) ? 1 : 0;
5348}
5349
5350unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5351  if (!clang_isDeclaration(C.kind))
5352    return 0;
5353
5354  CXXMethodDecl *Method = 0;
5355  Decl *D = cxcursor::getCursorDecl(C);
5356  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5357    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5358  else
5359    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5360  return (Method && Method->isVirtual()) ? 1 : 0;
5361}
5362} // end: extern "C"
5363
5364//===----------------------------------------------------------------------===//
5365// Attribute introspection.
5366//===----------------------------------------------------------------------===//
5367
5368extern "C" {
5369CXType clang_getIBOutletCollectionType(CXCursor C) {
5370  if (C.kind != CXCursor_IBOutletCollectionAttr)
5371    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5372
5373  IBOutletCollectionAttr *A =
5374    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5375
5376  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5377}
5378} // end: extern "C"
5379
5380//===----------------------------------------------------------------------===//
5381// Inspecting memory usage.
5382//===----------------------------------------------------------------------===//
5383
5384typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5385
5386static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5387                                              enum CXTUResourceUsageKind k,
5388                                              unsigned long amount) {
5389  CXTUResourceUsageEntry entry = { k, amount };
5390  entries.push_back(entry);
5391}
5392
5393extern "C" {
5394
5395const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5396  const char *str = "";
5397  switch (kind) {
5398    case CXTUResourceUsage_AST:
5399      str = "ASTContext: expressions, declarations, and types";
5400      break;
5401    case CXTUResourceUsage_Identifiers:
5402      str = "ASTContext: identifiers";
5403      break;
5404    case CXTUResourceUsage_Selectors:
5405      str = "ASTContext: selectors";
5406      break;
5407    case CXTUResourceUsage_GlobalCompletionResults:
5408      str = "Code completion: cached global results";
5409      break;
5410    case CXTUResourceUsage_SourceManagerContentCache:
5411      str = "SourceManager: content cache allocator";
5412      break;
5413    case CXTUResourceUsage_AST_SideTables:
5414      str = "ASTContext: side tables";
5415      break;
5416    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5417      str = "SourceManager: malloc'ed memory buffers";
5418      break;
5419    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5420      str = "SourceManager: mmap'ed memory buffers";
5421      break;
5422    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5423      str = "ExternalASTSource: malloc'ed memory buffers";
5424      break;
5425    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5426      str = "ExternalASTSource: mmap'ed memory buffers";
5427      break;
5428    case CXTUResourceUsage_Preprocessor:
5429      str = "Preprocessor: malloc'ed memory";
5430      break;
5431    case CXTUResourceUsage_PreprocessingRecord:
5432      str = "Preprocessor: PreprocessingRecord";
5433      break;
5434    case CXTUResourceUsage_SourceManager_DataStructures:
5435      str = "SourceManager: data structures and tables";
5436      break;
5437    case CXTUResourceUsage_Preprocessor_HeaderSearch:
5438      str = "Preprocessor: header search tables";
5439      break;
5440  }
5441  return str;
5442}
5443
5444CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5445  if (!TU) {
5446    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5447    return usage;
5448  }
5449
5450  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5451  llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5452  ASTContext &astContext = astUnit->getASTContext();
5453
5454  // How much memory is used by AST nodes and types?
5455  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5456    (unsigned long) astContext.getASTAllocatedMemory());
5457
5458  // How much memory is used by identifiers?
5459  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5460    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5461
5462  // How much memory is used for selectors?
5463  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5464    (unsigned long) astContext.Selectors.getTotalMemory());
5465
5466  // How much memory is used by ASTContext's side tables?
5467  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5468    (unsigned long) astContext.getSideTableAllocatedMemory());
5469
5470  // How much memory is used for caching global code completion results?
5471  unsigned long completionBytes = 0;
5472  if (GlobalCodeCompletionAllocator *completionAllocator =
5473      astUnit->getCachedCompletionAllocator().getPtr()) {
5474    completionBytes = completionAllocator->getTotalMemory();
5475  }
5476  createCXTUResourceUsageEntry(*entries,
5477                               CXTUResourceUsage_GlobalCompletionResults,
5478                               completionBytes);
5479
5480  // How much memory is being used by SourceManager's content cache?
5481  createCXTUResourceUsageEntry(*entries,
5482          CXTUResourceUsage_SourceManagerContentCache,
5483          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5484
5485  // How much memory is being used by the MemoryBuffer's in SourceManager?
5486  const SourceManager::MemoryBufferSizes &srcBufs =
5487    astUnit->getSourceManager().getMemoryBufferSizes();
5488
5489  createCXTUResourceUsageEntry(*entries,
5490                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5491                               (unsigned long) srcBufs.malloc_bytes);
5492  createCXTUResourceUsageEntry(*entries,
5493                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5494                               (unsigned long) srcBufs.mmap_bytes);
5495  createCXTUResourceUsageEntry(*entries,
5496                               CXTUResourceUsage_SourceManager_DataStructures,
5497                               (unsigned long) astContext.getSourceManager()
5498                                .getDataStructureSizes());
5499
5500  // How much memory is being used by the ExternalASTSource?
5501  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5502    const ExternalASTSource::MemoryBufferSizes &sizes =
5503      esrc->getMemoryBufferSizes();
5504
5505    createCXTUResourceUsageEntry(*entries,
5506      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5507                                 (unsigned long) sizes.malloc_bytes);
5508    createCXTUResourceUsageEntry(*entries,
5509      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5510                                 (unsigned long) sizes.mmap_bytes);
5511  }
5512
5513  // How much memory is being used by the Preprocessor?
5514  Preprocessor &pp = astUnit->getPreprocessor();
5515  createCXTUResourceUsageEntry(*entries,
5516                               CXTUResourceUsage_Preprocessor,
5517                               pp.getTotalMemory());
5518
5519  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5520    createCXTUResourceUsageEntry(*entries,
5521                                 CXTUResourceUsage_PreprocessingRecord,
5522                                 pRec->getTotalMemory());
5523  }
5524
5525  createCXTUResourceUsageEntry(*entries,
5526                               CXTUResourceUsage_Preprocessor_HeaderSearch,
5527                               pp.getHeaderSearchInfo().getTotalMemory());
5528
5529  CXTUResourceUsage usage = { (void*) entries.get(),
5530                            (unsigned) entries->size(),
5531                            entries->size() ? &(*entries)[0] : 0 };
5532  entries.take();
5533  return usage;
5534}
5535
5536void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5537  if (usage.data)
5538    delete (MemUsageEntries*) usage.data;
5539}
5540
5541} // end extern "C"
5542
5543void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5544  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5545  for (unsigned I = 0; I != Usage.numEntries; ++I)
5546    fprintf(stderr, "  %s: %lu\n",
5547            clang_getTUResourceUsageName(Usage.entries[I].kind),
5548            Usage.entries[I].amount);
5549
5550  clang_disposeCXTUResourceUsage(Usage);
5551}
5552
5553//===----------------------------------------------------------------------===//
5554// Misc. utility functions.
5555//===----------------------------------------------------------------------===//
5556
5557/// Default to using an 8 MB stack size on "safety" threads.
5558static unsigned SafetyStackThreadSize = 8 << 20;
5559
5560namespace clang {
5561
5562bool RunSafely(llvm::CrashRecoveryContext &CRC,
5563               void (*Fn)(void*), void *UserData,
5564               unsigned Size) {
5565  if (!Size)
5566    Size = GetSafetyThreadStackSize();
5567  if (Size)
5568    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5569  return CRC.RunSafely(Fn, UserData);
5570}
5571
5572unsigned GetSafetyThreadStackSize() {
5573  return SafetyStackThreadSize;
5574}
5575
5576void SetSafetyThreadStackSize(unsigned Value) {
5577  SafetyStackThreadSize = Value;
5578}
5579
5580}
5581
5582extern "C" {
5583
5584CXString clang_getClangVersion() {
5585  return createCXString(getClangFullVersion());
5586}
5587
5588} // end: extern "C"
5589
5590