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