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