1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the main API hooks in the Clang-C Source Indexing
13 //===----------------------------------------------------------------------===//
16 #include "CIndexDiagnostic.h"
19 #include "CXSourceLocation.h"
21 #include "CXTranslationUnit.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/TargetSelect.h"
57 #include "llvm/Support/Threading.h"
58 #include "llvm/Support/Timer.h"
59 #include "llvm/Support/raw_ostream.h"
61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
62 #define USE_DARWIN_THREADS
65 #ifdef USE_DARWIN_THREADS
69 using namespace clang;
70 using namespace clang::cxcursor;
71 using namespace clang::cxtu;
72 using namespace clang::cxindex;
74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
78 CXTranslationUnit D = new CXTranslationUnitImpl();
81 D->StringPool = new cxstring::CXStringPool();
82 D->Diagnostics = nullptr;
83 D->OverridenCursorsPool = createOverridenCXCursorsPool();
84 D->CommentToXML = nullptr;
88 bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
100 cxtu::CXTUOwner::~CXTUOwner() {
102 clang_disposeTranslationUnit(TU);
105 /// \brief Compare two source ranges to determine their relative position in
106 /// the translation unit.
107 static RangeComparisonResult RangeCompare(SourceManager &SM,
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
121 /// \brief Determine if a source location falls within, before, or after a
122 /// a given source range.
123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
136 /// \brief Translate a Clang source range into a CIndex source range.
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
149 EndLoc = SM.getExpansionRange(EndLoc).second;
150 if (R.isTokenRange() && EndLoc.isValid()) {
151 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
153 EndLoc = EndLoc.getLocWithOffset(Length);
156 CXSourceRange Result = {
158 R.getBegin().getRawEncoding(),
159 EndLoc.getRawEncoding()
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 static SourceRange getRawCursorExtent(CXCursor C);
169 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
172 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
173 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
176 /// \brief Visit the given cursor and, if requested by the visitor,
179 /// \param Cursor the cursor to visit.
181 /// \param CheckedRegionOfInterest if true, then the caller already checked
182 /// that this cursor is within the region of interest.
184 /// \returns true if the visitation should be aborted, false if it
186 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
187 if (clang_isInvalid(Cursor.kind))
190 if (clang_isDeclaration(Cursor.kind)) {
191 const Decl *D = getCursorDecl(Cursor);
193 assert(0 && "Invalid declaration cursor");
194 return true; // abort.
197 // Ignore implicit declarations, unless it's an objc method because
198 // currently we should report implicit methods for properties when indexing.
199 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 // If we have a range of interest, and this cursor doesn't intersect with it,
205 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
206 SourceRange Range = getRawCursorExtent(Cursor);
207 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 switch (Visitor(Cursor, Parent, ClientData)) {
212 case CXChildVisit_Break:
215 case CXChildVisit_Continue:
218 case CXChildVisit_Recurse: {
219 bool ret = VisitChildren(Cursor);
220 if (PostChildrenVisitor)
221 if (PostChildrenVisitor(Cursor, ClientData))
227 llvm_unreachable("Invalid CXChildVisitResult!");
230 static bool visitPreprocessedEntitiesInRange(SourceRange R,
231 PreprocessingRecord &PPRec,
232 CursorVisitor &Visitor) {
233 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
236 if (!Visitor.shouldVisitIncludedEntities()) {
237 // If the begin/end of the range lie in the same FileID, do the optimization
238 // where we skip preprocessed entities that do not come from the same FileID.
239 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
240 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
245 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
249 bool CursorVisitor::visitFileRegion() {
250 if (RegionOfInterest.isInvalid())
253 ASTUnit *Unit = cxtu::getASTUnit(TU);
254 SourceManager &SM = Unit->getSourceManager();
256 std::pair<FileID, unsigned>
257 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
258 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
260 if (End.first != Begin.first) {
261 // If the end does not reside in the same file, try to recover by
262 // picking the end of the file of begin location.
263 End.first = Begin.first;
264 End.second = SM.getFileIDSize(Begin.first);
267 assert(Begin.first == End.first);
268 if (Begin.second > End.second)
271 FileID File = Begin.first;
272 unsigned Offset = Begin.second;
273 unsigned Length = End.second - Begin.second;
275 if (!VisitDeclsOnly && !VisitPreprocessorLast)
276 if (visitPreprocessedEntitiesInRegion())
277 return true; // visitation break.
279 if (visitDeclsFromFileRegion(File, Offset, Length))
280 return true; // visitation break.
282 if (!VisitDeclsOnly && VisitPreprocessorLast)
283 return visitPreprocessedEntitiesInRegion();
288 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 for (DeclContext *DeclDC = D->getLexicalDeclContext();
293 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
301 unsigned Offset, unsigned Length) {
302 ASTUnit *Unit = cxtu::getASTUnit(TU);
303 SourceManager &SM = Unit->getSourceManager();
304 SourceRange Range = RegionOfInterest;
306 SmallVector<Decl *, 16> Decls;
307 Unit->findFileRegionDecls(File, Offset, Length, Decls);
309 // If we didn't find any file level decls for the file, try looking at the
310 // file that it was included from.
311 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
312 bool Invalid = false;
313 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 SourceLocation Outer;
318 if (SLEntry.isFile())
319 Outer = SLEntry.getFile().getIncludeLoc();
321 Outer = SLEntry.getExpansion().getExpansionLocStart();
322 if (Outer.isInvalid())
325 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
327 Unit->findFileRegionDecls(File, Offset, Length, Decls);
330 assert(!Decls.empty());
332 bool VisitedAtLeastOnce = false;
333 DeclContext *CurDC = nullptr;
334 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
335 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
337 if (D->getSourceRange().isInvalid())
340 if (isInLexicalContext(D, CurDC))
343 CurDC = dyn_cast<DeclContext>(D);
345 if (TagDecl *TD = dyn_cast<TagDecl>(D))
346 if (!TD->isFreeStanding())
349 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
350 if (CompRes == RangeBefore)
352 if (CompRes == RangeAfter)
355 assert(CompRes == RangeOverlap);
356 VisitedAtLeastOnce = true;
358 if (isa<ObjCContainerDecl>(D)) {
359 FileDI_current = &DIt;
362 FileDI_current = nullptr;
365 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
366 return true; // visitation break.
369 if (VisitedAtLeastOnce)
372 // No Decls overlapped with the range. Move up the lexical context until there
373 // is a context that contains the range or we reach the translation unit
375 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
376 : (*(DIt-1))->getLexicalDeclContext();
378 while (DC && !DC->isTranslationUnit()) {
379 Decl *D = cast<Decl>(DC);
380 SourceRange CurDeclRange = D->getSourceRange();
381 if (CurDeclRange.isInvalid())
384 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
385 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
386 return true; // visitation break.
389 DC = D->getLexicalDeclContext();
395 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
396 if (!AU->getPreprocessor().getPreprocessingRecord())
399 PreprocessingRecord &PPRec
400 = *AU->getPreprocessor().getPreprocessingRecord();
401 SourceManager &SM = AU->getSourceManager();
403 if (RegionOfInterest.isValid()) {
404 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
405 SourceLocation B = MappedRange.getBegin();
406 SourceLocation E = MappedRange.getEnd();
408 if (AU->isInPreambleFileID(B)) {
409 if (SM.isLoadedSourceLocation(E))
410 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
413 // Beginning of range lies in the preamble but it also extends beyond
414 // it into the main file. Split the range into 2 parts, one covering
415 // the preamble and another covering the main file. This allows subsequent
416 // calls to visitPreprocessedEntitiesInRange to accept a source range that
417 // lies in the same FileID, allowing it to skip preprocessed entities that
418 // do not come from the same FileID.
420 visitPreprocessedEntitiesInRange(
421 SourceRange(B, AU->getEndOfPreambleFileID()),
423 if (breaked) return true;
424 return visitPreprocessedEntitiesInRange(
425 SourceRange(AU->getStartOfMainFileID(), E),
429 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
436 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
439 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
442 template<typename InputIterator>
443 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
445 PreprocessingRecord &PPRec,
447 for (; First != Last; ++First) {
448 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
451 PreprocessedEntity *PPE = *First;
455 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
456 if (Visit(MakeMacroExpansionCursor(ME, TU)))
462 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
463 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
469 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
470 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 /// \brief Visit the children of the given cursor.
482 /// \returns true if the visitation should be aborted, false if it
484 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
485 if (clang_isReference(Cursor.kind) &&
486 Cursor.kind != CXCursor_CXXBaseSpecifier) {
487 // By definition, references have no children.
491 // Set the Parent field to Cursor, then back to its old value once we're
493 SetParentRAII SetParent(Parent, StmtParent, Cursor);
495 if (clang_isDeclaration(Cursor.kind)) {
496 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
500 return VisitAttributes(D) || Visit(D);
503 if (clang_isStatement(Cursor.kind)) {
504 if (const Stmt *S = getCursorStmt(Cursor))
510 if (clang_isExpression(Cursor.kind)) {
511 if (const Expr *E = getCursorExpr(Cursor))
517 if (clang_isTranslationUnit(Cursor.kind)) {
518 CXTranslationUnit TU = getCursorTU(Cursor);
519 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
521 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
522 for (unsigned I = 0; I != 2; ++I) {
524 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525 RegionOfInterest.isInvalid()) {
526 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527 TLEnd = CXXUnit->top_level_end();
529 if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
555 const IBOutletCollectionAttr *A =
556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
577 // Nothing to visit at the moment.
581 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
592 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
598 switch (CompareRegionOfInterest(Range)) {
600 // This declaration comes before the region of interest; skip it.
604 // This declaration comes after the region of interest; we're done.
608 // This declaration overlaps the region of interest; visit it.
615 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623 for ( ; I != E; ++I) {
625 if (D->getLexicalDeclContext() != DC)
627 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
629 // Ignore synthesized ivars here, otherwise if we have something like:
630 // @synthesize prop = _prop;
631 // and '_prop' is not declared, we will encounter a '_prop' ivar before
632 // encountering the 'prop' synthesize declaration and we will think that
633 // we passed the region-of-interest.
634 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
635 if (ivarD->getSynthesize())
639 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
640 // declarations is a mismatch with the compiler semantics.
641 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
642 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
643 if (!ID->isThisDeclarationADefinition())
644 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
646 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
647 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
648 if (!PD->isThisDeclarationADefinition())
649 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
652 const Optional<bool> &V = shouldVisitCursor(Cursor);
657 if (Visit(Cursor, true))
663 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
664 llvm_unreachable("Translation units are visited directly by Visit()");
667 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
668 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
669 return Visit(TSInfo->getTypeLoc());
674 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
675 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
676 return Visit(TSInfo->getTypeLoc());
681 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
682 return VisitDeclContext(D);
685 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
686 ClassTemplateSpecializationDecl *D) {
687 bool ShouldVisitBody = false;
688 switch (D->getSpecializationKind()) {
690 case TSK_ImplicitInstantiation:
694 case TSK_ExplicitInstantiationDeclaration:
695 case TSK_ExplicitInstantiationDefinition:
698 case TSK_ExplicitSpecialization:
699 ShouldVisitBody = true;
703 // Visit the template arguments used in the specialization.
704 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
705 TypeLoc TL = SpecType->getTypeLoc();
706 if (TemplateSpecializationTypeLoc TSTLoc =
707 TL.getAs<TemplateSpecializationTypeLoc>()) {
708 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
709 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
714 if (ShouldVisitBody && VisitCXXRecordDecl(D))
720 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
721 ClassTemplatePartialSpecializationDecl *D) {
722 // FIXME: Visit the "outer" template parameter lists on the TagDecl
723 // before visiting these template parameters.
724 if (VisitTemplateParameters(D->getTemplateParameters()))
727 // Visit the partial specialization arguments.
728 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
729 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
730 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
731 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
734 return VisitCXXRecordDecl(D);
737 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
738 // Visit the default argument.
739 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
740 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
741 if (Visit(DefArg->getTypeLoc()))
747 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
748 if (Expr *Init = D->getInitExpr())
749 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
753 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
754 unsigned NumParamList = DD->getNumTemplateParameterLists();
755 for (unsigned i = 0; i < NumParamList; i++) {
756 TemplateParameterList* Params = DD->getTemplateParameterList(i);
757 if (VisitTemplateParameters(Params))
761 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
762 if (Visit(TSInfo->getTypeLoc()))
765 // Visit the nested-name-specifier, if present.
766 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
767 if (VisitNestedNameSpecifierLoc(QualifierLoc))
773 /// \brief Compare two base or member initializers based on their source order.
774 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
775 CXXCtorInitializer *const *Y) {
776 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
779 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
780 unsigned NumParamList = ND->getNumTemplateParameterLists();
781 for (unsigned i = 0; i < NumParamList; i++) {
782 TemplateParameterList* Params = ND->getTemplateParameterList(i);
783 if (VisitTemplateParameters(Params))
787 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
788 // Visit the function declaration's syntactic components in the order
789 // written. This requires a bit of work.
790 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
791 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
793 // If we have a function declared directly (without the use of a typedef),
794 // visit just the return type. Otherwise, just visit the function's type
796 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
800 // Visit the nested-name-specifier, if present.
801 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
802 if (VisitNestedNameSpecifierLoc(QualifierLoc))
805 // Visit the declaration name.
806 if (!isa<CXXDestructorDecl>(ND))
807 if (VisitDeclarationNameInfo(ND->getNameInfo()))
810 // FIXME: Visit explicitly-specified template arguments!
812 // Visit the function parameters, if we have a function type.
813 if (FTL && VisitFunctionTypeLoc(FTL, true))
816 // FIXME: Attributes?
819 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
820 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
821 // Find the initializers that were written in the source.
822 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
823 for (auto *I : Constructor->inits()) {
827 WrittenInits.push_back(I);
830 // Sort the initializers in source order
831 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
832 &CompareCXXCtorInitializers);
834 // Visit the initializers in source order
835 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
836 CXXCtorInitializer *Init = WrittenInits[I];
837 if (Init->isAnyMemberInitializer()) {
838 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
839 Init->getMemberLocation(), TU)))
841 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
842 if (Visit(TInfo->getTypeLoc()))
846 // Visit the initializer value.
847 if (Expr *Initializer = Init->getInit())
848 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
853 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
860 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
861 if (VisitDeclaratorDecl(D))
864 if (Expr *BitWidth = D->getBitWidth())
865 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
870 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
871 if (VisitDeclaratorDecl(D))
874 if (Expr *Init = D->getInit())
875 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
880 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
881 if (VisitDeclaratorDecl(D))
884 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
885 if (Expr *DefArg = D->getDefaultArgument())
886 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
891 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
892 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
893 // before visiting these template parameters.
894 if (VisitTemplateParameters(D->getTemplateParameters()))
897 return VisitFunctionDecl(D->getTemplatedDecl());
900 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
901 // FIXME: Visit the "outer" template parameter lists on the TagDecl
902 // before visiting these template parameters.
903 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return VisitCXXRecordDecl(D->getTemplatedDecl());
909 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
910 if (VisitTemplateParameters(D->getTemplateParameters()))
913 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
914 VisitTemplateArgumentLoc(D->getDefaultArgument()))
920 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
921 // Visit the bound, if it's explicit.
922 if (D->hasExplicitBound()) {
923 if (auto TInfo = D->getTypeSourceInfo()) {
924 if (Visit(TInfo->getTypeLoc()))
932 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
933 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
934 if (Visit(TSInfo->getTypeLoc()))
937 for (const auto *P : ND->params()) {
938 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
942 if (ND->isThisDeclarationADefinition() &&
943 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
949 template <typename DeclIt>
950 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
951 SourceManager &SM, SourceLocation EndLoc,
952 SmallVectorImpl<Decl *> &Decls) {
953 DeclIt next = *DI_current;
954 while (++next != DE_current) {
955 Decl *D_next = *next;
958 SourceLocation L = D_next->getLocStart();
961 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
963 Decls.push_back(D_next);
970 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
971 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
972 // an @implementation can lexically contain Decls that are not properly
973 // nested in the AST. When we identify such cases, we need to retrofit
974 // this nesting here.
975 if (!DI_current && !FileDI_current)
976 return VisitDeclContext(D);
978 // Scan the Decls that immediately come after the container
979 // in the current DeclContext. If any fall within the
980 // container's lexical region, stash them into a vector
981 // for later processing.
982 SmallVector<Decl *, 24> DeclsInContainer;
983 SourceLocation EndLoc = D->getSourceRange().getEnd();
984 SourceManager &SM = AU->getSourceManager();
985 if (EndLoc.isValid()) {
987 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
990 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
996 if (DeclsInContainer.empty())
997 return VisitDeclContext(D);
999 // Get all the Decls in the DeclContext, and sort them with the
1000 // additional ones we've collected. Then visit them.
1001 for (auto *SubDecl : D->decls()) {
1002 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1003 SubDecl->getLocStart().isInvalid())
1005 DeclsInContainer.push_back(SubDecl);
1008 // Now sort the Decls so that they appear in lexical order.
1009 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1010 [&SM](Decl *A, Decl *B) {
1011 SourceLocation L_A = A->getLocStart();
1012 SourceLocation L_B = B->getLocStart();
1013 assert(L_A.isValid() && L_B.isValid());
1014 return SM.isBeforeInTranslationUnit(L_A, L_B);
1017 // Now visit the decls.
1018 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1019 E = DeclsInContainer.end(); I != E; ++I) {
1020 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1021 const Optional<bool> &V = shouldVisitCursor(Cursor);
1026 if (Visit(Cursor, true))
1032 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1033 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1037 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1040 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1041 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1042 E = ND->protocol_end(); I != E; ++I, ++PL)
1043 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1046 return VisitObjCContainerDecl(ND);
1049 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1050 if (!PID->isThisDeclarationADefinition())
1051 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1053 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1054 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1055 E = PID->protocol_end(); I != E; ++I, ++PL)
1056 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1059 return VisitObjCContainerDecl(PID);
1062 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1063 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1066 // FIXME: This implements a workaround with @property declarations also being
1067 // installed in the DeclContext for the @interface. Eventually this code
1068 // should be removed.
1069 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1070 if (!CDecl || !CDecl->IsClassExtension())
1073 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1077 IdentifierInfo *PropertyId = PD->getIdentifier();
1078 ObjCPropertyDecl *prevDecl =
1079 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1084 // Visit synthesized methods since they will be skipped when visiting
1086 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1087 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1088 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1091 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1092 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1093 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1099 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1103 for (auto *typeParam : *typeParamList) {
1104 // Visit the type parameter.
1105 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1112 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1113 if (!D->isThisDeclarationADefinition()) {
1114 // Forward declaration is treated like a reference.
1115 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1118 // Objective-C type parameters.
1119 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1122 // Issue callbacks for super class.
1123 if (D->getSuperClass() &&
1124 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1125 D->getSuperClassLoc(),
1129 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1130 if (Visit(SuperClassTInfo->getTypeLoc()))
1133 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1134 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1135 E = D->protocol_end(); I != E; ++I, ++PL)
1136 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1139 return VisitObjCContainerDecl(D);
1142 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1143 return VisitObjCContainerDecl(D);
1146 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1147 // 'ID' could be null when dealing with invalid code.
1148 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1149 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1152 return VisitObjCImplDecl(D);
1155 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1157 // Issue callbacks for super class.
1158 // FIXME: No source location information!
1159 if (D->getSuperClass() &&
1160 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1161 D->getSuperClassLoc(),
1166 return VisitObjCImplDecl(D);
1169 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1170 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1171 if (PD->isIvarNameSpecified())
1172 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1177 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1178 return VisitDeclContext(D);
1181 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1182 // Visit nested-name-specifier.
1183 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1184 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1187 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1188 D->getTargetNameLoc(), TU));
1191 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1192 // Visit nested-name-specifier.
1193 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1194 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1198 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1201 return VisitDeclarationNameInfo(D->getNameInfo());
1204 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1205 // Visit nested-name-specifier.
1206 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1207 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1210 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1211 D->getIdentLocation(), TU));
1214 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1215 // Visit nested-name-specifier.
1216 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1221 return VisitDeclarationNameInfo(D->getNameInfo());
1224 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1225 UnresolvedUsingTypenameDecl *D) {
1226 // Visit nested-name-specifier.
1227 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1234 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1235 switch (Name.getName().getNameKind()) {
1236 case clang::DeclarationName::Identifier:
1237 case clang::DeclarationName::CXXLiteralOperatorName:
1238 case clang::DeclarationName::CXXOperatorName:
1239 case clang::DeclarationName::CXXUsingDirective:
1242 case clang::DeclarationName::CXXConstructorName:
1243 case clang::DeclarationName::CXXDestructorName:
1244 case clang::DeclarationName::CXXConversionFunctionName:
1245 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1246 return Visit(TSInfo->getTypeLoc());
1249 case clang::DeclarationName::ObjCZeroArgSelector:
1250 case clang::DeclarationName::ObjCOneArgSelector:
1251 case clang::DeclarationName::ObjCMultiArgSelector:
1252 // FIXME: Per-identifier location info?
1256 llvm_unreachable("Invalid DeclarationName::Kind!");
1259 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1260 SourceRange Range) {
1261 // FIXME: This whole routine is a hack to work around the lack of proper
1262 // source information in nested-name-specifiers (PR5791). Since we do have
1263 // a beginning source location, we can visit the first component of the
1264 // nested-name-specifier, if it's a single-token component.
1268 // Get the first component in the nested-name-specifier.
1269 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1272 switch (NNS->getKind()) {
1273 case NestedNameSpecifier::Namespace:
1274 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1277 case NestedNameSpecifier::NamespaceAlias:
1278 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1279 Range.getBegin(), TU));
1281 case NestedNameSpecifier::TypeSpec: {
1282 // If the type has a form where we know that the beginning of the source
1283 // range matches up with a reference cursor. Visit the appropriate reference
1285 const Type *T = NNS->getAsType();
1286 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1287 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1288 if (const TagType *Tag = dyn_cast<TagType>(T))
1289 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1290 if (const TemplateSpecializationType *TST
1291 = dyn_cast<TemplateSpecializationType>(T))
1292 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1296 case NestedNameSpecifier::TypeSpecWithTemplate:
1297 case NestedNameSpecifier::Global:
1298 case NestedNameSpecifier::Identifier:
1299 case NestedNameSpecifier::Super:
1307 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1308 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1309 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1310 Qualifiers.push_back(Qualifier);
1312 while (!Qualifiers.empty()) {
1313 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1314 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1315 switch (NNS->getKind()) {
1316 case NestedNameSpecifier::Namespace:
1317 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1318 Q.getLocalBeginLoc(),
1324 case NestedNameSpecifier::NamespaceAlias:
1325 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1326 Q.getLocalBeginLoc(),
1332 case NestedNameSpecifier::TypeSpec:
1333 case NestedNameSpecifier::TypeSpecWithTemplate:
1334 if (Visit(Q.getTypeLoc()))
1339 case NestedNameSpecifier::Global:
1340 case NestedNameSpecifier::Identifier:
1341 case NestedNameSpecifier::Super:
1349 bool CursorVisitor::VisitTemplateParameters(
1350 const TemplateParameterList *Params) {
1354 for (TemplateParameterList::const_iterator P = Params->begin(),
1355 PEnd = Params->end();
1357 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1364 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1365 switch (Name.getKind()) {
1366 case TemplateName::Template:
1367 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1369 case TemplateName::OverloadedTemplate:
1370 // Visit the overloaded template set.
1371 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1376 case TemplateName::DependentTemplate:
1377 // FIXME: Visit nested-name-specifier.
1380 case TemplateName::QualifiedTemplate:
1381 // FIXME: Visit nested-name-specifier.
1382 return Visit(MakeCursorTemplateRef(
1383 Name.getAsQualifiedTemplateName()->getDecl(),
1386 case TemplateName::SubstTemplateTemplateParm:
1387 return Visit(MakeCursorTemplateRef(
1388 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1391 case TemplateName::SubstTemplateTemplateParmPack:
1392 return Visit(MakeCursorTemplateRef(
1393 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1397 llvm_unreachable("Invalid TemplateName::Kind!");
1400 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1401 switch (TAL.getArgument().getKind()) {
1402 case TemplateArgument::Null:
1403 case TemplateArgument::Integral:
1404 case TemplateArgument::Pack:
1407 case TemplateArgument::Type:
1408 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1409 return Visit(TSInfo->getTypeLoc());
1412 case TemplateArgument::Declaration:
1413 if (Expr *E = TAL.getSourceDeclExpression())
1414 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1417 case TemplateArgument::NullPtr:
1418 if (Expr *E = TAL.getSourceNullPtrExpression())
1419 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1422 case TemplateArgument::Expression:
1423 if (Expr *E = TAL.getSourceExpression())
1424 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1427 case TemplateArgument::Template:
1428 case TemplateArgument::TemplateExpansion:
1429 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1432 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1433 TAL.getTemplateNameLoc());
1436 llvm_unreachable("Invalid TemplateArgument::Kind!");
1439 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1440 return VisitDeclContext(D);
1443 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1444 return Visit(TL.getUnqualifiedLoc());
1447 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1448 ASTContext &Context = AU->getASTContext();
1450 // Some builtin types (such as Objective-C's "id", "sel", and
1451 // "Class") have associated declarations. Create cursors for those.
1453 switch (TL.getTypePtr()->getKind()) {
1455 case BuiltinType::Void:
1456 case BuiltinType::NullPtr:
1457 case BuiltinType::Dependent:
1458 case BuiltinType::OCLImage1d:
1459 case BuiltinType::OCLImage1dArray:
1460 case BuiltinType::OCLImage1dBuffer:
1461 case BuiltinType::OCLImage2d:
1462 case BuiltinType::OCLImage2dArray:
1463 case BuiltinType::OCLImage2dDepth:
1464 case BuiltinType::OCLImage2dArrayDepth:
1465 case BuiltinType::OCLImage2dMSAA:
1466 case BuiltinType::OCLImage2dArrayMSAA:
1467 case BuiltinType::OCLImage2dMSAADepth:
1468 case BuiltinType::OCLImage2dArrayMSAADepth:
1469 case BuiltinType::OCLImage3d:
1470 case BuiltinType::OCLSampler:
1471 case BuiltinType::OCLEvent:
1472 case BuiltinType::OCLClkEvent:
1473 case BuiltinType::OCLQueue:
1474 case BuiltinType::OCLNDRange:
1475 case BuiltinType::OCLReserveID:
1476 #define BUILTIN_TYPE(Id, SingletonId)
1477 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1478 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1479 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1480 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1481 #include "clang/AST/BuiltinTypes.def"
1484 case BuiltinType::ObjCId:
1485 VisitType = Context.getObjCIdType();
1488 case BuiltinType::ObjCClass:
1489 VisitType = Context.getObjCClassType();
1492 case BuiltinType::ObjCSel:
1493 VisitType = Context.getObjCSelType();
1497 if (!VisitType.isNull()) {
1498 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1499 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1506 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1507 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1510 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1511 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1514 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1515 if (TL.isDefinition())
1516 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1518 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1521 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1522 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1525 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1526 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1529 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1530 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1533 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1534 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1538 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1539 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1547 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1548 return Visit(TL.getPointeeLoc());
1551 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1552 return Visit(TL.getInnerLoc());
1555 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1556 return Visit(TL.getPointeeLoc());
1559 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1560 return Visit(TL.getPointeeLoc());
1563 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1564 return Visit(TL.getPointeeLoc());
1567 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1568 return Visit(TL.getPointeeLoc());
1571 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1572 return Visit(TL.getPointeeLoc());
1575 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1576 return Visit(TL.getModifiedLoc());
1579 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1580 bool SkipResultType) {
1581 if (!SkipResultType && Visit(TL.getReturnLoc()))
1584 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1585 if (Decl *D = TL.getParam(I))
1586 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1592 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1593 if (Visit(TL.getElementLoc()))
1596 if (Expr *Size = TL.getSizeExpr())
1597 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1602 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1603 return Visit(TL.getOriginalLoc());
1606 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1607 return Visit(TL.getOriginalLoc());
1610 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1611 TemplateSpecializationTypeLoc TL) {
1612 // Visit the template name.
1613 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1614 TL.getTemplateNameLoc()))
1617 // Visit the template arguments.
1618 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1619 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1625 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1626 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1629 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1630 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1631 return Visit(TSInfo->getTypeLoc());
1636 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1637 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1638 return Visit(TSInfo->getTypeLoc());
1643 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1644 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1647 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1648 DependentTemplateSpecializationTypeLoc TL) {
1649 // Visit the nested-name-specifier, if there is one.
1650 if (TL.getQualifierLoc() &&
1651 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1654 // Visit the template arguments.
1655 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1656 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1662 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1663 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1666 return Visit(TL.getNamedTypeLoc());
1669 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1670 return Visit(TL.getPatternLoc());
1673 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1674 if (Expr *E = TL.getUnderlyingExpr())
1675 return Visit(MakeCXCursor(E, StmtParent, TU));
1680 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1681 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1684 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1685 return Visit(TL.getValueLoc());
1688 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1689 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1690 return Visit##PARENT##Loc(TL); \
1693 DEFAULT_TYPELOC_IMPL(Complex, Type)
1694 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1695 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1696 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1697 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1698 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1699 DEFAULT_TYPELOC_IMPL(Vector, Type)
1700 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1701 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1702 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1703 DEFAULT_TYPELOC_IMPL(Record, TagType)
1704 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1705 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1706 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1707 DEFAULT_TYPELOC_IMPL(Auto, Type)
1709 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1710 // Visit the nested-name-specifier, if present.
1711 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1712 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1715 if (D->isCompleteDefinition()) {
1716 for (const auto &I : D->bases()) {
1717 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1722 return VisitTagDecl(D);
1725 bool CursorVisitor::VisitAttributes(Decl *D) {
1726 for (const auto *I : D->attrs())
1727 if (Visit(MakeCXCursor(I, D, TU)))
1733 //===----------------------------------------------------------------------===//
1734 // Data-recursive visitor methods.
1735 //===----------------------------------------------------------------------===//
1738 #define DEF_JOB(NAME, DATA, KIND)\
1739 class NAME : public VisitorJob {\
1741 NAME(const DATA *d, CXCursor parent) : \
1742 VisitorJob(parent, VisitorJob::KIND, d) {} \
1743 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1744 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1747 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1748 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1749 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1750 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1751 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1752 ExplicitTemplateArgsVisitKind)
1753 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1754 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1755 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1758 class DeclVisit : public VisitorJob {
1760 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1761 VisitorJob(parent, VisitorJob::DeclVisitKind,
1762 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1763 static bool classof(const VisitorJob *VJ) {
1764 return VJ->getKind() == DeclVisitKind;
1766 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1767 bool isFirst() const { return data[1] != nullptr; }
1769 class TypeLocVisit : public VisitorJob {
1771 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1772 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1773 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1775 static bool classof(const VisitorJob *VJ) {
1776 return VJ->getKind() == TypeLocVisitKind;
1779 TypeLoc get() const {
1780 QualType T = QualType::getFromOpaquePtr(data[0]);
1781 return TypeLoc(T, const_cast<void *>(data[1]));
1785 class LabelRefVisit : public VisitorJob {
1787 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1788 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1789 labelLoc.getPtrEncoding()) {}
1791 static bool classof(const VisitorJob *VJ) {
1792 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1794 const LabelDecl *get() const {
1795 return static_cast<const LabelDecl *>(data[0]);
1797 SourceLocation getLoc() const {
1798 return SourceLocation::getFromPtrEncoding(data[1]); }
1801 class NestedNameSpecifierLocVisit : public VisitorJob {
1803 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1804 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1805 Qualifier.getNestedNameSpecifier(),
1806 Qualifier.getOpaqueData()) { }
1808 static bool classof(const VisitorJob *VJ) {
1809 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1812 NestedNameSpecifierLoc get() const {
1813 return NestedNameSpecifierLoc(
1814 const_cast<NestedNameSpecifier *>(
1815 static_cast<const NestedNameSpecifier *>(data[0])),
1816 const_cast<void *>(data[1]));
1820 class DeclarationNameInfoVisit : public VisitorJob {
1822 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1823 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1824 static bool classof(const VisitorJob *VJ) {
1825 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1827 DeclarationNameInfo get() const {
1828 const Stmt *S = static_cast<const Stmt *>(data[0]);
1829 switch (S->getStmtClass()) {
1831 llvm_unreachable("Unhandled Stmt");
1832 case clang::Stmt::MSDependentExistsStmtClass:
1833 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1834 case Stmt::CXXDependentScopeMemberExprClass:
1835 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1836 case Stmt::DependentScopeDeclRefExprClass:
1837 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1838 case Stmt::OMPCriticalDirectiveClass:
1839 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1843 class MemberRefVisit : public VisitorJob {
1845 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1846 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1847 L.getPtrEncoding()) {}
1848 static bool classof(const VisitorJob *VJ) {
1849 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1851 const FieldDecl *get() const {
1852 return static_cast<const FieldDecl *>(data[0]);
1854 SourceLocation getLoc() const {
1855 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1858 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1859 friend class OMPClauseEnqueue;
1860 VisitorWorkList &WL;
1863 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1864 : WL(wl), Parent(parent) {}
1866 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1867 void VisitBlockExpr(const BlockExpr *B);
1868 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1869 void VisitCompoundStmt(const CompoundStmt *S);
1870 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1871 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1872 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1873 void VisitCXXNewExpr(const CXXNewExpr *E);
1874 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1875 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1876 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1877 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1878 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1879 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1880 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1881 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1882 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1883 void VisitDeclRefExpr(const DeclRefExpr *D);
1884 void VisitDeclStmt(const DeclStmt *S);
1885 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1886 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1887 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1888 void VisitForStmt(const ForStmt *FS);
1889 void VisitGotoStmt(const GotoStmt *GS);
1890 void VisitIfStmt(const IfStmt *If);
1891 void VisitInitListExpr(const InitListExpr *IE);
1892 void VisitMemberExpr(const MemberExpr *M);
1893 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1894 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1895 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1896 void VisitOverloadExpr(const OverloadExpr *E);
1897 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1898 void VisitStmt(const Stmt *S);
1899 void VisitSwitchStmt(const SwitchStmt *S);
1900 void VisitWhileStmt(const WhileStmt *W);
1901 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1902 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1903 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1904 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1905 void VisitVAArgExpr(const VAArgExpr *E);
1906 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1907 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1908 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1909 void VisitLambdaExpr(const LambdaExpr *E);
1910 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1911 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1912 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1913 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1914 void VisitOMPForDirective(const OMPForDirective *D);
1915 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1916 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1917 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1918 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1919 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1920 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1921 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1922 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1923 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1924 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1925 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1926 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1927 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1928 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1930 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1931 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1932 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1933 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1934 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1935 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1936 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1937 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1940 void AddDeclarationNameInfo(const Stmt *S);
1941 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1942 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1943 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1944 void AddStmt(const Stmt *S);
1945 void AddDecl(const Decl *D, bool isFirst = true);
1946 void AddTypeLoc(TypeSourceInfo *TI);
1947 void EnqueueChildren(const Stmt *S);
1948 void EnqueueChildren(const OMPClause *S);
1950 } // end anonyous namespace
1952 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1953 // 'S' should always be non-null, since it comes from the
1954 // statement we are visiting.
1955 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1959 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1961 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1964 void EnqueueVisitor::AddStmt(const Stmt *S) {
1966 WL.push_back(StmtVisit(S, Parent));
1968 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1970 WL.push_back(DeclVisit(D, Parent, isFirst));
1972 void EnqueueVisitor::
1973 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1975 WL.push_back(ExplicitTemplateArgsVisit(A, Parent));
1977 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
1979 WL.push_back(MemberRefVisit(D, L, Parent));
1981 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1983 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1985 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
1986 unsigned size = WL.size();
1987 for (const Stmt *SubStmt : S->children()) {
1990 if (size == WL.size())
1992 // Now reverse the entries we just added. This will match the DFS
1993 // ordering performed by the worklist.
1994 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1998 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
1999 EnqueueVisitor *Visitor;
2000 /// \brief Process clauses with list of variables.
2001 template <typename T>
2002 void VisitOMPClauseList(T *Node);
2004 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2005 #define OPENMP_CLAUSE(Name, Class) \
2006 void Visit##Class(const Class *C);
2007 #include "clang/Basic/OpenMPKinds.def"
2010 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2011 Visitor->AddStmt(C->getCondition());
2014 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2015 Visitor->AddStmt(C->getCondition());
2018 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2019 Visitor->AddStmt(C->getNumThreads());
2022 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2023 Visitor->AddStmt(C->getSafelen());
2026 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2027 Visitor->AddStmt(C->getSimdlen());
2030 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2031 Visitor->AddStmt(C->getNumForLoops());
2034 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2036 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2038 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2039 Visitor->AddStmt(C->getChunkSize());
2040 Visitor->AddStmt(C->getHelperChunkSize());
2043 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2044 Visitor->AddStmt(C->getNumForLoops());
2047 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2049 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2051 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2053 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2055 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2057 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2059 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2061 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2063 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2065 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2067 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2068 Visitor->AddStmt(C->getDevice());
2071 template<typename T>
2072 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2073 for (const auto *I : Node->varlists()) {
2074 Visitor->AddStmt(I);
2078 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2079 VisitOMPClauseList(C);
2080 for (const auto *E : C->private_copies()) {
2081 Visitor->AddStmt(E);
2084 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2085 const OMPFirstprivateClause *C) {
2086 VisitOMPClauseList(C);
2088 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2089 const OMPLastprivateClause *C) {
2090 VisitOMPClauseList(C);
2091 for (auto *E : C->private_copies()) {
2092 Visitor->AddStmt(E);
2094 for (auto *E : C->source_exprs()) {
2095 Visitor->AddStmt(E);
2097 for (auto *E : C->destination_exprs()) {
2098 Visitor->AddStmt(E);
2100 for (auto *E : C->assignment_ops()) {
2101 Visitor->AddStmt(E);
2104 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2105 VisitOMPClauseList(C);
2107 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2108 VisitOMPClauseList(C);
2109 for (auto *E : C->lhs_exprs()) {
2110 Visitor->AddStmt(E);
2112 for (auto *E : C->rhs_exprs()) {
2113 Visitor->AddStmt(E);
2115 for (auto *E : C->reduction_ops()) {
2116 Visitor->AddStmt(E);
2119 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2120 VisitOMPClauseList(C);
2121 for (const auto *E : C->privates()) {
2122 Visitor->AddStmt(E);
2124 for (const auto *E : C->inits()) {
2125 Visitor->AddStmt(E);
2127 for (const auto *E : C->updates()) {
2128 Visitor->AddStmt(E);
2130 for (const auto *E : C->finals()) {
2131 Visitor->AddStmt(E);
2133 Visitor->AddStmt(C->getStep());
2134 Visitor->AddStmt(C->getCalcStep());
2136 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2137 VisitOMPClauseList(C);
2138 Visitor->AddStmt(C->getAlignment());
2140 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2141 VisitOMPClauseList(C);
2142 for (auto *E : C->source_exprs()) {
2143 Visitor->AddStmt(E);
2145 for (auto *E : C->destination_exprs()) {
2146 Visitor->AddStmt(E);
2148 for (auto *E : C->assignment_ops()) {
2149 Visitor->AddStmt(E);
2153 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2154 VisitOMPClauseList(C);
2155 for (auto *E : C->source_exprs()) {
2156 Visitor->AddStmt(E);
2158 for (auto *E : C->destination_exprs()) {
2159 Visitor->AddStmt(E);
2161 for (auto *E : C->assignment_ops()) {
2162 Visitor->AddStmt(E);
2165 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2166 VisitOMPClauseList(C);
2168 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2169 VisitOMPClauseList(C);
2173 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2174 unsigned size = WL.size();
2175 OMPClauseEnqueue Visitor(this);
2177 if (size == WL.size())
2179 // Now reverse the entries we just added. This will match the DFS
2180 // ordering performed by the worklist.
2181 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2184 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2185 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2187 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2188 AddDecl(B->getBlockDecl());
2190 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2192 AddTypeLoc(E->getTypeSourceInfo());
2194 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2195 for (auto &I : llvm::reverse(S->body()))
2198 void EnqueueVisitor::
2199 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2200 AddStmt(S->getSubStmt());
2201 AddDeclarationNameInfo(S);
2202 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2203 AddNestedNameSpecifierLoc(QualifierLoc);
2206 void EnqueueVisitor::
2207 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2208 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2209 AddDeclarationNameInfo(E);
2210 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2211 AddNestedNameSpecifierLoc(QualifierLoc);
2212 if (!E->isImplicitAccess())
2213 AddStmt(E->getBase());
2215 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2216 // Enqueue the initializer , if any.
2217 AddStmt(E->getInitializer());
2218 // Enqueue the array size, if any.
2219 AddStmt(E->getArraySize());
2220 // Enqueue the allocated type.
2221 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2222 // Enqueue the placement arguments.
2223 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2224 AddStmt(E->getPlacementArg(I-1));
2226 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2227 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2228 AddStmt(CE->getArg(I-1));
2229 AddStmt(CE->getCallee());
2230 AddStmt(CE->getArg(0));
2232 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2233 const CXXPseudoDestructorExpr *E) {
2234 // Visit the name of the type being destroyed.
2235 AddTypeLoc(E->getDestroyedTypeInfo());
2236 // Visit the scope type that looks disturbingly like the nested-name-specifier
2238 AddTypeLoc(E->getScopeTypeInfo());
2239 // Visit the nested-name-specifier.
2240 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2241 AddNestedNameSpecifierLoc(QualifierLoc);
2242 // Visit base expression.
2243 AddStmt(E->getBase());
2245 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2246 const CXXScalarValueInitExpr *E) {
2247 AddTypeLoc(E->getTypeSourceInfo());
2249 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2250 const CXXTemporaryObjectExpr *E) {
2252 AddTypeLoc(E->getTypeSourceInfo());
2254 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2256 if (E->isTypeOperand())
2257 AddTypeLoc(E->getTypeOperandSourceInfo());
2260 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2261 const CXXUnresolvedConstructExpr *E) {
2263 AddTypeLoc(E->getTypeSourceInfo());
2265 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2267 if (E->isTypeOperand())
2268 AddTypeLoc(E->getTypeOperandSourceInfo());
2271 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2273 AddDecl(S->getExceptionDecl());
2276 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2277 AddStmt(S->getBody());
2278 AddStmt(S->getRangeInit());
2279 AddDecl(S->getLoopVariable());
2282 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2283 if (DR->hasExplicitTemplateArgs()) {
2284 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
2286 WL.push_back(DeclRefExprParts(DR, Parent));
2288 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2289 const DependentScopeDeclRefExpr *E) {
2290 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2291 AddDeclarationNameInfo(E);
2292 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2294 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2295 unsigned size = WL.size();
2296 bool isFirst = true;
2297 for (const auto *D : S->decls()) {
2298 AddDecl(D, isFirst);
2301 if (size == WL.size())
2303 // Now reverse the entries we just added. This will match the DFS
2304 // ordering performed by the worklist.
2305 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2308 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2309 AddStmt(E->getInit());
2310 for (DesignatedInitExpr::const_reverse_designators_iterator
2311 D = E->designators_rbegin(), DEnd = E->designators_rend();
2313 if (D->isFieldDesignator()) {
2314 if (FieldDecl *Field = D->getField())
2315 AddMemberRef(Field, D->getFieldLoc());
2318 if (D->isArrayDesignator()) {
2319 AddStmt(E->getArrayIndex(*D));
2322 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2323 AddStmt(E->getArrayRangeEnd(*D));
2324 AddStmt(E->getArrayRangeStart(*D));
2327 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2329 AddTypeLoc(E->getTypeInfoAsWritten());
2331 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2332 AddStmt(FS->getBody());
2333 AddStmt(FS->getInc());
2334 AddStmt(FS->getCond());
2335 AddDecl(FS->getConditionVariable());
2336 AddStmt(FS->getInit());
2338 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2339 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2341 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2342 AddStmt(If->getElse());
2343 AddStmt(If->getThen());
2344 AddStmt(If->getCond());
2345 AddDecl(If->getConditionVariable());
2347 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2348 // We care about the syntactic form of the initializer list, only.
2349 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2351 EnqueueChildren(IE);
2353 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2354 WL.push_back(MemberExprParts(M, Parent));
2356 // If the base of the member access expression is an implicit 'this', don't
2358 // FIXME: If we ever want to show these implicit accesses, this will be
2359 // unfortunate. However, clang_getCursor() relies on this behavior.
2360 if (M->isImplicitAccess())
2363 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2364 // real field that that we are interested in.
2365 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2366 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2367 if (FD->isAnonymousStructOrUnion()) {
2368 AddStmt(SubME->getBase());
2374 AddStmt(M->getBase());
2376 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2377 AddTypeLoc(E->getEncodedTypeSourceInfo());
2379 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2381 AddTypeLoc(M->getClassReceiverTypeInfo());
2383 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2384 // Visit the components of the offsetof expression.
2385 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2386 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2387 const OffsetOfNode &Node = E->getComponent(I-1);
2388 switch (Node.getKind()) {
2389 case OffsetOfNode::Array:
2390 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2392 case OffsetOfNode::Field:
2393 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2395 case OffsetOfNode::Identifier:
2396 case OffsetOfNode::Base:
2400 // Visit the type into which we're computing the offset.
2401 AddTypeLoc(E->getTypeSourceInfo());
2403 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2404 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2405 WL.push_back(OverloadExprParts(E, Parent));
2407 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2408 const UnaryExprOrTypeTraitExpr *E) {
2410 if (E->isArgumentType())
2411 AddTypeLoc(E->getArgumentTypeInfo());
2413 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2416 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2417 AddStmt(S->getBody());
2418 AddStmt(S->getCond());
2419 AddDecl(S->getConditionVariable());
2422 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2423 AddStmt(W->getBody());
2424 AddStmt(W->getCond());
2425 AddDecl(W->getConditionVariable());
2428 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2429 for (unsigned I = E->getNumArgs(); I > 0; --I)
2430 AddTypeLoc(E->getArg(I-1));
2433 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2434 AddTypeLoc(E->getQueriedTypeSourceInfo());
2437 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2441 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2442 VisitOverloadExpr(U);
2443 if (!U->isImplicitAccess())
2444 AddStmt(U->getBase());
2446 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2447 AddStmt(E->getSubExpr());
2448 AddTypeLoc(E->getWrittenTypeInfo());
2450 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2451 WL.push_back(SizeOfPackExprParts(E, Parent));
2453 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2454 // If the opaque value has a source expression, just transparently
2455 // visit that. This is useful for (e.g.) pseudo-object expressions.
2456 if (Expr *SourceExpr = E->getSourceExpr())
2457 return Visit(SourceExpr);
2459 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2460 AddStmt(E->getBody());
2461 WL.push_back(LambdaExprParts(E, Parent));
2463 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2464 // Treat the expression like its syntactic form.
2465 Visit(E->getSyntacticForm());
2468 void EnqueueVisitor::VisitOMPExecutableDirective(
2469 const OMPExecutableDirective *D) {
2471 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2472 E = D->clauses().end();
2474 EnqueueChildren(*I);
2477 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2478 VisitOMPExecutableDirective(D);
2481 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2482 VisitOMPExecutableDirective(D);
2485 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2486 VisitOMPLoopDirective(D);
2489 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2490 VisitOMPLoopDirective(D);
2493 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2494 VisitOMPLoopDirective(D);
2497 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2498 VisitOMPExecutableDirective(D);
2501 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2502 VisitOMPExecutableDirective(D);
2505 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2506 VisitOMPExecutableDirective(D);
2509 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2510 VisitOMPExecutableDirective(D);
2513 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2514 VisitOMPExecutableDirective(D);
2515 AddDeclarationNameInfo(D);
2519 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2520 VisitOMPLoopDirective(D);
2523 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2524 const OMPParallelForSimdDirective *D) {
2525 VisitOMPLoopDirective(D);
2528 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2529 const OMPParallelSectionsDirective *D) {
2530 VisitOMPExecutableDirective(D);
2533 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2534 VisitOMPExecutableDirective(D);
2538 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2539 VisitOMPExecutableDirective(D);
2542 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2543 VisitOMPExecutableDirective(D);
2546 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2547 VisitOMPExecutableDirective(D);
2550 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2551 const OMPTaskgroupDirective *D) {
2552 VisitOMPExecutableDirective(D);
2555 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2556 VisitOMPExecutableDirective(D);
2559 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2560 VisitOMPExecutableDirective(D);
2563 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2564 VisitOMPExecutableDirective(D);
2567 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2568 VisitOMPExecutableDirective(D);
2571 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2572 OMPTargetDataDirective *D) {
2573 VisitOMPExecutableDirective(D);
2576 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2577 VisitOMPExecutableDirective(D);
2580 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2581 const OMPCancellationPointDirective *D) {
2582 VisitOMPExecutableDirective(D);
2585 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2586 VisitOMPExecutableDirective(D);
2589 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2590 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2593 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2594 if (RegionOfInterest.isValid()) {
2595 SourceRange Range = getRawCursorExtent(C);
2596 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2602 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2603 while (!WL.empty()) {
2604 // Dequeue the worklist item.
2605 VisitorJob LI = WL.pop_back_val();
2607 // Set the Parent field, then back to its old value once we're done.
2608 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2610 switch (LI.getKind()) {
2611 case VisitorJob::DeclVisitKind: {
2612 const Decl *D = cast<DeclVisit>(&LI)->get();
2616 // For now, perform default visitation for Decls.
2617 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2618 cast<DeclVisit>(&LI)->isFirst())))
2623 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2624 const ASTTemplateArgumentListInfo *ArgList =
2625 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2626 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2627 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2628 Arg != ArgEnd; ++Arg) {
2629 if (VisitTemplateArgumentLoc(*Arg))
2634 case VisitorJob::TypeLocVisitKind: {
2635 // Perform default visitation for TypeLocs.
2636 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2640 case VisitorJob::LabelRefVisitKind: {
2641 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2642 if (LabelStmt *stmt = LS->getStmt()) {
2643 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2651 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2652 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2653 if (VisitNestedNameSpecifierLoc(V->get()))
2658 case VisitorJob::DeclarationNameInfoVisitKind: {
2659 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2664 case VisitorJob::MemberRefVisitKind: {
2665 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2666 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2670 case VisitorJob::StmtVisitKind: {
2671 const Stmt *S = cast<StmtVisit>(&LI)->get();
2675 // Update the current cursor.
2676 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2677 if (!IsInRegionOfInterest(Cursor))
2679 switch (Visitor(Cursor, Parent, ClientData)) {
2680 case CXChildVisit_Break: return true;
2681 case CXChildVisit_Continue: break;
2682 case CXChildVisit_Recurse:
2683 if (PostChildrenVisitor)
2684 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2685 EnqueueWorkList(WL, S);
2690 case VisitorJob::MemberExprPartsKind: {
2691 // Handle the other pieces in the MemberExpr besides the base.
2692 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2694 // Visit the nested-name-specifier
2695 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2696 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2699 // Visit the declaration name.
2700 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2703 // Visit the explicitly-specified template arguments, if any.
2704 if (M->hasExplicitTemplateArgs()) {
2705 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2706 *ArgEnd = Arg + M->getNumTemplateArgs();
2707 Arg != ArgEnd; ++Arg) {
2708 if (VisitTemplateArgumentLoc(*Arg))
2714 case VisitorJob::DeclRefExprPartsKind: {
2715 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2716 // Visit nested-name-specifier, if present.
2717 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2718 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2720 // Visit declaration name.
2721 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2725 case VisitorJob::OverloadExprPartsKind: {
2726 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2727 // Visit the nested-name-specifier.
2728 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2729 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2731 // Visit the declaration name.
2732 if (VisitDeclarationNameInfo(O->getNameInfo()))
2734 // Visit the overloaded declaration reference.
2735 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2739 case VisitorJob::SizeOfPackExprPartsKind: {
2740 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2741 NamedDecl *Pack = E->getPack();
2742 if (isa<TemplateTypeParmDecl>(Pack)) {
2743 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2744 E->getPackLoc(), TU)))
2750 if (isa<TemplateTemplateParmDecl>(Pack)) {
2751 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2752 E->getPackLoc(), TU)))
2758 // Non-type template parameter packs and function parameter packs are
2759 // treated like DeclRefExpr cursors.
2763 case VisitorJob::LambdaExprPartsKind: {
2765 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2766 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2767 CEnd = E->explicit_capture_end();
2769 // FIXME: Lambda init-captures.
2770 if (!C->capturesVariable())
2773 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2779 // Visit parameters and return type, if present.
2780 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2781 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2782 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2783 // Visit the whole type.
2786 } else if (FunctionProtoTypeLoc Proto =
2787 TL.getAs<FunctionProtoTypeLoc>()) {
2788 if (E->hasExplicitParameters()) {
2789 // Visit parameters.
2790 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2791 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2794 // Visit result type.
2795 if (Visit(Proto.getReturnLoc()))
2803 case VisitorJob::PostChildrenVisitKind:
2804 if (PostChildrenVisitor(Parent, ClientData))
2812 bool CursorVisitor::Visit(const Stmt *S) {
2813 VisitorWorkList *WL = nullptr;
2814 if (!WorkListFreeList.empty()) {
2815 WL = WorkListFreeList.back();
2817 WorkListFreeList.pop_back();
2820 WL = new VisitorWorkList();
2821 WorkListCache.push_back(WL);
2823 EnqueueWorkList(*WL, S);
2824 bool result = RunVisitorWorkList(*WL);
2825 WorkListFreeList.push_back(WL);
2830 typedef SmallVector<SourceRange, 4> RefNamePieces;
2832 buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2833 const DeclarationNameInfo &NI, SourceRange QLoc,
2834 const ASTTemplateArgumentListInfo *TemplateArgs = nullptr) {
2835 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2836 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2837 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2839 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2841 RefNamePieces Pieces;
2843 if (WantQualifier && QLoc.isValid())
2844 Pieces.push_back(QLoc);
2846 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2847 Pieces.push_back(NI.getLoc());
2849 if (WantTemplateArgs && TemplateArgs)
2850 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2851 TemplateArgs->RAngleLoc));
2853 if (Kind == DeclarationName::CXXOperatorName) {
2854 Pieces.push_back(SourceLocation::getFromRawEncoding(
2855 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2856 Pieces.push_back(SourceLocation::getFromRawEncoding(
2857 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2860 if (WantSinglePiece) {
2861 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2863 Pieces.push_back(R);
2870 //===----------------------------------------------------------------------===//
2872 //===----------------------------------------------------------------------===//
2874 static void fatal_error_handler(void *user_data, const std::string& reason,
2875 bool gen_crash_diag) {
2876 // Write the result out to stderr avoiding errs() because raw_ostreams can
2877 // call report_fatal_error.
2878 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2883 struct RegisterFatalErrorHandler {
2884 RegisterFatalErrorHandler() {
2885 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
2890 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
2893 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2894 int displayDiagnostics) {
2895 // We use crash recovery to make some of our APIs more reliable, implicitly
2897 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
2898 llvm::CrashRecoveryContext::Enable();
2900 // Look through the managed static to trigger construction of the managed
2901 // static which registers our fatal error handler. This ensures it is only
2903 (void)*RegisterFatalErrorHandlerOnce;
2905 // Initialize targets for clang module support.
2906 llvm::InitializeAllTargets();
2907 llvm::InitializeAllTargetMCs();
2908 llvm::InitializeAllAsmPrinters();
2909 llvm::InitializeAllAsmParsers();
2911 CIndexer *CIdxr = new CIndexer();
2913 if (excludeDeclarationsFromPCH)
2914 CIdxr->setOnlyLocalDecls();
2915 if (displayDiagnostics)
2916 CIdxr->setDisplayDiagnostics();
2918 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2919 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2920 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2921 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2922 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2923 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2928 void clang_disposeIndex(CXIndex CIdx) {
2930 delete static_cast<CIndexer *>(CIdx);
2933 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2935 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2938 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2940 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2944 void clang_toggleCrashRecovery(unsigned isEnabled) {
2946 llvm::CrashRecoveryContext::Enable();
2948 llvm::CrashRecoveryContext::Disable();
2951 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2952 const char *ast_filename) {
2953 CXTranslationUnit TU;
2954 enum CXErrorCode Result =
2955 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
2957 assert((TU && Result == CXError_Success) ||
2958 (!TU && Result != CXError_Success));
2962 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
2963 const char *ast_filename,
2964 CXTranslationUnit *out_TU) {
2968 if (!CIdx || !ast_filename || !out_TU)
2969 return CXError_InvalidArguments;
2972 *Log << ast_filename;
2975 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2976 FileSystemOptions FileSystemOpts;
2978 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
2979 CompilerInstance::createDiagnostics(new DiagnosticOptions());
2980 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
2981 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
2982 FileSystemOpts, /*UseDebugInfo=*/false,
2983 CXXIdx->getOnlyLocalDecls(), None,
2984 /*CaptureDiagnostics=*/true,
2985 /*AllowPCHWithCompilerErrors=*/true,
2986 /*UserFilesAreVolatile=*/true);
2987 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
2988 return *out_TU ? CXError_Success : CXError_Failure;
2991 unsigned clang_defaultEditingTranslationUnitOptions() {
2992 return CXTranslationUnit_PrecompiledPreamble |
2993 CXTranslationUnit_CacheCompletionResults;
2997 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2998 const char *source_filename,
2999 int num_command_line_args,
3000 const char * const *command_line_args,
3001 unsigned num_unsaved_files,
3002 struct CXUnsavedFile *unsaved_files) {
3003 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3004 return clang_parseTranslationUnit(CIdx, source_filename,
3005 command_line_args, num_command_line_args,
3006 unsaved_files, num_unsaved_files,
3011 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3012 const char *const *command_line_args,
3013 int num_command_line_args,
3014 ArrayRef<CXUnsavedFile> unsaved_files,
3015 unsigned options, CXTranslationUnit *out_TU) {
3016 // Set up the initial return values.
3021 if (!CIdx || !out_TU)
3022 return CXError_InvalidArguments;
3024 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3026 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3027 setThreadBackgroundPriority();
3029 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3030 // FIXME: Add a flag for modules.
3031 TranslationUnitKind TUKind
3032 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3033 bool CacheCodeCompletionResults
3034 = options & CXTranslationUnit_CacheCompletionResults;
3035 bool IncludeBriefCommentsInCodeCompletion
3036 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3037 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3038 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3040 // Configure the diagnostics.
3041 IntrusiveRefCntPtr<DiagnosticsEngine>
3042 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3044 // Recover resources if we crash before exiting this function.
3045 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3046 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3047 DiagCleanup(Diags.get());
3049 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3050 new std::vector<ASTUnit::RemappedFile>());
3052 // Recover resources if we crash before exiting this function.
3053 llvm::CrashRecoveryContextCleanupRegistrar<
3054 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3056 for (auto &UF : unsaved_files) {
3057 std::unique_ptr<llvm::MemoryBuffer> MB =
3058 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3059 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3062 std::unique_ptr<std::vector<const char *>> Args(
3063 new std::vector<const char *>());
3065 // Recover resources if we crash before exiting this method.
3066 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3067 ArgsCleanup(Args.get());
3069 // Since the Clang C library is primarily used by batch tools dealing with
3070 // (often very broken) source code, where spell-checking can have a
3071 // significant negative impact on performance (particularly when
3072 // precompiled headers are involved), we disable it by default.
3073 // Only do this if we haven't found a spell-checking-related argument.
3074 bool FoundSpellCheckingArgument = false;
3075 for (int I = 0; I != num_command_line_args; ++I) {
3076 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3077 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3078 FoundSpellCheckingArgument = true;
3082 if (!FoundSpellCheckingArgument)
3083 Args->push_back("-fno-spell-checking");
3085 Args->insert(Args->end(), command_line_args,
3086 command_line_args + num_command_line_args);
3088 // The 'source_filename' argument is optional. If the caller does not
3089 // specify it then it is assumed that the source file is specified
3090 // in the actual argument list.
3091 // Put the source file after command_line_args otherwise if '-x' flag is
3092 // present it will be unused.
3093 if (source_filename)
3094 Args->push_back(source_filename);
3096 // Do we need the detailed preprocessing record?
3097 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3098 Args->push_back("-Xclang");
3099 Args->push_back("-detailed-preprocessing-record");
3102 unsigned NumErrors = Diags->getClient()->getNumErrors();
3103 std::unique_ptr<ASTUnit> ErrUnit;
3104 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3105 Args->data(), Args->data() + Args->size(),
3106 CXXIdx->getPCHContainerOperations(), Diags,
3107 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3108 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3109 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreamble, TUKind,
3110 CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3111 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3112 /*UserFilesAreVolatile=*/true, ForSerialization, &ErrUnit));
3114 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3115 if (!Unit && !ErrUnit)
3116 return CXError_ASTReadError;
3118 if (NumErrors != Diags->getClient()->getNumErrors()) {
3119 // Make sure to check that 'Unit' is non-NULL.
3120 if (CXXIdx->getDisplayDiagnostics())
3121 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3124 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3125 return CXError_ASTReadError;
3127 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3128 return *out_TU ? CXError_Success : CXError_Failure;
3132 clang_parseTranslationUnit(CXIndex CIdx,
3133 const char *source_filename,
3134 const char *const *command_line_args,
3135 int num_command_line_args,
3136 struct CXUnsavedFile *unsaved_files,
3137 unsigned num_unsaved_files,
3139 CXTranslationUnit TU;
3140 enum CXErrorCode Result = clang_parseTranslationUnit2(
3141 CIdx, source_filename, command_line_args, num_command_line_args,
3142 unsaved_files, num_unsaved_files, options, &TU);
3144 assert((TU && Result == CXError_Success) ||
3145 (!TU && Result != CXError_Success));
3149 enum CXErrorCode clang_parseTranslationUnit2(
3151 const char *source_filename,
3152 const char *const *command_line_args,
3153 int num_command_line_args,
3154 struct CXUnsavedFile *unsaved_files,
3155 unsigned num_unsaved_files,
3157 CXTranslationUnit *out_TU) {
3159 *Log << source_filename << ": ";
3160 for (int i = 0; i != num_command_line_args; ++i)
3161 *Log << command_line_args[i] << " ";
3164 if (num_unsaved_files && !unsaved_files)
3165 return CXError_InvalidArguments;
3167 CXErrorCode result = CXError_Failure;
3168 auto ParseTranslationUnitImpl = [=, &result] {
3169 result = clang_parseTranslationUnit_Impl(
3170 CIdx, source_filename, command_line_args, num_command_line_args,
3171 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3173 llvm::CrashRecoveryContext CRC;
3175 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3176 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3177 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3178 fprintf(stderr, " 'command_line_args' : [");
3179 for (int i = 0; i != num_command_line_args; ++i) {
3181 fprintf(stderr, ", ");
3182 fprintf(stderr, "'%s'", command_line_args[i]);
3184 fprintf(stderr, "],\n");
3185 fprintf(stderr, " 'unsaved_files' : [");
3186 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3188 fprintf(stderr, ", ");
3189 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3190 unsaved_files[i].Length);
3192 fprintf(stderr, "],\n");
3193 fprintf(stderr, " 'options' : %d,\n", options);
3194 fprintf(stderr, "}\n");
3196 return CXError_Crashed;
3197 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3198 if (CXTranslationUnit *TU = out_TU)
3199 PrintLibclangResourceUsage(*TU);
3205 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3206 return CXSaveTranslationUnit_None;
3209 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3210 const char *FileName,
3212 CIndexer *CXXIdx = TU->CIdx;
3213 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3214 setThreadBackgroundPriority();
3216 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3217 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3220 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3223 *Log << TU << ' ' << FileName;
3226 if (isNotUsableTU(TU)) {
3228 return CXSaveError_InvalidTU;
3231 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3232 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3233 if (!CXXUnit->hasSema())
3234 return CXSaveError_InvalidTU;
3237 auto SaveTranslationUnitImpl = [=, &result]() {
3238 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3241 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3242 getenv("LIBCLANG_NOTHREADS")) {
3243 SaveTranslationUnitImpl();
3245 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3246 PrintLibclangResourceUsage(TU);
3251 // We have an AST that has invalid nodes due to compiler errors.
3252 // Use a crash recovery thread for protection.
3254 llvm::CrashRecoveryContext CRC;
3256 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3257 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3258 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3259 fprintf(stderr, " 'options' : %d,\n", options);
3260 fprintf(stderr, "}\n");
3262 return CXSaveError_Unknown;
3264 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3265 PrintLibclangResourceUsage(TU);
3271 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3273 // If the translation unit has been marked as unsafe to free, just discard
3275 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3276 if (Unit && Unit->isUnsafeToFree())
3279 delete cxtu::getASTUnit(CTUnit);
3280 delete CTUnit->StringPool;
3281 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3282 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3283 delete CTUnit->CommentToXML;
3288 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3289 return CXReparse_None;
3293 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3294 ArrayRef<CXUnsavedFile> unsaved_files,
3297 if (isNotUsableTU(TU)) {
3299 return CXError_InvalidArguments;
3302 // Reset the associated diagnostics.
3303 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3304 TU->Diagnostics = nullptr;
3306 CIndexer *CXXIdx = TU->CIdx;
3307 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3308 setThreadBackgroundPriority();
3310 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3311 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3313 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3314 new std::vector<ASTUnit::RemappedFile>());
3316 // Recover resources if we crash before exiting this function.
3317 llvm::CrashRecoveryContextCleanupRegistrar<
3318 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3320 for (auto &UF : unsaved_files) {
3321 std::unique_ptr<llvm::MemoryBuffer> MB =
3322 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3323 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3326 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3327 *RemappedFiles.get()))
3328 return CXError_Success;
3329 if (isASTReadError(CXXUnit))
3330 return CXError_ASTReadError;
3331 return CXError_Failure;
3334 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3335 unsigned num_unsaved_files,
3336 struct CXUnsavedFile *unsaved_files,
3342 if (num_unsaved_files && !unsaved_files)
3343 return CXError_InvalidArguments;
3346 auto ReparseTranslationUnitImpl = [=, &result]() {
3347 result = clang_reparseTranslationUnit_Impl(
3348 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3351 if (getenv("LIBCLANG_NOTHREADS")) {
3352 ReparseTranslationUnitImpl();
3356 llvm::CrashRecoveryContext CRC;
3358 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3359 fprintf(stderr, "libclang: crash detected during reparsing\n");
3360 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3361 return CXError_Crashed;
3362 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3363 PrintLibclangResourceUsage(TU);
3369 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3370 if (isNotUsableTU(CTUnit)) {
3372 return cxstring::createEmpty();
3375 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3376 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3379 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3380 if (isNotUsableTU(TU)) {
3382 return clang_getNullCursor();
3385 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3386 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3389 } // end: extern "C"
3391 //===----------------------------------------------------------------------===//
3392 // CXFile Operations.
3393 //===----------------------------------------------------------------------===//
3396 CXString clang_getFileName(CXFile SFile) {
3398 return cxstring::createNull();
3400 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3401 return cxstring::createRef(FEnt->getName());
3404 time_t clang_getFileTime(CXFile SFile) {
3408 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3409 return FEnt->getModificationTime();
3412 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3413 if (isNotUsableTU(TU)) {
3418 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3420 FileManager &FMgr = CXXUnit->getFileManager();
3421 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3424 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3426 if (isNotUsableTU(TU)) {
3434 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3435 FileEntry *FEnt = static_cast<FileEntry *>(file);
3436 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3437 .isFileMultipleIncludeGuarded(FEnt);
3440 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3441 if (!file || !outID)
3444 FileEntry *FEnt = static_cast<FileEntry *>(file);
3445 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3446 outID->data[0] = ID.getDevice();
3447 outID->data[1] = ID.getFile();
3448 outID->data[2] = FEnt->getModificationTime();
3452 int clang_File_isEqual(CXFile file1, CXFile file2) {
3456 if (!file1 || !file2)
3459 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3460 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3461 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3464 } // end: extern "C"
3466 //===----------------------------------------------------------------------===//
3467 // CXCursor Operations.
3468 //===----------------------------------------------------------------------===//
3470 static const Decl *getDeclFromExpr(const Stmt *E) {
3471 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3472 return getDeclFromExpr(CE->getSubExpr());
3474 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3475 return RefExpr->getDecl();
3476 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3477 return ME->getMemberDecl();
3478 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3479 return RE->getDecl();
3480 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3481 if (PRE->isExplicitProperty())
3482 return PRE->getExplicitProperty();
3483 // It could be messaging both getter and setter as in:
3485 // in which case prefer to associate the setter since it is less obvious
3486 // from inspecting the source that the setter is going to get called.
3487 if (PRE->isMessagingSetter())
3488 return PRE->getImplicitPropertySetter();
3489 return PRE->getImplicitPropertyGetter();
3491 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3492 return getDeclFromExpr(POE->getSyntacticForm());
3493 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3494 if (Expr *Src = OVE->getSourceExpr())
3495 return getDeclFromExpr(Src);
3497 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3498 return getDeclFromExpr(CE->getCallee());
3499 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3500 if (!CE->isElidable())
3501 return CE->getConstructor();
3502 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3503 return OME->getMethodDecl();
3505 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3506 return PE->getProtocol();
3507 if (const SubstNonTypeTemplateParmPackExpr *NTTP
3508 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3509 return NTTP->getParameterPack();
3510 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3511 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3512 isa<ParmVarDecl>(SizeOfPack->getPack()))
3513 return SizeOfPack->getPack();
3518 static SourceLocation getLocationFromExpr(const Expr *E) {
3519 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3520 return getLocationFromExpr(CE->getSubExpr());
3522 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3523 return /*FIXME:*/Msg->getLeftLoc();
3524 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3525 return DRE->getLocation();
3526 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3527 return Member->getMemberLoc();
3528 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3529 return Ivar->getLocation();
3530 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3531 return SizeOfPack->getPackLoc();
3532 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3533 return PropRef->getLocation();
3535 return E->getLocStart();
3540 unsigned clang_visitChildren(CXCursor parent,
3541 CXCursorVisitor visitor,
3542 CXClientData client_data) {
3543 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3544 /*VisitPreprocessorLast=*/false);
3545 return CursorVis.VisitChildren(parent);
3548 #ifndef __has_feature
3549 #define __has_feature(x) 0
3551 #if __has_feature(blocks)
3552 typedef enum CXChildVisitResult
3553 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3555 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3556 CXClientData client_data) {
3557 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3558 return block(cursor, parent);
3561 // If we are compiled with a compiler that doesn't have native blocks support,
3562 // define and call the block manually, so the
3563 typedef struct _CXChildVisitResult
3568 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3570 } *CXCursorVisitorBlock;
3572 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3573 CXClientData client_data) {
3574 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3575 return block->invoke(block, cursor, parent);
3580 unsigned clang_visitChildrenWithBlock(CXCursor parent,
3581 CXCursorVisitorBlock block) {
3582 return clang_visitChildren(parent, visitWithBlock, block);
3585 static CXString getDeclSpelling(const Decl *D) {
3587 return cxstring::createEmpty();
3589 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3591 if (const ObjCPropertyImplDecl *PropImpl =
3592 dyn_cast<ObjCPropertyImplDecl>(D))
3593 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3594 return cxstring::createDup(Property->getIdentifier()->getName());
3596 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3597 if (Module *Mod = ImportD->getImportedModule())
3598 return cxstring::createDup(Mod->getFullModuleName());
3600 return cxstring::createEmpty();
3603 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3604 return cxstring::createDup(OMD->getSelector().getAsString());
3606 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3607 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3608 // and returns different names. NamedDecl returns the class name and
3609 // ObjCCategoryImplDecl returns the category name.
3610 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
3612 if (isa<UsingDirectiveDecl>(D))
3613 return cxstring::createEmpty();
3615 SmallString<1024> S;
3616 llvm::raw_svector_ostream os(S);
3619 return cxstring::createDup(os.str());
3622 CXString clang_getCursorSpelling(CXCursor C) {
3623 if (clang_isTranslationUnit(C.kind))
3624 return clang_getTranslationUnitSpelling(getCursorTU(C));
3626 if (clang_isReference(C.kind)) {
3628 case CXCursor_ObjCSuperClassRef: {
3629 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3630 return cxstring::createRef(Super->getIdentifier()->getNameStart());
3632 case CXCursor_ObjCClassRef: {
3633 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3634 return cxstring::createRef(Class->getIdentifier()->getNameStart());
3636 case CXCursor_ObjCProtocolRef: {
3637 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3638 assert(OID && "getCursorSpelling(): Missing protocol decl");
3639 return cxstring::createRef(OID->getIdentifier()->getNameStart());
3641 case CXCursor_CXXBaseSpecifier: {
3642 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3643 return cxstring::createDup(B->getType().getAsString());
3645 case CXCursor_TypeRef: {
3646 const TypeDecl *Type = getCursorTypeRef(C).first;
3647 assert(Type && "Missing type decl");
3649 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
3652 case CXCursor_TemplateRef: {
3653 const TemplateDecl *Template = getCursorTemplateRef(C).first;
3654 assert(Template && "Missing template decl");
3656 return cxstring::createDup(Template->getNameAsString());
3659 case CXCursor_NamespaceRef: {
3660 const NamedDecl *NS = getCursorNamespaceRef(C).first;
3661 assert(NS && "Missing namespace decl");
3663 return cxstring::createDup(NS->getNameAsString());
3666 case CXCursor_MemberRef: {
3667 const FieldDecl *Field = getCursorMemberRef(C).first;
3668 assert(Field && "Missing member decl");
3670 return cxstring::createDup(Field->getNameAsString());
3673 case CXCursor_LabelRef: {
3674 const LabelStmt *Label = getCursorLabelRef(C).first;
3675 assert(Label && "Missing label");
3677 return cxstring::createRef(Label->getName());
3680 case CXCursor_OverloadedDeclRef: {
3681 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3682 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3683 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3684 return cxstring::createDup(ND->getNameAsString());
3685 return cxstring::createEmpty();
3687 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3688 return cxstring::createDup(E->getName().getAsString());
3689 OverloadedTemplateStorage *Ovl
3690 = Storage.get<OverloadedTemplateStorage*>();
3691 if (Ovl->size() == 0)
3692 return cxstring::createEmpty();
3693 return cxstring::createDup((*Ovl->begin())->getNameAsString());
3696 case CXCursor_VariableRef: {
3697 const VarDecl *Var = getCursorVariableRef(C).first;
3698 assert(Var && "Missing variable decl");
3700 return cxstring::createDup(Var->getNameAsString());
3704 return cxstring::createRef("<not implemented>");
3708 if (clang_isExpression(C.kind)) {
3709 const Expr *E = getCursorExpr(C);
3711 if (C.kind == CXCursor_ObjCStringLiteral ||
3712 C.kind == CXCursor_StringLiteral) {
3713 const StringLiteral *SLit;
3714 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
3715 SLit = OSL->getString();
3717 SLit = cast<StringLiteral>(E);
3719 SmallString<256> Buf;
3720 llvm::raw_svector_ostream OS(Buf);
3721 SLit->outputString(OS);
3722 return cxstring::createDup(OS.str());
3725 const Decl *D = getDeclFromExpr(getCursorExpr(C));
3727 return getDeclSpelling(D);
3728 return cxstring::createEmpty();
3731 if (clang_isStatement(C.kind)) {
3732 const Stmt *S = getCursorStmt(C);
3733 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3734 return cxstring::createRef(Label->getName());
3736 return cxstring::createEmpty();
3739 if (C.kind == CXCursor_MacroExpansion)
3740 return cxstring::createRef(getCursorMacroExpansion(C).getName()
3743 if (C.kind == CXCursor_MacroDefinition)
3744 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
3747 if (C.kind == CXCursor_InclusionDirective)
3748 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
3750 if (clang_isDeclaration(C.kind))
3751 return getDeclSpelling(getCursorDecl(C));
3753 if (C.kind == CXCursor_AnnotateAttr) {
3754 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3755 return cxstring::createDup(AA->getAnnotation());
3758 if (C.kind == CXCursor_AsmLabelAttr) {
3759 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3760 return cxstring::createDup(AA->getLabel());
3763 if (C.kind == CXCursor_PackedAttr) {
3764 return cxstring::createRef("packed");
3767 if (C.kind == CXCursor_VisibilityAttr) {
3768 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
3769 switch (AA->getVisibility()) {
3770 case VisibilityAttr::VisibilityType::Default:
3771 return cxstring::createRef("default");
3772 case VisibilityAttr::VisibilityType::Hidden:
3773 return cxstring::createRef("hidden");
3774 case VisibilityAttr::VisibilityType::Protected:
3775 return cxstring::createRef("protected");
3777 llvm_unreachable("unknown visibility type");
3780 return cxstring::createEmpty();
3783 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3784 unsigned pieceIndex,
3786 if (clang_Cursor_isNull(C))
3787 return clang_getNullRange();
3789 ASTContext &Ctx = getCursorContext(C);
3791 if (clang_isStatement(C.kind)) {
3792 const Stmt *S = getCursorStmt(C);
3793 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3795 return clang_getNullRange();
3796 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3799 return clang_getNullRange();
3802 if (C.kind == CXCursor_ObjCMessageExpr) {
3803 if (const ObjCMessageExpr *
3804 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3805 if (pieceIndex >= ME->getNumSelectorLocs())
3806 return clang_getNullRange();
3807 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3811 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3812 C.kind == CXCursor_ObjCClassMethodDecl) {
3813 if (const ObjCMethodDecl *
3814 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3815 if (pieceIndex >= MD->getNumSelectorLocs())
3816 return clang_getNullRange();
3817 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3821 if (C.kind == CXCursor_ObjCCategoryDecl ||
3822 C.kind == CXCursor_ObjCCategoryImplDecl) {
3824 return clang_getNullRange();
3825 if (const ObjCCategoryDecl *
3826 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3827 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3828 if (const ObjCCategoryImplDecl *
3829 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3830 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3833 if (C.kind == CXCursor_ModuleImportDecl) {
3835 return clang_getNullRange();
3836 if (const ImportDecl *ImportD =
3837 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3838 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3840 return cxloc::translateSourceRange(Ctx,
3841 SourceRange(Locs.front(), Locs.back()));
3843 return clang_getNullRange();
3846 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
3847 C.kind == CXCursor_ConversionFunction) {
3849 return clang_getNullRange();
3850 if (const FunctionDecl *FD =
3851 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
3852 DeclarationNameInfo FunctionName = FD->getNameInfo();
3853 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
3855 return clang_getNullRange();
3858 // FIXME: A CXCursor_InclusionDirective should give the location of the
3859 // filename, but we don't keep track of this.
3861 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3862 // but we don't keep track of this.
3864 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3865 // but we don't keep track of this.
3867 // Default handling, give the location of the cursor.
3870 return clang_getNullRange();
3872 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3873 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3874 return cxloc::translateSourceRange(Ctx, Loc);
3877 CXString clang_Cursor_getMangling(CXCursor C) {
3878 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
3879 return cxstring::createEmpty();
3881 // Mangling only works for functions and variables.
3882 const Decl *D = getCursorDecl(C);
3883 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
3884 return cxstring::createEmpty();
3886 // First apply frontend mangling.
3887 const NamedDecl *ND = cast<NamedDecl>(D);
3888 ASTContext &Ctx = ND->getASTContext();
3889 std::unique_ptr<MangleContext> MC(Ctx.createMangleContext());
3891 std::string FrontendBuf;
3892 llvm::raw_string_ostream FrontendBufOS(FrontendBuf);
3893 if (MC->shouldMangleDeclName(ND)) {
3894 MC->mangleName(ND, FrontendBufOS);
3896 ND->printName(FrontendBufOS);
3899 // Now apply backend mangling.
3900 std::unique_ptr<llvm::DataLayout> DL(
3901 new llvm::DataLayout(Ctx.getTargetInfo().getDataLayoutString()));
3903 std::string FinalBuf;
3904 llvm::raw_string_ostream FinalBufOS(FinalBuf);
3905 llvm::Mangler::getNameWithPrefix(FinalBufOS, llvm::Twine(FrontendBufOS.str()),
3908 return cxstring::createDup(FinalBufOS.str());
3911 CXString clang_getCursorDisplayName(CXCursor C) {
3912 if (!clang_isDeclaration(C.kind))
3913 return clang_getCursorSpelling(C);
3915 const Decl *D = getCursorDecl(C);
3917 return cxstring::createEmpty();
3919 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3920 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3921 D = FunTmpl->getTemplatedDecl();
3923 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3924 SmallString<64> Str;
3925 llvm::raw_svector_ostream OS(Str);
3927 if (Function->getPrimaryTemplate())
3930 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3933 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3936 if (Function->isVariadic()) {
3937 if (Function->getNumParams())
3942 return cxstring::createDup(OS.str());
3945 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3946 SmallString<64> Str;
3947 llvm::raw_svector_ostream OS(Str);
3948 OS << *ClassTemplate;
3950 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3951 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3955 NamedDecl *Param = Params->getParam(I);
3956 if (Param->getIdentifier()) {
3957 OS << Param->getIdentifier()->getName();
3961 // There is no parameter name, which makes this tricky. Try to come up
3962 // with something useful that isn't too long.
3963 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3964 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3965 else if (NonTypeTemplateParmDecl *NTTP
3966 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3967 OS << NTTP->getType().getAsString(Policy);
3969 OS << "template<...> class";
3973 return cxstring::createDup(OS.str());
3976 if (const ClassTemplateSpecializationDecl *ClassSpec
3977 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3978 // If the type was explicitly written, use that.
3979 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3980 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
3982 SmallString<128> Str;
3983 llvm::raw_svector_ostream OS(Str);
3985 TemplateSpecializationType::PrintTemplateArgumentList(OS,
3986 ClassSpec->getTemplateArgs().data(),
3987 ClassSpec->getTemplateArgs().size(),
3989 return cxstring::createDup(OS.str());
3992 return clang_getCursorSpelling(C);
3995 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3997 case CXCursor_FunctionDecl:
3998 return cxstring::createRef("FunctionDecl");
3999 case CXCursor_TypedefDecl:
4000 return cxstring::createRef("TypedefDecl");
4001 case CXCursor_EnumDecl:
4002 return cxstring::createRef("EnumDecl");
4003 case CXCursor_EnumConstantDecl:
4004 return cxstring::createRef("EnumConstantDecl");
4005 case CXCursor_StructDecl:
4006 return cxstring::createRef("StructDecl");
4007 case CXCursor_UnionDecl:
4008 return cxstring::createRef("UnionDecl");
4009 case CXCursor_ClassDecl:
4010 return cxstring::createRef("ClassDecl");
4011 case CXCursor_FieldDecl:
4012 return cxstring::createRef("FieldDecl");
4013 case CXCursor_VarDecl:
4014 return cxstring::createRef("VarDecl");
4015 case CXCursor_ParmDecl:
4016 return cxstring::createRef("ParmDecl");
4017 case CXCursor_ObjCInterfaceDecl:
4018 return cxstring::createRef("ObjCInterfaceDecl");
4019 case CXCursor_ObjCCategoryDecl:
4020 return cxstring::createRef("ObjCCategoryDecl");
4021 case CXCursor_ObjCProtocolDecl:
4022 return cxstring::createRef("ObjCProtocolDecl");
4023 case CXCursor_ObjCPropertyDecl:
4024 return cxstring::createRef("ObjCPropertyDecl");
4025 case CXCursor_ObjCIvarDecl:
4026 return cxstring::createRef("ObjCIvarDecl");
4027 case CXCursor_ObjCInstanceMethodDecl:
4028 return cxstring::createRef("ObjCInstanceMethodDecl");
4029 case CXCursor_ObjCClassMethodDecl:
4030 return cxstring::createRef("ObjCClassMethodDecl");
4031 case CXCursor_ObjCImplementationDecl:
4032 return cxstring::createRef("ObjCImplementationDecl");
4033 case CXCursor_ObjCCategoryImplDecl:
4034 return cxstring::createRef("ObjCCategoryImplDecl");
4035 case CXCursor_CXXMethod:
4036 return cxstring::createRef("CXXMethod");
4037 case CXCursor_UnexposedDecl:
4038 return cxstring::createRef("UnexposedDecl");
4039 case CXCursor_ObjCSuperClassRef:
4040 return cxstring::createRef("ObjCSuperClassRef");
4041 case CXCursor_ObjCProtocolRef:
4042 return cxstring::createRef("ObjCProtocolRef");
4043 case CXCursor_ObjCClassRef:
4044 return cxstring::createRef("ObjCClassRef");
4045 case CXCursor_TypeRef:
4046 return cxstring::createRef("TypeRef");
4047 case CXCursor_TemplateRef:
4048 return cxstring::createRef("TemplateRef");
4049 case CXCursor_NamespaceRef:
4050 return cxstring::createRef("NamespaceRef");
4051 case CXCursor_MemberRef:
4052 return cxstring::createRef("MemberRef");
4053 case CXCursor_LabelRef:
4054 return cxstring::createRef("LabelRef");
4055 case CXCursor_OverloadedDeclRef:
4056 return cxstring::createRef("OverloadedDeclRef");
4057 case CXCursor_VariableRef:
4058 return cxstring::createRef("VariableRef");
4059 case CXCursor_IntegerLiteral:
4060 return cxstring::createRef("IntegerLiteral");
4061 case CXCursor_FloatingLiteral:
4062 return cxstring::createRef("FloatingLiteral");
4063 case CXCursor_ImaginaryLiteral:
4064 return cxstring::createRef("ImaginaryLiteral");
4065 case CXCursor_StringLiteral:
4066 return cxstring::createRef("StringLiteral");
4067 case CXCursor_CharacterLiteral:
4068 return cxstring::createRef("CharacterLiteral");
4069 case CXCursor_ParenExpr:
4070 return cxstring::createRef("ParenExpr");
4071 case CXCursor_UnaryOperator:
4072 return cxstring::createRef("UnaryOperator");
4073 case CXCursor_ArraySubscriptExpr:
4074 return cxstring::createRef("ArraySubscriptExpr");
4075 case CXCursor_OMPArraySectionExpr:
4076 return cxstring::createRef("OMPArraySectionExpr");
4077 case CXCursor_BinaryOperator:
4078 return cxstring::createRef("BinaryOperator");
4079 case CXCursor_CompoundAssignOperator:
4080 return cxstring::createRef("CompoundAssignOperator");
4081 case CXCursor_ConditionalOperator:
4082 return cxstring::createRef("ConditionalOperator");
4083 case CXCursor_CStyleCastExpr:
4084 return cxstring::createRef("CStyleCastExpr");
4085 case CXCursor_CompoundLiteralExpr:
4086 return cxstring::createRef("CompoundLiteralExpr");
4087 case CXCursor_InitListExpr:
4088 return cxstring::createRef("InitListExpr");
4089 case CXCursor_AddrLabelExpr:
4090 return cxstring::createRef("AddrLabelExpr");
4091 case CXCursor_StmtExpr:
4092 return cxstring::createRef("StmtExpr");
4093 case CXCursor_GenericSelectionExpr:
4094 return cxstring::createRef("GenericSelectionExpr");
4095 case CXCursor_GNUNullExpr:
4096 return cxstring::createRef("GNUNullExpr");
4097 case CXCursor_CXXStaticCastExpr:
4098 return cxstring::createRef("CXXStaticCastExpr");
4099 case CXCursor_CXXDynamicCastExpr:
4100 return cxstring::createRef("CXXDynamicCastExpr");
4101 case CXCursor_CXXReinterpretCastExpr:
4102 return cxstring::createRef("CXXReinterpretCastExpr");
4103 case CXCursor_CXXConstCastExpr:
4104 return cxstring::createRef("CXXConstCastExpr");
4105 case CXCursor_CXXFunctionalCastExpr:
4106 return cxstring::createRef("CXXFunctionalCastExpr");
4107 case CXCursor_CXXTypeidExpr:
4108 return cxstring::createRef("CXXTypeidExpr");
4109 case CXCursor_CXXBoolLiteralExpr:
4110 return cxstring::createRef("CXXBoolLiteralExpr");
4111 case CXCursor_CXXNullPtrLiteralExpr:
4112 return cxstring::createRef("CXXNullPtrLiteralExpr");
4113 case CXCursor_CXXThisExpr:
4114 return cxstring::createRef("CXXThisExpr");
4115 case CXCursor_CXXThrowExpr:
4116 return cxstring::createRef("CXXThrowExpr");
4117 case CXCursor_CXXNewExpr:
4118 return cxstring::createRef("CXXNewExpr");
4119 case CXCursor_CXXDeleteExpr:
4120 return cxstring::createRef("CXXDeleteExpr");
4121 case CXCursor_UnaryExpr:
4122 return cxstring::createRef("UnaryExpr");
4123 case CXCursor_ObjCStringLiteral:
4124 return cxstring::createRef("ObjCStringLiteral");
4125 case CXCursor_ObjCBoolLiteralExpr:
4126 return cxstring::createRef("ObjCBoolLiteralExpr");
4127 case CXCursor_ObjCSelfExpr:
4128 return cxstring::createRef("ObjCSelfExpr");
4129 case CXCursor_ObjCEncodeExpr:
4130 return cxstring::createRef("ObjCEncodeExpr");
4131 case CXCursor_ObjCSelectorExpr:
4132 return cxstring::createRef("ObjCSelectorExpr");
4133 case CXCursor_ObjCProtocolExpr:
4134 return cxstring::createRef("ObjCProtocolExpr");
4135 case CXCursor_ObjCBridgedCastExpr:
4136 return cxstring::createRef("ObjCBridgedCastExpr");
4137 case CXCursor_BlockExpr:
4138 return cxstring::createRef("BlockExpr");
4139 case CXCursor_PackExpansionExpr:
4140 return cxstring::createRef("PackExpansionExpr");
4141 case CXCursor_SizeOfPackExpr:
4142 return cxstring::createRef("SizeOfPackExpr");
4143 case CXCursor_LambdaExpr:
4144 return cxstring::createRef("LambdaExpr");
4145 case CXCursor_UnexposedExpr:
4146 return cxstring::createRef("UnexposedExpr");
4147 case CXCursor_DeclRefExpr:
4148 return cxstring::createRef("DeclRefExpr");
4149 case CXCursor_MemberRefExpr:
4150 return cxstring::createRef("MemberRefExpr");
4151 case CXCursor_CallExpr:
4152 return cxstring::createRef("CallExpr");
4153 case CXCursor_ObjCMessageExpr:
4154 return cxstring::createRef("ObjCMessageExpr");
4155 case CXCursor_UnexposedStmt:
4156 return cxstring::createRef("UnexposedStmt");
4157 case CXCursor_DeclStmt:
4158 return cxstring::createRef("DeclStmt");
4159 case CXCursor_LabelStmt:
4160 return cxstring::createRef("LabelStmt");
4161 case CXCursor_CompoundStmt:
4162 return cxstring::createRef("CompoundStmt");
4163 case CXCursor_CaseStmt:
4164 return cxstring::createRef("CaseStmt");
4165 case CXCursor_DefaultStmt:
4166 return cxstring::createRef("DefaultStmt");
4167 case CXCursor_IfStmt:
4168 return cxstring::createRef("IfStmt");
4169 case CXCursor_SwitchStmt:
4170 return cxstring::createRef("SwitchStmt");
4171 case CXCursor_WhileStmt:
4172 return cxstring::createRef("WhileStmt");
4173 case CXCursor_DoStmt:
4174 return cxstring::createRef("DoStmt");
4175 case CXCursor_ForStmt:
4176 return cxstring::createRef("ForStmt");
4177 case CXCursor_GotoStmt:
4178 return cxstring::createRef("GotoStmt");
4179 case CXCursor_IndirectGotoStmt:
4180 return cxstring::createRef("IndirectGotoStmt");
4181 case CXCursor_ContinueStmt:
4182 return cxstring::createRef("ContinueStmt");
4183 case CXCursor_BreakStmt:
4184 return cxstring::createRef("BreakStmt");
4185 case CXCursor_ReturnStmt:
4186 return cxstring::createRef("ReturnStmt");
4187 case CXCursor_GCCAsmStmt:
4188 return cxstring::createRef("GCCAsmStmt");
4189 case CXCursor_MSAsmStmt:
4190 return cxstring::createRef("MSAsmStmt");
4191 case CXCursor_ObjCAtTryStmt:
4192 return cxstring::createRef("ObjCAtTryStmt");
4193 case CXCursor_ObjCAtCatchStmt:
4194 return cxstring::createRef("ObjCAtCatchStmt");
4195 case CXCursor_ObjCAtFinallyStmt:
4196 return cxstring::createRef("ObjCAtFinallyStmt");
4197 case CXCursor_ObjCAtThrowStmt:
4198 return cxstring::createRef("ObjCAtThrowStmt");
4199 case CXCursor_ObjCAtSynchronizedStmt:
4200 return cxstring::createRef("ObjCAtSynchronizedStmt");
4201 case CXCursor_ObjCAutoreleasePoolStmt:
4202 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4203 case CXCursor_ObjCForCollectionStmt:
4204 return cxstring::createRef("ObjCForCollectionStmt");
4205 case CXCursor_CXXCatchStmt:
4206 return cxstring::createRef("CXXCatchStmt");
4207 case CXCursor_CXXTryStmt:
4208 return cxstring::createRef("CXXTryStmt");
4209 case CXCursor_CXXForRangeStmt:
4210 return cxstring::createRef("CXXForRangeStmt");
4211 case CXCursor_SEHTryStmt:
4212 return cxstring::createRef("SEHTryStmt");
4213 case CXCursor_SEHExceptStmt:
4214 return cxstring::createRef("SEHExceptStmt");
4215 case CXCursor_SEHFinallyStmt:
4216 return cxstring::createRef("SEHFinallyStmt");
4217 case CXCursor_SEHLeaveStmt:
4218 return cxstring::createRef("SEHLeaveStmt");
4219 case CXCursor_NullStmt:
4220 return cxstring::createRef("NullStmt");
4221 case CXCursor_InvalidFile:
4222 return cxstring::createRef("InvalidFile");
4223 case CXCursor_InvalidCode:
4224 return cxstring::createRef("InvalidCode");
4225 case CXCursor_NoDeclFound:
4226 return cxstring::createRef("NoDeclFound");
4227 case CXCursor_NotImplemented:
4228 return cxstring::createRef("NotImplemented");
4229 case CXCursor_TranslationUnit:
4230 return cxstring::createRef("TranslationUnit");
4231 case CXCursor_UnexposedAttr:
4232 return cxstring::createRef("UnexposedAttr");
4233 case CXCursor_IBActionAttr:
4234 return cxstring::createRef("attribute(ibaction)");
4235 case CXCursor_IBOutletAttr:
4236 return cxstring::createRef("attribute(iboutlet)");
4237 case CXCursor_IBOutletCollectionAttr:
4238 return cxstring::createRef("attribute(iboutletcollection)");
4239 case CXCursor_CXXFinalAttr:
4240 return cxstring::createRef("attribute(final)");
4241 case CXCursor_CXXOverrideAttr:
4242 return cxstring::createRef("attribute(override)");
4243 case CXCursor_AnnotateAttr:
4244 return cxstring::createRef("attribute(annotate)");
4245 case CXCursor_AsmLabelAttr:
4246 return cxstring::createRef("asm label");
4247 case CXCursor_PackedAttr:
4248 return cxstring::createRef("attribute(packed)");
4249 case CXCursor_PureAttr:
4250 return cxstring::createRef("attribute(pure)");
4251 case CXCursor_ConstAttr:
4252 return cxstring::createRef("attribute(const)");
4253 case CXCursor_NoDuplicateAttr:
4254 return cxstring::createRef("attribute(noduplicate)");
4255 case CXCursor_CUDAConstantAttr:
4256 return cxstring::createRef("attribute(constant)");
4257 case CXCursor_CUDADeviceAttr:
4258 return cxstring::createRef("attribute(device)");
4259 case CXCursor_CUDAGlobalAttr:
4260 return cxstring::createRef("attribute(global)");
4261 case CXCursor_CUDAHostAttr:
4262 return cxstring::createRef("attribute(host)");
4263 case CXCursor_CUDASharedAttr:
4264 return cxstring::createRef("attribute(shared)");
4265 case CXCursor_VisibilityAttr:
4266 return cxstring::createRef("attribute(visibility)");
4267 case CXCursor_PreprocessingDirective:
4268 return cxstring::createRef("preprocessing directive");
4269 case CXCursor_MacroDefinition:
4270 return cxstring::createRef("macro definition");
4271 case CXCursor_MacroExpansion:
4272 return cxstring::createRef("macro expansion");
4273 case CXCursor_InclusionDirective:
4274 return cxstring::createRef("inclusion directive");
4275 case CXCursor_Namespace:
4276 return cxstring::createRef("Namespace");
4277 case CXCursor_LinkageSpec:
4278 return cxstring::createRef("LinkageSpec");
4279 case CXCursor_CXXBaseSpecifier:
4280 return cxstring::createRef("C++ base class specifier");
4281 case CXCursor_Constructor:
4282 return cxstring::createRef("CXXConstructor");
4283 case CXCursor_Destructor:
4284 return cxstring::createRef("CXXDestructor");
4285 case CXCursor_ConversionFunction:
4286 return cxstring::createRef("CXXConversion");
4287 case CXCursor_TemplateTypeParameter:
4288 return cxstring::createRef("TemplateTypeParameter");
4289 case CXCursor_NonTypeTemplateParameter:
4290 return cxstring::createRef("NonTypeTemplateParameter");
4291 case CXCursor_TemplateTemplateParameter:
4292 return cxstring::createRef("TemplateTemplateParameter");
4293 case CXCursor_FunctionTemplate:
4294 return cxstring::createRef("FunctionTemplate");
4295 case CXCursor_ClassTemplate:
4296 return cxstring::createRef("ClassTemplate");
4297 case CXCursor_ClassTemplatePartialSpecialization:
4298 return cxstring::createRef("ClassTemplatePartialSpecialization");
4299 case CXCursor_NamespaceAlias:
4300 return cxstring::createRef("NamespaceAlias");
4301 case CXCursor_UsingDirective:
4302 return cxstring::createRef("UsingDirective");
4303 case CXCursor_UsingDeclaration:
4304 return cxstring::createRef("UsingDeclaration");
4305 case CXCursor_TypeAliasDecl:
4306 return cxstring::createRef("TypeAliasDecl");
4307 case CXCursor_ObjCSynthesizeDecl:
4308 return cxstring::createRef("ObjCSynthesizeDecl");
4309 case CXCursor_ObjCDynamicDecl:
4310 return cxstring::createRef("ObjCDynamicDecl");
4311 case CXCursor_CXXAccessSpecifier:
4312 return cxstring::createRef("CXXAccessSpecifier");
4313 case CXCursor_ModuleImportDecl:
4314 return cxstring::createRef("ModuleImport");
4315 case CXCursor_OMPParallelDirective:
4316 return cxstring::createRef("OMPParallelDirective");
4317 case CXCursor_OMPSimdDirective:
4318 return cxstring::createRef("OMPSimdDirective");
4319 case CXCursor_OMPForDirective:
4320 return cxstring::createRef("OMPForDirective");
4321 case CXCursor_OMPForSimdDirective:
4322 return cxstring::createRef("OMPForSimdDirective");
4323 case CXCursor_OMPSectionsDirective:
4324 return cxstring::createRef("OMPSectionsDirective");
4325 case CXCursor_OMPSectionDirective:
4326 return cxstring::createRef("OMPSectionDirective");
4327 case CXCursor_OMPSingleDirective:
4328 return cxstring::createRef("OMPSingleDirective");
4329 case CXCursor_OMPMasterDirective:
4330 return cxstring::createRef("OMPMasterDirective");
4331 case CXCursor_OMPCriticalDirective:
4332 return cxstring::createRef("OMPCriticalDirective");
4333 case CXCursor_OMPParallelForDirective:
4334 return cxstring::createRef("OMPParallelForDirective");
4335 case CXCursor_OMPParallelForSimdDirective:
4336 return cxstring::createRef("OMPParallelForSimdDirective");
4337 case CXCursor_OMPParallelSectionsDirective:
4338 return cxstring::createRef("OMPParallelSectionsDirective");
4339 case CXCursor_OMPTaskDirective:
4340 return cxstring::createRef("OMPTaskDirective");
4341 case CXCursor_OMPTaskyieldDirective:
4342 return cxstring::createRef("OMPTaskyieldDirective");
4343 case CXCursor_OMPBarrierDirective:
4344 return cxstring::createRef("OMPBarrierDirective");
4345 case CXCursor_OMPTaskwaitDirective:
4346 return cxstring::createRef("OMPTaskwaitDirective");
4347 case CXCursor_OMPTaskgroupDirective:
4348 return cxstring::createRef("OMPTaskgroupDirective");
4349 case CXCursor_OMPFlushDirective:
4350 return cxstring::createRef("OMPFlushDirective");
4351 case CXCursor_OMPOrderedDirective:
4352 return cxstring::createRef("OMPOrderedDirective");
4353 case CXCursor_OMPAtomicDirective:
4354 return cxstring::createRef("OMPAtomicDirective");
4355 case CXCursor_OMPTargetDirective:
4356 return cxstring::createRef("OMPTargetDirective");
4357 case CXCursor_OMPTargetDataDirective:
4358 return cxstring::createRef("OMPTargetDataDirective");
4359 case CXCursor_OMPTeamsDirective:
4360 return cxstring::createRef("OMPTeamsDirective");
4361 case CXCursor_OMPCancellationPointDirective:
4362 return cxstring::createRef("OMPCancellationPointDirective");
4363 case CXCursor_OMPCancelDirective:
4364 return cxstring::createRef("OMPCancelDirective");
4365 case CXCursor_OverloadCandidate:
4366 return cxstring::createRef("OverloadCandidate");
4369 llvm_unreachable("Unhandled CXCursorKind");
4372 struct GetCursorData {
4373 SourceLocation TokenBeginLoc;
4374 bool PointsAtMacroArgExpansion;
4375 bool VisitedObjCPropertyImplDecl;
4376 SourceLocation VisitedDeclaratorDeclStartLoc;
4377 CXCursor &BestCursor;
4379 GetCursorData(SourceManager &SM,
4380 SourceLocation tokenBegin, CXCursor &outputCursor)
4381 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4382 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4383 VisitedObjCPropertyImplDecl = false;
4387 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4389 CXClientData client_data) {
4390 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4391 CXCursor *BestCursor = &Data->BestCursor;
4393 // If we point inside a macro argument we should provide info of what the
4394 // token is so use the actual cursor, don't replace it with a macro expansion
4396 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4397 return CXChildVisit_Recurse;
4399 if (clang_isDeclaration(cursor.kind)) {
4400 // Avoid having the implicit methods override the property decls.
4401 if (const ObjCMethodDecl *MD
4402 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4403 if (MD->isImplicit())
4404 return CXChildVisit_Break;
4406 } else if (const ObjCInterfaceDecl *ID
4407 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4408 // Check that when we have multiple @class references in the same line,
4409 // that later ones do not override the previous ones.
4412 // source ranges for both start at '@', so 'Bar' will end up overriding
4413 // 'Foo' even though the cursor location was at 'Foo'.
4414 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4415 BestCursor->kind == CXCursor_ObjCClassRef)
4416 if (const ObjCInterfaceDecl *PrevID
4417 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4419 !PrevID->isThisDeclarationADefinition() &&
4420 !ID->isThisDeclarationADefinition())
4421 return CXChildVisit_Break;
4424 } else if (const DeclaratorDecl *DD
4425 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4426 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4427 // Check that when we have multiple declarators in the same line,
4428 // that later ones do not override the previous ones.
4431 // source ranges for both start at 'int', so 'Bar' will end up overriding
4432 // 'Foo' even though the cursor location was at 'Foo'.
4433 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4434 return CXChildVisit_Break;
4435 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4437 } else if (const ObjCPropertyImplDecl *PropImp
4438 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4440 // Check that when we have multiple @synthesize in the same line,
4441 // that later ones do not override the previous ones.
4443 // @synthesize Foo, Bar;
4444 // source ranges for both start at '@', so 'Bar' will end up overriding
4445 // 'Foo' even though the cursor location was at 'Foo'.
4446 if (Data->VisitedObjCPropertyImplDecl)
4447 return CXChildVisit_Break;
4448 Data->VisitedObjCPropertyImplDecl = true;
4452 if (clang_isExpression(cursor.kind) &&
4453 clang_isDeclaration(BestCursor->kind)) {
4454 if (const Decl *D = getCursorDecl(*BestCursor)) {
4455 // Avoid having the cursor of an expression replace the declaration cursor
4456 // when the expression source range overlaps the declaration range.
4457 // This can happen for C++ constructor expressions whose range generally
4458 // include the variable declaration, e.g.:
4459 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4460 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4461 D->getLocation() == Data->TokenBeginLoc)
4462 return CXChildVisit_Break;
4466 // If our current best cursor is the construction of a temporary object,
4467 // don't replace that cursor with a type reference, because we want
4468 // clang_getCursor() to point at the constructor.
4469 if (clang_isExpression(BestCursor->kind) &&
4470 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4471 cursor.kind == CXCursor_TypeRef) {
4472 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4473 // as having the actual point on the type reference.
4474 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4475 return CXChildVisit_Recurse;
4478 // If we already have an Objective-C superclass reference, don't
4479 // update it further.
4480 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4481 return CXChildVisit_Break;
4483 *BestCursor = cursor;
4484 return CXChildVisit_Recurse;
4487 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4488 if (isNotUsableTU(TU)) {
4490 return clang_getNullCursor();
4493 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4494 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4496 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4497 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4501 unsigned SearchLine, SearchColumn;
4503 unsigned ResultLine, ResultColumn;
4504 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4505 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4506 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4508 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4510 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4511 &ResultColumn, nullptr);
4512 SearchFileName = clang_getFileName(SearchFile);
4513 ResultFileName = clang_getFileName(ResultFile);
4514 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4515 USR = clang_getCursorUSR(Result);
4516 *Log << llvm::format("(%s:%d:%d) = %s",
4517 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4518 clang_getCString(KindSpelling))
4519 << llvm::format("(%s:%d:%d):%s%s",
4520 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4521 clang_getCString(USR), IsDef);
4522 clang_disposeString(SearchFileName);
4523 clang_disposeString(ResultFileName);
4524 clang_disposeString(KindSpelling);
4525 clang_disposeString(USR);
4527 CXCursor Definition = clang_getCursorDefinition(Result);
4528 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4529 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4530 CXString DefinitionKindSpelling
4531 = clang_getCursorKindSpelling(Definition.kind);
4532 CXFile DefinitionFile;
4533 unsigned DefinitionLine, DefinitionColumn;
4534 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
4535 &DefinitionLine, &DefinitionColumn, nullptr);
4536 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
4537 *Log << llvm::format(" -> %s(%s:%d:%d)",
4538 clang_getCString(DefinitionKindSpelling),
4539 clang_getCString(DefinitionFileName),
4540 DefinitionLine, DefinitionColumn);
4541 clang_disposeString(DefinitionFileName);
4542 clang_disposeString(DefinitionKindSpelling);
4549 CXCursor clang_getNullCursor(void) {
4550 return MakeCXCursorInvalid(CXCursor_InvalidFile);
4553 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
4554 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
4555 // can't set consistently. For example, when visiting a DeclStmt we will set
4556 // it but we don't set it on the result of clang_getCursorDefinition for
4557 // a reference of the same declaration.
4558 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
4559 // when visiting a DeclStmt currently, the AST should be enhanced to be able
4560 // to provide that kind of info.
4561 if (clang_isDeclaration(X.kind))
4562 X.data[1] = nullptr;
4563 if (clang_isDeclaration(Y.kind))
4564 Y.data[1] = nullptr;
4569 unsigned clang_hashCursor(CXCursor C) {
4571 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
4574 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
4575 std::make_pair(C.kind, C.data[Index]));
4578 unsigned clang_isInvalid(enum CXCursorKind K) {
4579 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
4582 unsigned clang_isDeclaration(enum CXCursorKind K) {
4583 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
4584 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
4587 unsigned clang_isReference(enum CXCursorKind K) {
4588 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
4591 unsigned clang_isExpression(enum CXCursorKind K) {
4592 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
4595 unsigned clang_isStatement(enum CXCursorKind K) {
4596 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
4599 unsigned clang_isAttribute(enum CXCursorKind K) {
4600 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
4603 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
4604 return K == CXCursor_TranslationUnit;
4607 unsigned clang_isPreprocessing(enum CXCursorKind K) {
4608 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
4611 unsigned clang_isUnexposed(enum CXCursorKind K) {
4613 case CXCursor_UnexposedDecl:
4614 case CXCursor_UnexposedExpr:
4615 case CXCursor_UnexposedStmt:
4616 case CXCursor_UnexposedAttr:
4623 CXCursorKind clang_getCursorKind(CXCursor C) {
4627 CXSourceLocation clang_getCursorLocation(CXCursor C) {
4628 if (clang_isReference(C.kind)) {
4630 case CXCursor_ObjCSuperClassRef: {
4631 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4632 = getCursorObjCSuperClassRef(C);
4633 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4636 case CXCursor_ObjCProtocolRef: {
4637 std::pair<const ObjCProtocolDecl *, SourceLocation> P
4638 = getCursorObjCProtocolRef(C);
4639 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4642 case CXCursor_ObjCClassRef: {
4643 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4644 = getCursorObjCClassRef(C);
4645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4648 case CXCursor_TypeRef: {
4649 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
4650 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4653 case CXCursor_TemplateRef: {
4654 std::pair<const TemplateDecl *, SourceLocation> P =
4655 getCursorTemplateRef(C);
4656 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4659 case CXCursor_NamespaceRef: {
4660 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
4661 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4664 case CXCursor_MemberRef: {
4665 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4666 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4669 case CXCursor_VariableRef: {
4670 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4674 case CXCursor_CXXBaseSpecifier: {
4675 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4677 return clang_getNullLocation();
4679 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4680 return cxloc::translateSourceLocation(getCursorContext(C),
4681 TSInfo->getTypeLoc().getBeginLoc());
4683 return cxloc::translateSourceLocation(getCursorContext(C),
4684 BaseSpec->getLocStart());
4687 case CXCursor_LabelRef: {
4688 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4689 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4692 case CXCursor_OverloadedDeclRef:
4693 return cxloc::translateSourceLocation(getCursorContext(C),
4694 getCursorOverloadedDeclRef(C).second);
4697 // FIXME: Need a way to enumerate all non-reference cases.
4698 llvm_unreachable("Missed a reference kind");
4702 if (clang_isExpression(C.kind))
4703 return cxloc::translateSourceLocation(getCursorContext(C),
4704 getLocationFromExpr(getCursorExpr(C)));
4706 if (clang_isStatement(C.kind))
4707 return cxloc::translateSourceLocation(getCursorContext(C),
4708 getCursorStmt(C)->getLocStart());
4710 if (C.kind == CXCursor_PreprocessingDirective) {
4711 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4712 return cxloc::translateSourceLocation(getCursorContext(C), L);
4715 if (C.kind == CXCursor_MacroExpansion) {
4717 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4718 return cxloc::translateSourceLocation(getCursorContext(C), L);
4721 if (C.kind == CXCursor_MacroDefinition) {
4722 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4723 return cxloc::translateSourceLocation(getCursorContext(C), L);
4726 if (C.kind == CXCursor_InclusionDirective) {
4728 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4729 return cxloc::translateSourceLocation(getCursorContext(C), L);
4732 if (clang_isAttribute(C.kind)) {
4734 = cxcursor::getCursorAttr(C)->getLocation();
4735 return cxloc::translateSourceLocation(getCursorContext(C), L);
4738 if (!clang_isDeclaration(C.kind))
4739 return clang_getNullLocation();
4741 const Decl *D = getCursorDecl(C);
4743 return clang_getNullLocation();
4745 SourceLocation Loc = D->getLocation();
4746 // FIXME: Multiple variables declared in a single declaration
4747 // currently lack the information needed to correctly determine their
4748 // ranges when accounting for the type-specifier. We use context
4749 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4750 // and if so, whether it is the first decl.
4751 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4752 if (!cxcursor::isFirstInDeclGroup(C))
4753 Loc = VD->getLocation();
4756 // For ObjC methods, give the start location of the method name.
4757 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4758 Loc = MD->getSelectorStartLoc();
4760 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4765 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4768 // Guard against an invalid SourceLocation, or we may assert in one
4769 // of the following calls.
4770 if (SLoc.isInvalid())
4771 return clang_getNullCursor();
4773 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4775 // Translate the given source location to make it point at the beginning of
4776 // the token under the cursor.
4777 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4778 CXXUnit->getASTContext().getLangOpts());
4780 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4781 if (SLoc.isValid()) {
4782 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4783 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4784 /*VisitPreprocessorLast=*/true,
4785 /*VisitIncludedEntities=*/false,
4786 SourceLocation(SLoc));
4787 CursorVis.visitFileRegion();
4793 static SourceRange getRawCursorExtent(CXCursor C) {
4794 if (clang_isReference(C.kind)) {
4796 case CXCursor_ObjCSuperClassRef:
4797 return getCursorObjCSuperClassRef(C).second;
4799 case CXCursor_ObjCProtocolRef:
4800 return getCursorObjCProtocolRef(C).second;
4802 case CXCursor_ObjCClassRef:
4803 return getCursorObjCClassRef(C).second;
4805 case CXCursor_TypeRef:
4806 return getCursorTypeRef(C).second;
4808 case CXCursor_TemplateRef:
4809 return getCursorTemplateRef(C).second;
4811 case CXCursor_NamespaceRef:
4812 return getCursorNamespaceRef(C).second;
4814 case CXCursor_MemberRef:
4815 return getCursorMemberRef(C).second;
4817 case CXCursor_CXXBaseSpecifier:
4818 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4820 case CXCursor_LabelRef:
4821 return getCursorLabelRef(C).second;
4823 case CXCursor_OverloadedDeclRef:
4824 return getCursorOverloadedDeclRef(C).second;
4826 case CXCursor_VariableRef:
4827 return getCursorVariableRef(C).second;
4830 // FIXME: Need a way to enumerate all non-reference cases.
4831 llvm_unreachable("Missed a reference kind");
4835 if (clang_isExpression(C.kind))
4836 return getCursorExpr(C)->getSourceRange();
4838 if (clang_isStatement(C.kind))
4839 return getCursorStmt(C)->getSourceRange();
4841 if (clang_isAttribute(C.kind))
4842 return getCursorAttr(C)->getRange();
4844 if (C.kind == CXCursor_PreprocessingDirective)
4845 return cxcursor::getCursorPreprocessingDirective(C);
4847 if (C.kind == CXCursor_MacroExpansion) {
4848 ASTUnit *TU = getCursorASTUnit(C);
4849 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4850 return TU->mapRangeFromPreamble(Range);
4853 if (C.kind == CXCursor_MacroDefinition) {
4854 ASTUnit *TU = getCursorASTUnit(C);
4855 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4856 return TU->mapRangeFromPreamble(Range);
4859 if (C.kind == CXCursor_InclusionDirective) {
4860 ASTUnit *TU = getCursorASTUnit(C);
4861 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4862 return TU->mapRangeFromPreamble(Range);
4865 if (C.kind == CXCursor_TranslationUnit) {
4866 ASTUnit *TU = getCursorASTUnit(C);
4867 FileID MainID = TU->getSourceManager().getMainFileID();
4868 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4869 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4870 return SourceRange(Start, End);
4873 if (clang_isDeclaration(C.kind)) {
4874 const Decl *D = cxcursor::getCursorDecl(C);
4876 return SourceRange();
4878 SourceRange R = D->getSourceRange();
4879 // FIXME: Multiple variables declared in a single declaration
4880 // currently lack the information needed to correctly determine their
4881 // ranges when accounting for the type-specifier. We use context
4882 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4883 // and if so, whether it is the first decl.
4884 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4885 if (!cxcursor::isFirstInDeclGroup(C))
4886 R.setBegin(VD->getLocation());
4890 return SourceRange();
4893 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
4894 /// the decl-specifier-seq for declarations.
4895 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4896 if (clang_isDeclaration(C.kind)) {
4897 const Decl *D = cxcursor::getCursorDecl(C);
4899 return SourceRange();
4901 SourceRange R = D->getSourceRange();
4903 // Adjust the start of the location for declarations preceded by
4904 // declaration specifiers.
4905 SourceLocation StartLoc;
4906 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4907 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4908 StartLoc = TI->getTypeLoc().getLocStart();
4909 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4910 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4911 StartLoc = TI->getTypeLoc().getLocStart();
4914 if (StartLoc.isValid() && R.getBegin().isValid() &&
4915 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4916 R.setBegin(StartLoc);
4918 // FIXME: Multiple variables declared in a single declaration
4919 // currently lack the information needed to correctly determine their
4920 // ranges when accounting for the type-specifier. We use context
4921 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4922 // and if so, whether it is the first decl.
4923 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4924 if (!cxcursor::isFirstInDeclGroup(C))
4925 R.setBegin(VD->getLocation());
4931 return getRawCursorExtent(C);
4936 CXSourceRange clang_getCursorExtent(CXCursor C) {
4937 SourceRange R = getRawCursorExtent(C);
4939 return clang_getNullRange();
4941 return cxloc::translateSourceRange(getCursorContext(C), R);
4944 CXCursor clang_getCursorReferenced(CXCursor C) {
4945 if (clang_isInvalid(C.kind))
4946 return clang_getNullCursor();
4948 CXTranslationUnit tu = getCursorTU(C);
4949 if (clang_isDeclaration(C.kind)) {
4950 const Decl *D = getCursorDecl(C);
4952 return clang_getNullCursor();
4953 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4954 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4955 if (const ObjCPropertyImplDecl *PropImpl =
4956 dyn_cast<ObjCPropertyImplDecl>(D))
4957 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4958 return MakeCXCursor(Property, tu);
4963 if (clang_isExpression(C.kind)) {
4964 const Expr *E = getCursorExpr(C);
4965 const Decl *D = getDeclFromExpr(E);
4967 CXCursor declCursor = MakeCXCursor(D, tu);
4968 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4973 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4974 return MakeCursorOverloadedDeclRef(Ovl, tu);
4976 return clang_getNullCursor();
4979 if (clang_isStatement(C.kind)) {
4980 const Stmt *S = getCursorStmt(C);
4981 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4982 if (LabelDecl *label = Goto->getLabel())
4983 if (LabelStmt *labelS = label->getStmt())
4984 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4986 return clang_getNullCursor();
4989 if (C.kind == CXCursor_MacroExpansion) {
4990 if (const MacroDefinitionRecord *Def =
4991 getCursorMacroExpansion(C).getDefinition())
4992 return MakeMacroDefinitionCursor(Def, tu);
4995 if (!clang_isReference(C.kind))
4996 return clang_getNullCursor();
4999 case CXCursor_ObjCSuperClassRef:
5000 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5002 case CXCursor_ObjCProtocolRef: {
5003 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5004 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5005 return MakeCXCursor(Def, tu);
5007 return MakeCXCursor(Prot, tu);
5010 case CXCursor_ObjCClassRef: {
5011 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5012 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5013 return MakeCXCursor(Def, tu);
5015 return MakeCXCursor(Class, tu);
5018 case CXCursor_TypeRef:
5019 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5021 case CXCursor_TemplateRef:
5022 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5024 case CXCursor_NamespaceRef:
5025 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5027 case CXCursor_MemberRef:
5028 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5030 case CXCursor_CXXBaseSpecifier: {
5031 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5032 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5036 case CXCursor_LabelRef:
5037 // FIXME: We end up faking the "parent" declaration here because we
5038 // don't want to make CXCursor larger.
5039 return MakeCXCursor(getCursorLabelRef(C).first,
5040 cxtu::getASTUnit(tu)->getASTContext()
5041 .getTranslationUnitDecl(),
5044 case CXCursor_OverloadedDeclRef:
5047 case CXCursor_VariableRef:
5048 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5051 // We would prefer to enumerate all non-reference cursor kinds here.
5052 llvm_unreachable("Unhandled reference cursor kind");
5056 CXCursor clang_getCursorDefinition(CXCursor C) {
5057 if (clang_isInvalid(C.kind))
5058 return clang_getNullCursor();
5060 CXTranslationUnit TU = getCursorTU(C);
5062 bool WasReference = false;
5063 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5064 C = clang_getCursorReferenced(C);
5065 WasReference = true;
5068 if (C.kind == CXCursor_MacroExpansion)
5069 return clang_getCursorReferenced(C);
5071 if (!clang_isDeclaration(C.kind))
5072 return clang_getNullCursor();
5074 const Decl *D = getCursorDecl(C);
5076 return clang_getNullCursor();
5078 switch (D->getKind()) {
5079 // Declaration kinds that don't really separate the notions of
5080 // declaration and definition.
5081 case Decl::Namespace:
5083 case Decl::TypeAlias:
5084 case Decl::TypeAliasTemplate:
5085 case Decl::TemplateTypeParm:
5086 case Decl::EnumConstant:
5088 case Decl::MSProperty:
5089 case Decl::IndirectField:
5090 case Decl::ObjCIvar:
5091 case Decl::ObjCAtDefsField:
5092 case Decl::ImplicitParam:
5094 case Decl::NonTypeTemplateParm:
5095 case Decl::TemplateTemplateParm:
5096 case Decl::ObjCCategoryImpl:
5097 case Decl::ObjCImplementation:
5098 case Decl::AccessSpec:
5099 case Decl::LinkageSpec:
5100 case Decl::ObjCPropertyImpl:
5101 case Decl::FileScopeAsm:
5102 case Decl::StaticAssert:
5104 case Decl::Captured:
5105 case Decl::Label: // FIXME: Is this right??
5106 case Decl::ClassScopeFunctionSpecialization:
5108 case Decl::OMPThreadPrivate:
5109 case Decl::ObjCTypeParam:
5112 // Declaration kinds that don't make any sense here, but are
5113 // nonetheless harmless.
5115 case Decl::TranslationUnit:
5116 case Decl::ExternCContext:
5119 // Declaration kinds for which the definition is not resolvable.
5120 case Decl::UnresolvedUsingTypename:
5121 case Decl::UnresolvedUsingValue:
5124 case Decl::UsingDirective:
5125 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5128 case Decl::NamespaceAlias:
5129 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5133 case Decl::CXXRecord:
5134 case Decl::ClassTemplateSpecialization:
5135 case Decl::ClassTemplatePartialSpecialization:
5136 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5137 return MakeCXCursor(Def, TU);
5138 return clang_getNullCursor();
5140 case Decl::Function:
5141 case Decl::CXXMethod:
5142 case Decl::CXXConstructor:
5143 case Decl::CXXDestructor:
5144 case Decl::CXXConversion: {
5145 const FunctionDecl *Def = nullptr;
5146 if (cast<FunctionDecl>(D)->getBody(Def))
5147 return MakeCXCursor(Def, TU);
5148 return clang_getNullCursor();
5152 case Decl::VarTemplateSpecialization:
5153 case Decl::VarTemplatePartialSpecialization: {
5154 // Ask the variable if it has a definition.
5155 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5156 return MakeCXCursor(Def, TU);
5157 return clang_getNullCursor();
5160 case Decl::FunctionTemplate: {
5161 const FunctionDecl *Def = nullptr;
5162 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5163 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5164 return clang_getNullCursor();
5167 case Decl::ClassTemplate: {
5168 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5170 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5172 return clang_getNullCursor();
5175 case Decl::VarTemplate: {
5177 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5178 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5179 return clang_getNullCursor();
5183 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5184 D->getLocation(), TU);
5186 case Decl::UsingShadow:
5187 return clang_getCursorDefinition(
5188 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5191 case Decl::ObjCMethod: {
5192 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5193 if (Method->isThisDeclarationADefinition())
5196 // Dig out the method definition in the associated
5197 // @implementation, if we have it.
5198 // FIXME: The ASTs should make finding the definition easier.
5199 if (const ObjCInterfaceDecl *Class
5200 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5201 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5202 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5203 Method->isInstanceMethod()))
5204 if (Def->isThisDeclarationADefinition())
5205 return MakeCXCursor(Def, TU);
5207 return clang_getNullCursor();
5210 case Decl::ObjCCategory:
5211 if (ObjCCategoryImplDecl *Impl
5212 = cast<ObjCCategoryDecl>(D)->getImplementation())
5213 return MakeCXCursor(Impl, TU);
5214 return clang_getNullCursor();
5216 case Decl::ObjCProtocol:
5217 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5218 return MakeCXCursor(Def, TU);
5219 return clang_getNullCursor();
5221 case Decl::ObjCInterface: {
5222 // There are two notions of a "definition" for an Objective-C
5223 // class: the interface and its implementation. When we resolved a
5224 // reference to an Objective-C class, produce the @interface as
5225 // the definition; when we were provided with the interface,
5226 // produce the @implementation as the definition.
5227 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5229 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5230 return MakeCXCursor(Def, TU);
5231 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5232 return MakeCXCursor(Impl, TU);
5233 return clang_getNullCursor();
5236 case Decl::ObjCProperty:
5237 // FIXME: We don't really know where to find the
5238 // ObjCPropertyImplDecls that implement this property.
5239 return clang_getNullCursor();
5241 case Decl::ObjCCompatibleAlias:
5242 if (const ObjCInterfaceDecl *Class
5243 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5244 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5245 return MakeCXCursor(Def, TU);
5247 return clang_getNullCursor();
5250 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5251 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5252 return clang_getNullCursor();
5254 case Decl::FriendTemplate:
5255 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5256 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5257 return clang_getNullCursor();
5260 return clang_getNullCursor();
5263 unsigned clang_isCursorDefinition(CXCursor C) {
5264 if (!clang_isDeclaration(C.kind))
5267 return clang_getCursorDefinition(C) == C;
5270 CXCursor clang_getCanonicalCursor(CXCursor C) {
5271 if (!clang_isDeclaration(C.kind))
5274 if (const Decl *D = getCursorDecl(C)) {
5275 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5276 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5277 return MakeCXCursor(CatD, getCursorTU(C));
5279 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5280 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5281 return MakeCXCursor(IFD, getCursorTU(C));
5283 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5289 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5290 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5293 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5294 if (C.kind != CXCursor_OverloadedDeclRef)
5297 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5298 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5299 return E->getNumDecls();
5301 if (OverloadedTemplateStorage *S
5302 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5305 const Decl *D = Storage.get<const Decl *>();
5306 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5307 return Using->shadow_size();
5312 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5313 if (cursor.kind != CXCursor_OverloadedDeclRef)
5314 return clang_getNullCursor();
5316 if (index >= clang_getNumOverloadedDecls(cursor))
5317 return clang_getNullCursor();
5319 CXTranslationUnit TU = getCursorTU(cursor);
5320 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5321 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5322 return MakeCXCursor(E->decls_begin()[index], TU);
5324 if (OverloadedTemplateStorage *S
5325 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5326 return MakeCXCursor(S->begin()[index], TU);
5328 const Decl *D = Storage.get<const Decl *>();
5329 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5330 // FIXME: This is, unfortunately, linear time.
5331 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5332 std::advance(Pos, index);
5333 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5336 return clang_getNullCursor();
5339 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5340 const char **startBuf,
5341 const char **endBuf,
5342 unsigned *startLine,
5343 unsigned *startColumn,
5345 unsigned *endColumn) {
5346 assert(getCursorDecl(C) && "CXCursor has null decl");
5347 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5348 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5350 SourceManager &SM = FD->getASTContext().getSourceManager();
5351 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5352 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5353 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5354 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5355 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5356 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5360 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5361 unsigned PieceIndex) {
5362 RefNamePieces Pieces;
5365 case CXCursor_MemberRefExpr:
5366 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5367 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5368 E->getQualifierLoc().getSourceRange());
5371 case CXCursor_DeclRefExpr:
5372 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
5373 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
5374 E->getQualifierLoc().getSourceRange(),
5375 E->getOptionalExplicitTemplateArgs());
5378 case CXCursor_CallExpr:
5379 if (const CXXOperatorCallExpr *OCE =
5380 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5381 const Expr *Callee = OCE->getCallee();
5382 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5383 Callee = ICE->getSubExpr();
5385 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5386 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5387 DRE->getQualifierLoc().getSourceRange());
5395 if (Pieces.empty()) {
5396 if (PieceIndex == 0)
5397 return clang_getCursorExtent(C);
5398 } else if (PieceIndex < Pieces.size()) {
5399 SourceRange R = Pieces[PieceIndex];
5401 return cxloc::translateSourceRange(getCursorContext(C), R);
5404 return clang_getNullRange();
5407 void clang_enableStackTraces(void) {
5408 llvm::sys::PrintStackTraceOnErrorSignal();
5411 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5412 unsigned stack_size) {
5413 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5416 } // end: extern "C"
5418 //===----------------------------------------------------------------------===//
5419 // Token-based Operations.
5420 //===----------------------------------------------------------------------===//
5423 * int_data[0]: a CXTokenKind
5424 * int_data[1]: starting token location
5425 * int_data[2]: token length
5426 * int_data[3]: reserved
5427 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5432 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5433 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5436 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5437 switch (clang_getTokenKind(CXTok)) {
5438 case CXToken_Identifier:
5439 case CXToken_Keyword:
5440 // We know we have an IdentifierInfo*, so use that.
5441 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5444 case CXToken_Literal: {
5445 // We have stashed the starting pointer in the ptr_data field. Use it.
5446 const char *Text = static_cast<const char *>(CXTok.ptr_data);
5447 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5450 case CXToken_Punctuation:
5451 case CXToken_Comment:
5455 if (isNotUsableTU(TU)) {
5457 return cxstring::createEmpty();
5460 // We have to find the starting buffer pointer the hard way, by
5461 // deconstructing the source location.
5462 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5464 return cxstring::createEmpty();
5466 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5467 std::pair<FileID, unsigned> LocInfo
5468 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5469 bool Invalid = false;
5471 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5473 return cxstring::createEmpty();
5475 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5478 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5479 if (isNotUsableTU(TU)) {
5481 return clang_getNullLocation();
5484 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5486 return clang_getNullLocation();
5488 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5489 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5492 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5493 if (isNotUsableTU(TU)) {
5495 return clang_getNullRange();
5498 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5500 return clang_getNullRange();
5502 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5503 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5506 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5507 SmallVectorImpl<CXToken> &CXTokens) {
5508 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5509 std::pair<FileID, unsigned> BeginLocInfo
5510 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5511 std::pair<FileID, unsigned> EndLocInfo
5512 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5514 // Cannot tokenize across files.
5515 if (BeginLocInfo.first != EndLocInfo.first)
5519 bool Invalid = false;
5521 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5525 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5526 CXXUnit->getASTContext().getLangOpts(),
5527 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
5528 Lex.SetCommentRetentionState(true);
5530 // Lex tokens until we hit the end of the range.
5531 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
5533 bool previousWasAt = false;
5535 // Lex the next token
5536 Lex.LexFromRawLexer(Tok);
5537 if (Tok.is(tok::eof))
5540 // Initialize the CXToken.
5544 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
5545 CXTok.int_data[2] = Tok.getLength();
5546 CXTok.int_data[3] = 0;
5548 // - Kind-specific fields
5549 if (Tok.isLiteral()) {
5550 CXTok.int_data[0] = CXToken_Literal;
5551 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
5552 } else if (Tok.is(tok::raw_identifier)) {
5553 // Lookup the identifier to determine whether we have a keyword.
5555 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
5557 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
5558 CXTok.int_data[0] = CXToken_Keyword;
5561 CXTok.int_data[0] = Tok.is(tok::identifier)
5562 ? CXToken_Identifier
5565 CXTok.ptr_data = II;
5566 } else if (Tok.is(tok::comment)) {
5567 CXTok.int_data[0] = CXToken_Comment;
5568 CXTok.ptr_data = nullptr;
5570 CXTok.int_data[0] = CXToken_Punctuation;
5571 CXTok.ptr_data = nullptr;
5573 CXTokens.push_back(CXTok);
5574 previousWasAt = Tok.is(tok::at);
5575 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
5578 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
5579 CXToken **Tokens, unsigned *NumTokens) {
5581 *Log << TU << ' ' << Range;
5589 if (isNotUsableTU(TU)) {
5594 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5595 if (!CXXUnit || !Tokens || !NumTokens)
5598 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5600 SourceRange R = cxloc::translateCXSourceRange(Range);
5604 SmallVector<CXToken, 32> CXTokens;
5605 getTokens(CXXUnit, R, CXTokens);
5607 if (CXTokens.empty())
5610 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
5611 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
5612 *NumTokens = CXTokens.size();
5615 void clang_disposeTokens(CXTranslationUnit TU,
5616 CXToken *Tokens, unsigned NumTokens) {
5620 } // end: extern "C"
5622 //===----------------------------------------------------------------------===//
5623 // Token annotation APIs.
5624 //===----------------------------------------------------------------------===//
5626 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5628 CXClientData client_data);
5629 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5630 CXClientData client_data);
5633 class AnnotateTokensWorker {
5638 unsigned PreprocessingTokIdx;
5639 CursorVisitor AnnotateVis;
5640 SourceManager &SrcMgr;
5641 bool HasContextSensitiveKeywords;
5643 struct PostChildrenInfo {
5645 SourceRange CursorRange;
5646 unsigned BeforeReachingCursorIdx;
5647 unsigned BeforeChildrenTokenIdx;
5649 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
5651 CXToken &getTok(unsigned Idx) {
5652 assert(Idx < NumTokens);
5655 const CXToken &getTok(unsigned Idx) const {
5656 assert(Idx < NumTokens);
5659 bool MoreTokens() const { return TokIdx < NumTokens; }
5660 unsigned NextToken() const { return TokIdx; }
5661 void AdvanceToken() { ++TokIdx; }
5662 SourceLocation GetTokenLoc(unsigned tokI) {
5663 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
5665 bool isFunctionMacroToken(unsigned tokI) const {
5666 return getTok(tokI).int_data[3] != 0;
5668 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
5669 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
5672 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
5673 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
5677 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
5678 CXTranslationUnit TU, SourceRange RegionOfInterest)
5679 : Tokens(tokens), Cursors(cursors),
5680 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
5682 AnnotateTokensVisitor, this,
5683 /*VisitPreprocessorLast=*/true,
5684 /*VisitIncludedEntities=*/false,
5686 /*VisitDeclsOnly=*/false,
5687 AnnotateTokensPostChildrenVisitor),
5688 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
5689 HasContextSensitiveKeywords(false) { }
5691 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
5692 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
5693 bool postVisitChildren(CXCursor cursor);
5694 void AnnotateTokens();
5696 /// \brief Determine whether the annotator saw any cursors that have
5697 /// context-sensitive keywords.
5698 bool hasContextSensitiveKeywords() const {
5699 return HasContextSensitiveKeywords;
5702 ~AnnotateTokensWorker() {
5703 assert(PostChildrenInfos.empty());
5708 void AnnotateTokensWorker::AnnotateTokens() {
5709 // Walk the AST within the region of interest, annotating tokens
5711 AnnotateVis.visitFileRegion();
5714 static inline void updateCursorAnnotation(CXCursor &Cursor,
5715 const CXCursor &updateC) {
5716 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
5721 /// \brief It annotates and advances tokens with a cursor until the comparison
5722 //// between the cursor location and the source range is the same as
5723 /// \arg compResult.
5725 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5726 /// Pass RangeOverlap to annotate tokens inside a range.
5727 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5728 RangeComparisonResult compResult,
5729 SourceRange range) {
5730 while (MoreTokens()) {
5731 const unsigned I = NextToken();
5732 if (isFunctionMacroToken(I))
5733 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
5736 SourceLocation TokLoc = GetTokenLoc(I);
5737 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5738 updateCursorAnnotation(Cursors[I], updateC);
5746 /// \brief Special annotation handling for macro argument tokens.
5747 /// \returns true if it advanced beyond all macro tokens, false otherwise.
5748 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5750 RangeComparisonResult compResult,
5751 SourceRange range) {
5752 assert(MoreTokens());
5753 assert(isFunctionMacroToken(NextToken()) &&
5754 "Should be called only for macro arg tokens");
5756 // This works differently than annotateAndAdvanceTokens; because expanded
5757 // macro arguments can have arbitrary translation-unit source order, we do not
5758 // advance the token index one by one until a token fails the range test.
5759 // We only advance once past all of the macro arg tokens if all of them
5760 // pass the range test. If one of them fails we keep the token index pointing
5761 // at the start of the macro arg tokens so that the failing token will be
5762 // annotated by a subsequent annotation try.
5764 bool atLeastOneCompFail = false;
5766 unsigned I = NextToken();
5767 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5768 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5769 if (TokLoc.isFileID())
5770 continue; // not macro arg token, it's parens or comma.
5771 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5772 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5773 Cursors[I] = updateC;
5775 atLeastOneCompFail = true;
5778 if (atLeastOneCompFail)
5781 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5785 enum CXChildVisitResult
5786 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5787 SourceRange cursorRange = getRawCursorExtent(cursor);
5788 if (cursorRange.isInvalid())
5789 return CXChildVisit_Recurse;
5791 if (!HasContextSensitiveKeywords) {
5792 // Objective-C properties can have context-sensitive keywords.
5793 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5794 if (const ObjCPropertyDecl *Property
5795 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5796 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5798 // Objective-C methods can have context-sensitive keywords.
5799 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5800 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5801 if (const ObjCMethodDecl *Method
5802 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5803 if (Method->getObjCDeclQualifier())
5804 HasContextSensitiveKeywords = true;
5806 for (const auto *P : Method->params()) {
5807 if (P->getObjCDeclQualifier()) {
5808 HasContextSensitiveKeywords = true;
5815 // C++ methods can have context-sensitive keywords.
5816 else if (cursor.kind == CXCursor_CXXMethod) {
5817 if (const CXXMethodDecl *Method
5818 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5819 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5820 HasContextSensitiveKeywords = true;
5823 // C++ classes can have context-sensitive keywords.
5824 else if (cursor.kind == CXCursor_StructDecl ||
5825 cursor.kind == CXCursor_ClassDecl ||
5826 cursor.kind == CXCursor_ClassTemplate ||
5827 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5828 if (const Decl *D = getCursorDecl(cursor))
5829 if (D->hasAttr<FinalAttr>())
5830 HasContextSensitiveKeywords = true;
5834 // Don't override a property annotation with its getter/setter method.
5835 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
5836 parent.kind == CXCursor_ObjCPropertyDecl)
5837 return CXChildVisit_Continue;
5839 if (clang_isPreprocessing(cursor.kind)) {
5840 // Items in the preprocessing record are kept separate from items in
5841 // declarations, so we keep a separate token index.
5842 unsigned SavedTokIdx = TokIdx;
5843 TokIdx = PreprocessingTokIdx;
5845 // Skip tokens up until we catch up to the beginning of the preprocessing
5847 while (MoreTokens()) {
5848 const unsigned I = NextToken();
5849 SourceLocation TokLoc = GetTokenLoc(I);
5850 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5861 // Look at all of the tokens within this range.
5862 while (MoreTokens()) {
5863 const unsigned I = NextToken();
5864 SourceLocation TokLoc = GetTokenLoc(I);
5865 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5867 llvm_unreachable("Infeasible");
5871 // For macro expansions, just note where the beginning of the macro
5872 // expansion occurs.
5873 if (cursor.kind == CXCursor_MacroExpansion) {
5874 if (TokLoc == cursorRange.getBegin())
5875 Cursors[I] = cursor;
5879 // We may have already annotated macro names inside macro definitions.
5880 if (Cursors[I].kind != CXCursor_MacroExpansion)
5881 Cursors[I] = cursor;
5888 // Save the preprocessing token index; restore the non-preprocessing
5890 PreprocessingTokIdx = TokIdx;
5891 TokIdx = SavedTokIdx;
5892 return CXChildVisit_Recurse;
5895 if (cursorRange.isInvalid())
5896 return CXChildVisit_Continue;
5898 unsigned BeforeReachingCursorIdx = NextToken();
5899 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5900 const enum CXCursorKind K = clang_getCursorKind(parent);
5901 const CXCursor updateC =
5902 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
5903 // Attributes are annotated out-of-order, skip tokens until we reach it.
5904 clang_isAttribute(cursor.kind))
5905 ? clang_getNullCursor() : parent;
5907 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5909 // Avoid having the cursor of an expression "overwrite" the annotation of the
5910 // variable declaration that it belongs to.
5911 // This can happen for C++ constructor expressions whose range generally
5912 // include the variable declaration, e.g.:
5913 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5914 if (clang_isExpression(cursorK) && MoreTokens()) {
5915 const Expr *E = getCursorExpr(cursor);
5916 if (const Decl *D = getCursorParentDecl(cursor)) {
5917 const unsigned I = NextToken();
5918 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5919 E->getLocStart() == D->getLocation() &&
5920 E->getLocStart() == GetTokenLoc(I)) {
5921 updateCursorAnnotation(Cursors[I], updateC);
5927 // Before recursing into the children keep some state that we are going
5928 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5929 // extra work after the child nodes are visited.
5930 // Note that we don't call VisitChildren here to avoid traversing statements
5931 // code-recursively which can blow the stack.
5933 PostChildrenInfo Info;
5934 Info.Cursor = cursor;
5935 Info.CursorRange = cursorRange;
5936 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
5937 Info.BeforeChildrenTokenIdx = NextToken();
5938 PostChildrenInfos.push_back(Info);
5940 return CXChildVisit_Recurse;
5943 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5944 if (PostChildrenInfos.empty())
5946 const PostChildrenInfo &Info = PostChildrenInfos.back();
5947 if (!clang_equalCursors(Info.Cursor, cursor))
5950 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5951 const unsigned AfterChildren = NextToken();
5952 SourceRange cursorRange = Info.CursorRange;
5954 // Scan the tokens that are at the end of the cursor, but are not captured
5955 // but the child cursors.
5956 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5958 // Scan the tokens that are at the beginning of the cursor, but are not
5959 // capture by the child cursors.
5960 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5961 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5964 Cursors[I] = cursor;
5967 // Attributes are annotated out-of-order, rewind TokIdx to when we first
5968 // encountered the attribute cursor.
5969 if (clang_isAttribute(cursor.kind))
5970 TokIdx = Info.BeforeReachingCursorIdx;
5972 PostChildrenInfos.pop_back();
5976 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5978 CXClientData client_data) {
5979 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5982 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5983 CXClientData client_data) {
5984 return static_cast<AnnotateTokensWorker*>(client_data)->
5985 postVisitChildren(cursor);
5990 /// \brief Uses the macro expansions in the preprocessing record to find
5991 /// and mark tokens that are macro arguments. This info is used by the
5992 /// AnnotateTokensWorker.
5993 class MarkMacroArgTokensVisitor {
6000 MarkMacroArgTokensVisitor(SourceManager &SM,
6001 CXToken *tokens, unsigned numTokens)
6002 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6004 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6005 if (cursor.kind != CXCursor_MacroExpansion)
6006 return CXChildVisit_Continue;
6008 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6009 if (macroRange.getBegin() == macroRange.getEnd())
6010 return CXChildVisit_Continue; // it's not a function macro.
6012 for (; CurIdx < NumTokens; ++CurIdx) {
6013 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6014 macroRange.getBegin()))
6018 if (CurIdx == NumTokens)
6019 return CXChildVisit_Break;
6021 for (; CurIdx < NumTokens; ++CurIdx) {
6022 SourceLocation tokLoc = getTokenLoc(CurIdx);
6023 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6026 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6029 if (CurIdx == NumTokens)
6030 return CXChildVisit_Break;
6032 return CXChildVisit_Continue;
6036 CXToken &getTok(unsigned Idx) {
6037 assert(Idx < NumTokens);
6040 const CXToken &getTok(unsigned Idx) const {
6041 assert(Idx < NumTokens);
6045 SourceLocation getTokenLoc(unsigned tokI) {
6046 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6049 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6050 // The third field is reserved and currently not used. Use it here
6051 // to mark macro arg expanded tokens with their expanded locations.
6052 getTok(tokI).int_data[3] = loc.getRawEncoding();
6056 } // end anonymous namespace
6058 static CXChildVisitResult
6059 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6060 CXClientData client_data) {
6061 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6065 /// \brief Used by \c annotatePreprocessorTokens.
6066 /// \returns true if lexing was finished, false otherwise.
6067 static bool lexNext(Lexer &Lex, Token &Tok,
6068 unsigned &NextIdx, unsigned NumTokens) {
6069 if (NextIdx >= NumTokens)
6073 Lex.LexFromRawLexer(Tok);
6074 if (Tok.is(tok::eof))
6080 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6081 SourceRange RegionOfInterest,
6084 unsigned NumTokens) {
6085 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6087 Preprocessor &PP = CXXUnit->getPreprocessor();
6088 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6089 std::pair<FileID, unsigned> BeginLocInfo
6090 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6091 std::pair<FileID, unsigned> EndLocInfo
6092 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6094 if (BeginLocInfo.first != EndLocInfo.first)
6098 bool Invalid = false;
6099 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6100 if (Buffer.empty() || Invalid)
6103 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6104 CXXUnit->getASTContext().getLangOpts(),
6105 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6107 Lex.SetCommentRetentionState(true);
6109 unsigned NextIdx = 0;
6110 // Lex tokens in raw mode until we hit the end of the range, to avoid
6111 // entering #includes or expanding macros.
6114 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6116 unsigned TokIdx = NextIdx-1;
6117 assert(Tok.getLocation() ==
6118 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6121 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6122 // We have found a preprocessing directive. Annotate the tokens
6125 // FIXME: Some simple tests here could identify macro definitions and
6126 // #undefs, to provide specific cursor kinds for those.
6128 SourceLocation BeginLoc = Tok.getLocation();
6129 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6132 MacroInfo *MI = nullptr;
6133 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6134 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6137 if (Tok.is(tok::raw_identifier)) {
6138 IdentifierInfo &II =
6139 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6140 SourceLocation MappedTokLoc =
6141 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6142 MI = getMacroInfo(II, MappedTokLoc, TU);
6146 bool finished = false;
6148 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6152 // If we are in a macro definition, check if the token was ever a
6153 // macro name and annotate it if that's the case.
6155 SourceLocation SaveLoc = Tok.getLocation();
6156 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6157 MacroDefinitionRecord *MacroDef =
6158 checkForMacroInMacroDefinition(MI, Tok, TU);
6159 Tok.setLocation(SaveLoc);
6161 Cursors[NextIdx - 1] =
6162 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6164 } while (!Tok.isAtStartOfLine());
6166 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6167 assert(TokIdx <= LastIdx);
6168 SourceLocation EndLoc =
6169 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6171 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6173 for (; TokIdx <= LastIdx; ++TokIdx)
6174 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6183 // This gets run a separate thread to avoid stack blowout.
6184 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6185 CXToken *Tokens, unsigned NumTokens,
6186 CXCursor *Cursors) {
6187 CIndexer *CXXIdx = TU->CIdx;
6188 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6189 setThreadBackgroundPriority();
6191 // Determine the region of interest, which contains all of the tokens.
6192 SourceRange RegionOfInterest;
6193 RegionOfInterest.setBegin(
6194 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6195 RegionOfInterest.setEnd(
6196 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6197 Tokens[NumTokens-1])));
6199 // Relex the tokens within the source range to look for preprocessing
6201 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6203 // If begin location points inside a macro argument, set it to the expansion
6204 // location so we can have the full context when annotating semantically.
6206 SourceManager &SM = CXXUnit->getSourceManager();
6207 SourceLocation Loc =
6208 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6209 if (Loc.isMacroID())
6210 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6213 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6214 // Search and mark tokens that are macro argument expansions.
6215 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6217 CursorVisitor MacroArgMarker(TU,
6218 MarkMacroArgTokensVisitorDelegate, &Visitor,
6219 /*VisitPreprocessorLast=*/true,
6220 /*VisitIncludedEntities=*/false,
6222 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6225 // Annotate all of the source locations in the region of interest that map to
6226 // a specific cursor.
6227 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6229 // FIXME: We use a ridiculous stack size here because the data-recursion
6230 // algorithm uses a large stack frame than the non-data recursive version,
6231 // and AnnotationTokensWorker currently transforms the data-recursion
6232 // algorithm back into a traditional recursion by explicitly calling
6233 // VisitChildren(). We will need to remove this explicit recursive call.
6236 // If we ran into any entities that involve context-sensitive keywords,
6237 // take another pass through the tokens to mark them as such.
6238 if (W.hasContextSensitiveKeywords()) {
6239 for (unsigned I = 0; I != NumTokens; ++I) {
6240 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6243 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6244 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6245 if (const ObjCPropertyDecl *Property
6246 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6247 if (Property->getPropertyAttributesAsWritten() != 0 &&
6248 llvm::StringSwitch<bool>(II->getName())
6249 .Case("readonly", true)
6250 .Case("assign", true)
6251 .Case("unsafe_unretained", true)
6252 .Case("readwrite", true)
6253 .Case("retain", true)
6255 .Case("nonatomic", true)
6256 .Case("atomic", true)
6257 .Case("getter", true)
6258 .Case("setter", true)
6259 .Case("strong", true)
6262 Tokens[I].int_data[0] = CXToken_Keyword;
6267 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6268 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6269 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6270 if (llvm::StringSwitch<bool>(II->getName())
6273 .Case("inout", true)
6274 .Case("oneway", true)
6275 .Case("bycopy", true)
6276 .Case("byref", true)
6278 Tokens[I].int_data[0] = CXToken_Keyword;
6282 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6283 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6284 Tokens[I].int_data[0] = CXToken_Keyword;
6293 void clang_annotateTokens(CXTranslationUnit TU,
6294 CXToken *Tokens, unsigned NumTokens,
6295 CXCursor *Cursors) {
6296 if (isNotUsableTU(TU)) {
6300 if (NumTokens == 0 || !Tokens || !Cursors) {
6301 LOG_FUNC_SECTION { *Log << "<null input>"; }
6307 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6308 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6309 *Log << clang_getRange(bloc, eloc);
6312 // Any token we don't specifically annotate will have a NULL cursor.
6313 CXCursor C = clang_getNullCursor();
6314 for (unsigned I = 0; I != NumTokens; ++I)
6317 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6321 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6323 auto AnnotateTokensImpl = [=]() {
6324 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6326 llvm::CrashRecoveryContext CRC;
6327 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6328 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6332 } // end: extern "C"
6334 //===----------------------------------------------------------------------===//
6335 // Operations for querying linkage of a cursor.
6336 //===----------------------------------------------------------------------===//
6339 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6340 if (!clang_isDeclaration(cursor.kind))
6341 return CXLinkage_Invalid;
6343 const Decl *D = cxcursor::getCursorDecl(cursor);
6344 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6345 switch (ND->getLinkageInternal()) {
6347 case VisibleNoLinkage: return CXLinkage_NoLinkage;
6348 case InternalLinkage: return CXLinkage_Internal;
6349 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6350 case ExternalLinkage: return CXLinkage_External;
6353 return CXLinkage_Invalid;
6355 } // end: extern "C"
6357 //===----------------------------------------------------------------------===//
6358 // Operations for querying language of a cursor.
6359 //===----------------------------------------------------------------------===//
6361 static CXLanguageKind getDeclLanguage(const Decl *D) {
6363 return CXLanguage_C;
6365 switch (D->getKind()) {
6368 case Decl::ImplicitParam:
6369 case Decl::ObjCAtDefsField:
6370 case Decl::ObjCCategory:
6371 case Decl::ObjCCategoryImpl:
6372 case Decl::ObjCCompatibleAlias:
6373 case Decl::ObjCImplementation:
6374 case Decl::ObjCInterface:
6375 case Decl::ObjCIvar:
6376 case Decl::ObjCMethod:
6377 case Decl::ObjCProperty:
6378 case Decl::ObjCPropertyImpl:
6379 case Decl::ObjCProtocol:
6380 case Decl::ObjCTypeParam:
6381 return CXLanguage_ObjC;
6382 case Decl::CXXConstructor:
6383 case Decl::CXXConversion:
6384 case Decl::CXXDestructor:
6385 case Decl::CXXMethod:
6386 case Decl::CXXRecord:
6387 case Decl::ClassTemplate:
6388 case Decl::ClassTemplatePartialSpecialization:
6389 case Decl::ClassTemplateSpecialization:
6391 case Decl::FriendTemplate:
6392 case Decl::FunctionTemplate:
6393 case Decl::LinkageSpec:
6394 case Decl::Namespace:
6395 case Decl::NamespaceAlias:
6396 case Decl::NonTypeTemplateParm:
6397 case Decl::StaticAssert:
6398 case Decl::TemplateTemplateParm:
6399 case Decl::TemplateTypeParm:
6400 case Decl::UnresolvedUsingTypename:
6401 case Decl::UnresolvedUsingValue:
6403 case Decl::UsingDirective:
6404 case Decl::UsingShadow:
6405 return CXLanguage_CPlusPlus;
6408 return CXLanguage_C;
6413 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6414 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6415 return CXAvailability_NotAvailable;
6417 switch (D->getAvailability()) {
6419 case AR_NotYetIntroduced:
6420 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6421 return getCursorAvailabilityForDecl(
6422 cast<Decl>(EnumConst->getDeclContext()));
6423 return CXAvailability_Available;
6426 return CXAvailability_Deprecated;
6428 case AR_Unavailable:
6429 return CXAvailability_NotAvailable;
6432 llvm_unreachable("Unknown availability kind!");
6435 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6436 if (clang_isDeclaration(cursor.kind))
6437 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6438 return getCursorAvailabilityForDecl(D);
6440 return CXAvailability_Available;
6443 static CXVersion convertVersion(VersionTuple In) {
6444 CXVersion Out = { -1, -1, -1 };
6448 Out.Major = In.getMajor();
6450 Optional<unsigned> Minor = In.getMinor();
6451 if (Minor.hasValue())
6456 Optional<unsigned> Subminor = In.getSubminor();
6457 if (Subminor.hasValue())
6458 Out.Subminor = *Subminor;
6463 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6464 int *always_deprecated,
6465 CXString *deprecated_message,
6466 int *always_unavailable,
6467 CXString *unavailable_message,
6468 CXPlatformAvailability *availability,
6469 int availability_size) {
6470 bool HadAvailAttr = false;
6472 for (auto A : D->attrs()) {
6473 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6474 HadAvailAttr = true;
6475 if (always_deprecated)
6476 *always_deprecated = 1;
6477 if (deprecated_message) {
6478 clang_disposeString(*deprecated_message);
6479 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6484 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6485 HadAvailAttr = true;
6486 if (always_unavailable)
6487 *always_unavailable = 1;
6488 if (unavailable_message) {
6489 clang_disposeString(*unavailable_message);
6490 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6495 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6496 HadAvailAttr = true;
6497 if (N < availability_size) {
6498 availability[N].Platform
6499 = cxstring::createDup(Avail->getPlatform()->getName());
6500 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6501 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6502 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6503 availability[N].Unavailable = Avail->getUnavailable();
6504 availability[N].Message = cxstring::createDup(Avail->getMessage());
6511 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6512 return getCursorPlatformAvailabilityForDecl(
6513 cast<Decl>(EnumConst->getDeclContext()),
6517 unavailable_message,
6524 int clang_getCursorPlatformAvailability(CXCursor cursor,
6525 int *always_deprecated,
6526 CXString *deprecated_message,
6527 int *always_unavailable,
6528 CXString *unavailable_message,
6529 CXPlatformAvailability *availability,
6530 int availability_size) {
6531 if (always_deprecated)
6532 *always_deprecated = 0;
6533 if (deprecated_message)
6534 *deprecated_message = cxstring::createEmpty();
6535 if (always_unavailable)
6536 *always_unavailable = 0;
6537 if (unavailable_message)
6538 *unavailable_message = cxstring::createEmpty();
6540 if (!clang_isDeclaration(cursor.kind))
6543 const Decl *D = cxcursor::getCursorDecl(cursor);
6547 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
6550 unavailable_message,
6555 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
6556 clang_disposeString(availability->Platform);
6557 clang_disposeString(availability->Message);
6560 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
6561 if (clang_isDeclaration(cursor.kind))
6562 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
6564 return CXLanguage_Invalid;
6567 /// \brief If the given cursor is the "templated" declaration
6568 /// descibing a class or function template, return the class or
6569 /// function template.
6570 static const Decl *maybeGetTemplateCursor(const Decl *D) {
6574 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6575 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
6578 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6579 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
6586 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
6587 StorageClass sc = SC_None;
6588 const Decl *D = getCursorDecl(C);
6590 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6591 sc = FD->getStorageClass();
6592 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6593 sc = VD->getStorageClass();
6595 return CX_SC_Invalid;
6598 return CX_SC_Invalid;
6604 return CX_SC_Extern;
6606 return CX_SC_Static;
6607 case SC_PrivateExtern:
6608 return CX_SC_PrivateExtern;
6612 return CX_SC_Register;
6614 llvm_unreachable("Unhandled storage class!");
6617 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
6618 if (clang_isDeclaration(cursor.kind)) {
6619 if (const Decl *D = getCursorDecl(cursor)) {
6620 const DeclContext *DC = D->getDeclContext();
6622 return clang_getNullCursor();
6624 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6625 getCursorTU(cursor));
6629 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
6630 if (const Decl *D = getCursorDecl(cursor))
6631 return MakeCXCursor(D, getCursorTU(cursor));
6634 return clang_getNullCursor();
6637 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
6638 if (clang_isDeclaration(cursor.kind)) {
6639 if (const Decl *D = getCursorDecl(cursor)) {
6640 const DeclContext *DC = D->getLexicalDeclContext();
6642 return clang_getNullCursor();
6644 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6645 getCursorTU(cursor));
6649 // FIXME: Note that we can't easily compute the lexical context of a
6650 // statement or expression, so we return nothing.
6651 return clang_getNullCursor();
6654 CXFile clang_getIncludedFile(CXCursor cursor) {
6655 if (cursor.kind != CXCursor_InclusionDirective)
6658 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
6659 return const_cast<FileEntry *>(ID->getFile());
6662 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
6663 if (C.kind != CXCursor_ObjCPropertyDecl)
6664 return CXObjCPropertyAttr_noattr;
6666 unsigned Result = CXObjCPropertyAttr_noattr;
6667 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
6668 ObjCPropertyDecl::PropertyAttributeKind Attr =
6669 PD->getPropertyAttributesAsWritten();
6671 #define SET_CXOBJCPROP_ATTR(A) \
6672 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
6673 Result |= CXObjCPropertyAttr_##A
6674 SET_CXOBJCPROP_ATTR(readonly);
6675 SET_CXOBJCPROP_ATTR(getter);
6676 SET_CXOBJCPROP_ATTR(assign);
6677 SET_CXOBJCPROP_ATTR(readwrite);
6678 SET_CXOBJCPROP_ATTR(retain);
6679 SET_CXOBJCPROP_ATTR(copy);
6680 SET_CXOBJCPROP_ATTR(nonatomic);
6681 SET_CXOBJCPROP_ATTR(setter);
6682 SET_CXOBJCPROP_ATTR(atomic);
6683 SET_CXOBJCPROP_ATTR(weak);
6684 SET_CXOBJCPROP_ATTR(strong);
6685 SET_CXOBJCPROP_ATTR(unsafe_unretained);
6686 #undef SET_CXOBJCPROP_ATTR
6691 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
6692 if (!clang_isDeclaration(C.kind))
6693 return CXObjCDeclQualifier_None;
6695 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
6696 const Decl *D = getCursorDecl(C);
6697 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6698 QT = MD->getObjCDeclQualifier();
6699 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
6700 QT = PD->getObjCDeclQualifier();
6701 if (QT == Decl::OBJC_TQ_None)
6702 return CXObjCDeclQualifier_None;
6704 unsigned Result = CXObjCDeclQualifier_None;
6705 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
6706 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
6707 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
6708 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
6709 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
6710 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
6715 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
6716 if (!clang_isDeclaration(C.kind))
6719 const Decl *D = getCursorDecl(C);
6720 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
6721 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
6722 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6723 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
6728 unsigned clang_Cursor_isVariadic(CXCursor C) {
6729 if (!clang_isDeclaration(C.kind))
6732 const Decl *D = getCursorDecl(C);
6733 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6734 return FD->isVariadic();
6735 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6736 return MD->isVariadic();
6741 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
6742 if (!clang_isDeclaration(C.kind))
6743 return clang_getNullRange();
6745 const Decl *D = getCursorDecl(C);
6746 ASTContext &Context = getCursorContext(C);
6747 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6749 return clang_getNullRange();
6751 return cxloc::translateSourceRange(Context, RC->getSourceRange());
6754 CXString clang_Cursor_getRawCommentText(CXCursor C) {
6755 if (!clang_isDeclaration(C.kind))
6756 return cxstring::createNull();
6758 const Decl *D = getCursorDecl(C);
6759 ASTContext &Context = getCursorContext(C);
6760 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6761 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
6764 // Don't duplicate the string because RawText points directly into source
6766 return cxstring::createRef(RawText);
6769 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
6770 if (!clang_isDeclaration(C.kind))
6771 return cxstring::createNull();
6773 const Decl *D = getCursorDecl(C);
6774 const ASTContext &Context = getCursorContext(C);
6775 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6778 StringRef BriefText = RC->getBriefText(Context);
6780 // Don't duplicate the string because RawComment ensures that this memory
6781 // will not go away.
6782 return cxstring::createRef(BriefText);
6785 return cxstring::createNull();
6788 CXModule clang_Cursor_getModule(CXCursor C) {
6789 if (C.kind == CXCursor_ModuleImportDecl) {
6790 if (const ImportDecl *ImportD =
6791 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
6792 return ImportD->getImportedModule();
6798 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
6799 if (isNotUsableTU(TU)) {
6805 FileEntry *FE = static_cast<FileEntry *>(File);
6807 ASTUnit &Unit = *cxtu::getASTUnit(TU);
6808 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
6809 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
6811 return Header.getModule();
6814 CXFile clang_Module_getASTFile(CXModule CXMod) {
6817 Module *Mod = static_cast<Module*>(CXMod);
6818 return const_cast<FileEntry *>(Mod->getASTFile());
6821 CXModule clang_Module_getParent(CXModule CXMod) {
6824 Module *Mod = static_cast<Module*>(CXMod);
6828 CXString clang_Module_getName(CXModule CXMod) {
6830 return cxstring::createEmpty();
6831 Module *Mod = static_cast<Module*>(CXMod);
6832 return cxstring::createDup(Mod->Name);
6835 CXString clang_Module_getFullName(CXModule CXMod) {
6837 return cxstring::createEmpty();
6838 Module *Mod = static_cast<Module*>(CXMod);
6839 return cxstring::createDup(Mod->getFullModuleName());
6842 int clang_Module_isSystem(CXModule CXMod) {
6845 Module *Mod = static_cast<Module*>(CXMod);
6846 return Mod->IsSystem;
6849 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
6851 if (isNotUsableTU(TU)) {
6857 Module *Mod = static_cast<Module*>(CXMod);
6858 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6859 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6860 return TopHeaders.size();
6863 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
6864 CXModule CXMod, unsigned Index) {
6865 if (isNotUsableTU(TU)) {
6871 Module *Mod = static_cast<Module*>(CXMod);
6872 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6874 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6875 if (Index < TopHeaders.size())
6876 return const_cast<FileEntry *>(TopHeaders[Index]);
6881 } // end: extern "C"
6883 //===----------------------------------------------------------------------===//
6884 // C++ AST instrospection.
6885 //===----------------------------------------------------------------------===//
6888 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
6889 if (!clang_isDeclaration(C.kind))
6892 const Decl *D = cxcursor::getCursorDecl(C);
6893 const CXXMethodDecl *Method =
6894 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6895 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
6898 unsigned clang_CXXMethod_isConst(CXCursor C) {
6899 if (!clang_isDeclaration(C.kind))
6902 const Decl *D = cxcursor::getCursorDecl(C);
6903 const CXXMethodDecl *Method =
6904 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6905 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
6908 unsigned clang_CXXMethod_isStatic(CXCursor C) {
6909 if (!clang_isDeclaration(C.kind))
6912 const Decl *D = cxcursor::getCursorDecl(C);
6913 const CXXMethodDecl *Method =
6914 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6915 return (Method && Method->isStatic()) ? 1 : 0;
6918 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
6919 if (!clang_isDeclaration(C.kind))
6922 const Decl *D = cxcursor::getCursorDecl(C);
6923 const CXXMethodDecl *Method =
6924 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6925 return (Method && Method->isVirtual()) ? 1 : 0;
6927 } // end: extern "C"
6929 //===----------------------------------------------------------------------===//
6930 // Attribute introspection.
6931 //===----------------------------------------------------------------------===//
6934 CXType clang_getIBOutletCollectionType(CXCursor C) {
6935 if (C.kind != CXCursor_IBOutletCollectionAttr)
6936 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
6938 const IBOutletCollectionAttr *A =
6939 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
6941 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
6943 } // end: extern "C"
6945 //===----------------------------------------------------------------------===//
6946 // Inspecting memory usage.
6947 //===----------------------------------------------------------------------===//
6949 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
6951 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
6952 enum CXTUResourceUsageKind k,
6953 unsigned long amount) {
6954 CXTUResourceUsageEntry entry = { k, amount };
6955 entries.push_back(entry);
6960 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
6961 const char *str = "";
6963 case CXTUResourceUsage_AST:
6964 str = "ASTContext: expressions, declarations, and types";
6966 case CXTUResourceUsage_Identifiers:
6967 str = "ASTContext: identifiers";
6969 case CXTUResourceUsage_Selectors:
6970 str = "ASTContext: selectors";
6972 case CXTUResourceUsage_GlobalCompletionResults:
6973 str = "Code completion: cached global results";
6975 case CXTUResourceUsage_SourceManagerContentCache:
6976 str = "SourceManager: content cache allocator";
6978 case CXTUResourceUsage_AST_SideTables:
6979 str = "ASTContext: side tables";
6981 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
6982 str = "SourceManager: malloc'ed memory buffers";
6984 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
6985 str = "SourceManager: mmap'ed memory buffers";
6987 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6988 str = "ExternalASTSource: malloc'ed memory buffers";
6990 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6991 str = "ExternalASTSource: mmap'ed memory buffers";
6993 case CXTUResourceUsage_Preprocessor:
6994 str = "Preprocessor: malloc'ed memory";
6996 case CXTUResourceUsage_PreprocessingRecord:
6997 str = "Preprocessor: PreprocessingRecord";
6999 case CXTUResourceUsage_SourceManager_DataStructures:
7000 str = "SourceManager: data structures and tables";
7002 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7003 str = "Preprocessor: header search tables";
7009 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7010 if (isNotUsableTU(TU)) {
7012 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7016 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7017 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7018 ASTContext &astContext = astUnit->getASTContext();
7020 // How much memory is used by AST nodes and types?
7021 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7022 (unsigned long) astContext.getASTAllocatedMemory());
7024 // How much memory is used by identifiers?
7025 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7026 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7028 // How much memory is used for selectors?
7029 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7030 (unsigned long) astContext.Selectors.getTotalMemory());
7032 // How much memory is used by ASTContext's side tables?
7033 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7034 (unsigned long) astContext.getSideTableAllocatedMemory());
7036 // How much memory is used for caching global code completion results?
7037 unsigned long completionBytes = 0;
7038 if (GlobalCodeCompletionAllocator *completionAllocator =
7039 astUnit->getCachedCompletionAllocator().get()) {
7040 completionBytes = completionAllocator->getTotalMemory();
7042 createCXTUResourceUsageEntry(*entries,
7043 CXTUResourceUsage_GlobalCompletionResults,
7046 // How much memory is being used by SourceManager's content cache?
7047 createCXTUResourceUsageEntry(*entries,
7048 CXTUResourceUsage_SourceManagerContentCache,
7049 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7051 // How much memory is being used by the MemoryBuffer's in SourceManager?
7052 const SourceManager::MemoryBufferSizes &srcBufs =
7053 astUnit->getSourceManager().getMemoryBufferSizes();
7055 createCXTUResourceUsageEntry(*entries,
7056 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7057 (unsigned long) srcBufs.malloc_bytes);
7058 createCXTUResourceUsageEntry(*entries,
7059 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7060 (unsigned long) srcBufs.mmap_bytes);
7061 createCXTUResourceUsageEntry(*entries,
7062 CXTUResourceUsage_SourceManager_DataStructures,
7063 (unsigned long) astContext.getSourceManager()
7064 .getDataStructureSizes());
7066 // How much memory is being used by the ExternalASTSource?
7067 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7068 const ExternalASTSource::MemoryBufferSizes &sizes =
7069 esrc->getMemoryBufferSizes();
7071 createCXTUResourceUsageEntry(*entries,
7072 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7073 (unsigned long) sizes.malloc_bytes);
7074 createCXTUResourceUsageEntry(*entries,
7075 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7076 (unsigned long) sizes.mmap_bytes);
7079 // How much memory is being used by the Preprocessor?
7080 Preprocessor &pp = astUnit->getPreprocessor();
7081 createCXTUResourceUsageEntry(*entries,
7082 CXTUResourceUsage_Preprocessor,
7083 pp.getTotalMemory());
7085 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7086 createCXTUResourceUsageEntry(*entries,
7087 CXTUResourceUsage_PreprocessingRecord,
7088 pRec->getTotalMemory());
7091 createCXTUResourceUsageEntry(*entries,
7092 CXTUResourceUsage_Preprocessor_HeaderSearch,
7093 pp.getHeaderSearchInfo().getTotalMemory());
7095 CXTUResourceUsage usage = { (void*) entries.get(),
7096 (unsigned) entries->size(),
7097 !entries->empty() ? &(*entries)[0] : nullptr };
7102 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7104 delete (MemUsageEntries*) usage.data;
7107 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7108 CXSourceRangeList *skipped = new CXSourceRangeList;
7110 skipped->ranges = nullptr;
7112 if (isNotUsableTU(TU)) {
7120 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7121 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7125 ASTContext &Ctx = astUnit->getASTContext();
7126 SourceManager &sm = Ctx.getSourceManager();
7127 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7128 FileID wantedFileID = sm.translateFile(fileEntry);
7130 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7131 std::vector<SourceRange> wantedRanges;
7132 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7134 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7135 wantedRanges.push_back(*i);
7138 skipped->count = wantedRanges.size();
7139 skipped->ranges = new CXSourceRange[skipped->count];
7140 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7141 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7146 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7148 delete[] ranges->ranges;
7155 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7156 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7157 for (unsigned I = 0; I != Usage.numEntries; ++I)
7158 fprintf(stderr, " %s: %lu\n",
7159 clang_getTUResourceUsageName(Usage.entries[I].kind),
7160 Usage.entries[I].amount);
7162 clang_disposeCXTUResourceUsage(Usage);
7165 //===----------------------------------------------------------------------===//
7166 // Misc. utility functions.
7167 //===----------------------------------------------------------------------===//
7169 /// Default to using an 8 MB stack size on "safety" threads.
7170 static unsigned SafetyStackThreadSize = 8 << 20;
7174 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7177 Size = GetSafetyThreadStackSize();
7179 return CRC.RunSafelyOnThread(Fn, Size);
7180 return CRC.RunSafely(Fn);
7183 unsigned GetSafetyThreadStackSize() {
7184 return SafetyStackThreadSize;
7187 void SetSafetyThreadStackSize(unsigned Value) {
7188 SafetyStackThreadSize = Value;
7193 void clang::setThreadBackgroundPriority() {
7194 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7197 #ifdef USE_DARWIN_THREADS
7198 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7202 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7206 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7207 DEnd = Unit->stored_diag_end();
7209 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7210 CXString Msg = clang_formatDiagnostic(&Diag,
7211 clang_defaultDiagnosticDisplayOptions());
7212 fprintf(stderr, "%s\n", clang_getCString(Msg));
7213 clang_disposeString(Msg);
7215 #ifdef LLVM_ON_WIN32
7216 // On Windows, force a flush, since there may be multiple copies of
7217 // stderr and stdout in the file system, all with different buffers
7218 // but writing to the same device.
7223 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7224 SourceLocation MacroDefLoc,
7225 CXTranslationUnit TU){
7226 if (MacroDefLoc.isInvalid() || !TU)
7228 if (!II.hadMacroDefinition())
7231 ASTUnit *Unit = cxtu::getASTUnit(TU);
7232 Preprocessor &PP = Unit->getPreprocessor();
7233 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7235 for (MacroDirective::DefInfo
7236 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7237 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7238 return Def.getMacroInfo();
7245 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7246 CXTranslationUnit TU) {
7247 if (!MacroDef || !TU)
7249 const IdentifierInfo *II = MacroDef->getName();
7253 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7256 MacroDefinitionRecord *
7257 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7258 CXTranslationUnit TU) {
7261 if (Tok.isNot(tok::raw_identifier))
7264 if (MI->getNumTokens() == 0)
7266 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7267 MI->getDefinitionEndLoc());
7268 ASTUnit *Unit = cxtu::getASTUnit(TU);
7270 // Check that the token is inside the definition and not its argument list.
7271 SourceManager &SM = Unit->getSourceManager();
7272 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7274 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7277 Preprocessor &PP = Unit->getPreprocessor();
7278 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7282 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7283 if (!II.hadMacroDefinition())
7286 // Check that the identifier is not one of the macro arguments.
7287 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7290 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7294 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7297 MacroDefinitionRecord *
7298 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7299 CXTranslationUnit TU) {
7300 if (Loc.isInvalid() || !MI || !TU)
7303 if (MI->getNumTokens() == 0)
7305 ASTUnit *Unit = cxtu::getASTUnit(TU);
7306 Preprocessor &PP = Unit->getPreprocessor();
7307 if (!PP.getPreprocessingRecord())
7309 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7311 if (PP.getRawToken(Loc, Tok))
7314 return checkForMacroInMacroDefinition(MI, Tok, TU);
7319 CXString clang_getClangVersion() {
7320 return cxstring::createDup(getClangFullVersion());
7323 } // end: extern "C"
7325 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7327 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7328 LogOS << '<' << Unit->getMainFileName() << '>';
7329 if (Unit->isMainFileAST())
7330 LogOS << " (" << Unit->getASTFileName() << ')';
7334 LogOS << "<NULL TU>";
7339 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7340 *this << FE->getName();
7344 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7345 CXString cursorName = clang_getCursorDisplayName(cursor);
7346 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7347 clang_disposeString(cursorName);
7351 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7353 unsigned Line, Column;
7354 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7355 CXString FileName = clang_getFileName(File);
7356 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7357 clang_disposeString(FileName);
7361 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7362 CXSourceLocation BLoc = clang_getRangeStart(range);
7363 CXSourceLocation ELoc = clang_getRangeEnd(range);
7366 unsigned BLine, BColumn;
7367 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7370 unsigned ELine, EColumn;
7371 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7373 CXString BFileName = clang_getFileName(BFile);
7374 if (BFile == EFile) {
7375 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7376 BLine, BColumn, ELine, EColumn);
7378 CXString EFileName = clang_getFileName(EFile);
7379 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7381 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7383 clang_disposeString(EFileName);
7385 clang_disposeString(BFileName);
7389 Logger &cxindex::Logger::operator<<(CXString Str) {
7390 *this << clang_getCString(Str);
7394 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7399 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7401 cxindex::Logger::~Logger() {
7402 llvm::sys::ScopedLock L(*LoggingMutex);
7404 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7406 raw_ostream &OS = llvm::errs();
7407 OS << "[libclang:" << Name << ':';
7409 #ifdef USE_DARWIN_THREADS
7410 // TODO: Portability.
7411 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7415 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7416 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7420 llvm::sys::PrintStackTrace(OS);
7421 OS << "--------------------------------------------------\n";