HELLO·Android
系统源代码
IT资讯
技术文章
我的收藏
注册
登录
-
我收藏的文章
创建代码块
我的代码块
我的账号
Android 10
|
10.0.0_r6
下载
查看原文件
收藏
根目录
external
clang
tools
libclang
CIndex.cpp
//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the main API hooks in the Clang-C Source Indexing // library. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CIndexDiagnostic.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "CXType.h" #include "CursorVisitor.h" #include "clang/AST/Attr.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticCategories.h" #include "clang/Basic/DiagnosticIDs.h" #include "clang/Basic/Version.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Index/CodegenNameGenerator.h" #include "clang/Index/CommentToXML.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" #include "clang/Serialization/SerializationDiagnostic.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Program.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Threading.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) #define USE_DARWIN_THREADS #endif #ifdef USE_DARWIN_THREADS #include
#endif using namespace clang; using namespace clang::cxcursor; using namespace clang::cxtu; using namespace clang::cxindex; CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) { if (!AU) return nullptr; assert(CIdx); CXTranslationUnit D = new CXTranslationUnitImpl(); D->CIdx = CIdx; D->TheASTUnit = AU; D->StringPool = new cxstring::CXStringPool(); D->Diagnostics = nullptr; D->OverridenCursorsPool = createOverridenCXCursorsPool(); D->CommentToXML = nullptr; return D; } bool cxtu::isASTReadError(ASTUnit *AU) { for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), DEnd = AU->stored_diag_end(); D != DEnd; ++D) { if (D->getLevel() >= DiagnosticsEngine::Error && DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == diag::DiagCat_AST_Deserialization_Issue) return true; } return false; } cxtu::CXTUOwner::~CXTUOwner() { if (TU) clang_disposeTranslationUnit(TU); } /// \brief Compare two source ranges to determine their relative position in /// the translation unit. static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1, SourceRange R2) { assert(R1.isValid() && "First range is invalid?"); assert(R2.isValid() && "Second range is invalid?"); if (R1.getEnd() != R2.getBegin() && SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) return RangeBefore; if (R2.getEnd() != R1.getBegin() && SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) return RangeAfter; return RangeOverlap; } /// \brief Determine if a source location falls within, before, or after a /// a given source range. static RangeComparisonResult LocationCompare(SourceManager &SM, SourceLocation L, SourceRange R) { assert(R.isValid() && "First range is invalid?"); assert(L.isValid() && "Second range is invalid?"); if (L == R.getBegin() || L == R.getEnd()) return RangeOverlap; if (SM.isBeforeInTranslationUnit(L, R.getBegin())) return RangeBefore; if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) return RangeAfter; return RangeOverlap; } /// \brief Translate a Clang source range into a CIndex source range. /// /// Clang internally represents ranges where the end location points to the /// start of the token at the end. However, for external clients it is more /// useful to have a CXSourceRange be a proper half-open interval. This routine /// does the appropriate translation. CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, const LangOptions &LangOpts, const CharSourceRange &R) { // We want the last character in this location, so we will adjust the // location accordingly. SourceLocation EndLoc = R.getEnd(); if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) EndLoc = SM.getExpansionRange(EndLoc).second; if (R.isTokenRange() && EndLoc.isValid()) { unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts); EndLoc = EndLoc.getLocWithOffset(Length); } CXSourceRange Result = { { &SM, &LangOpts }, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding() }; return Result; } //===----------------------------------------------------------------------===// // Cursor visitor. //===----------------------------------------------------------------------===// static SourceRange getRawCursorExtent(CXCursor C); static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); } /// \brief Visit the given cursor and, if requested by the visitor, /// its children. /// /// \param Cursor the cursor to visit. /// /// \param CheckedRegionOfInterest if true, then the caller already checked /// that this cursor is within the region of interest. /// /// \returns true if the visitation should be aborted, false if it /// should continue. bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { if (clang_isInvalid(Cursor.kind)) return false; if (clang_isDeclaration(Cursor.kind)) { const Decl *D = getCursorDecl(Cursor); if (!D) { assert(0 && "Invalid declaration cursor"); return true; // abort. } // Ignore implicit declarations, unless it's an objc method because // currently we should report implicit methods for properties when indexing. if (D->isImplicit() && !isa
(D)) return false; } // If we have a range of interest, and this cursor doesn't intersect with it, // we're done. if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { SourceRange Range = getRawCursorExtent(Cursor); if (Range.isInvalid() || CompareRegionOfInterest(Range)) return false; } switch (Visitor(Cursor, Parent, ClientData)) { case CXChildVisit_Break: return true; case CXChildVisit_Continue: return false; case CXChildVisit_Recurse: { bool ret = VisitChildren(Cursor); if (PostChildrenVisitor) if (PostChildrenVisitor(Cursor, ClientData)) return true; return ret; } } llvm_unreachable("Invalid CXChildVisitResult!"); } static bool visitPreprocessedEntitiesInRange(SourceRange R, PreprocessingRecord &PPRec, CursorVisitor &Visitor) { SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); FileID FID; if (!Visitor.shouldVisitIncludedEntities()) { // If the begin/end of the range lie in the same FileID, do the optimization // where we skip preprocessed entities that do not come from the same FileID. FID = SM.getFileID(SM.getFileLoc(R.getBegin())); if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) FID = FileID(); } const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), PPRec, FID); } bool CursorVisitor::visitFileRegion() { if (RegionOfInterest.isInvalid()) return false; ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); std::pair
Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); if (End.first != Begin.first) { // If the end does not reside in the same file, try to recover by // picking the end of the file of begin location. End.first = Begin.first; End.second = SM.getFileIDSize(Begin.first); } assert(Begin.first == End.first); if (Begin.second > End.second) return false; FileID File = Begin.first; unsigned Offset = Begin.second; unsigned Length = End.second - Begin.second; if (!VisitDeclsOnly && !VisitPreprocessorLast) if (visitPreprocessedEntitiesInRegion()) return true; // visitation break. if (visitDeclsFromFileRegion(File, Offset, Length)) return true; // visitation break. if (!VisitDeclsOnly && VisitPreprocessorLast) return visitPreprocessedEntitiesInRegion(); return false; } static bool isInLexicalContext(Decl *D, DeclContext *DC) { if (!DC) return false; for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC; DeclDC = DeclDC->getLexicalParent()) { if (DeclDC == DC) return true; } return false; } bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset, unsigned Length) { ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); SourceRange Range = RegionOfInterest; SmallVector
Decls; Unit->findFileRegionDecls(File, Offset, Length, Decls); // If we didn't find any file level decls for the file, try looking at the // file that it was included from. while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { bool Invalid = false; const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); if (Invalid) return false; SourceLocation Outer; if (SLEntry.isFile()) Outer = SLEntry.getFile().getIncludeLoc(); else Outer = SLEntry.getExpansion().getExpansionLocStart(); if (Outer.isInvalid()) return false; std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); Length = 0; Unit->findFileRegionDecls(File, Offset, Length, Decls); } assert(!Decls.empty()); bool VisitedAtLeastOnce = false; DeclContext *CurDC = nullptr; SmallVectorImpl
::iterator DIt = Decls.begin(); for (SmallVectorImpl
::iterator DE = Decls.end(); DIt != DE; ++DIt) { Decl *D = *DIt; if (D->getSourceRange().isInvalid()) continue; if (isInLexicalContext(D, CurDC)) continue; CurDC = dyn_cast
(D); if (TagDecl *TD = dyn_cast
(D)) if (!TD->isFreeStanding()) continue; RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); if (CompRes == RangeBefore) continue; if (CompRes == RangeAfter) break; assert(CompRes == RangeOverlap); VisitedAtLeastOnce = true; if (isa
(D)) { FileDI_current = &DIt; FileDE_current = DE; } else { FileDI_current = nullptr; } if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) return true; // visitation break. } if (VisitedAtLeastOnce) return false; // No Decls overlapped with the range. Move up the lexical context until there // is a context that contains the range or we reach the translation unit // level. DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() : (*(DIt-1))->getLexicalDeclContext(); while (DC && !DC->isTranslationUnit()) { Decl *D = cast
(DC); SourceRange CurDeclRange = D->getSourceRange(); if (CurDeclRange.isInvalid()) break; if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) return true; // visitation break. } DC = D->getLexicalDeclContext(); } return false; } bool CursorVisitor::visitPreprocessedEntitiesInRegion() { if (!AU->getPreprocessor().getPreprocessingRecord()) return false; PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord(); SourceManager &SM = AU->getSourceManager(); if (RegionOfInterest.isValid()) { SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); SourceLocation B = MappedRange.getBegin(); SourceLocation E = MappedRange.getEnd(); if (AU->isInPreambleFileID(B)) { if (SM.isLoadedSourceLocation(E)) return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); // Beginning of range lies in the preamble but it also extends beyond // it into the main file. Split the range into 2 parts, one covering // the preamble and another covering the main file. This allows subsequent // calls to visitPreprocessedEntitiesInRange to accept a source range that // lies in the same FileID, allowing it to skip preprocessed entities that // do not come from the same FileID. bool breaked = visitPreprocessedEntitiesInRange( SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this); if (breaked) return true; return visitPreprocessedEntitiesInRange( SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this); } return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); } bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); if (OnlyLocalDecls) return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), PPRec); return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); } template
bool CursorVisitor::visitPreprocessedEntities(InputIterator First, InputIterator Last, PreprocessingRecord &PPRec, FileID FID) { for (; First != Last; ++First) { if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) continue; PreprocessedEntity *PPE = *First; if (!PPE) continue; if (MacroExpansion *ME = dyn_cast
(PPE)) { if (Visit(MakeMacroExpansionCursor(ME, TU))) return true; continue; } if (MacroDefinitionRecord *MD = dyn_cast
(PPE)) { if (Visit(MakeMacroDefinitionCursor(MD, TU))) return true; continue; } if (InclusionDirective *ID = dyn_cast
(PPE)) { if (Visit(MakeInclusionDirectiveCursor(ID, TU))) return true; continue; } } return false; } /// \brief Visit the children of the given cursor. /// /// \returns true if the visitation should be aborted, false if it /// should continue. bool CursorVisitor::VisitChildren(CXCursor Cursor) { if (clang_isReference(Cursor.kind) && Cursor.kind != CXCursor_CXXBaseSpecifier) { // By definition, references have no children. return false; } // Set the Parent field to Cursor, then back to its old value once we're // done. SetParentRAII SetParent(Parent, StmtParent, Cursor); if (clang_isDeclaration(Cursor.kind)) { Decl *D = const_cast
(getCursorDecl(Cursor)); if (!D) return false; return VisitAttributes(D) || Visit(D); } if (clang_isStatement(Cursor.kind)) { if (const Stmt *S = getCursorStmt(Cursor)) return Visit(S); return false; } if (clang_isExpression(Cursor.kind)) { if (const Expr *E = getCursorExpr(Cursor)) return Visit(E); return false; } if (clang_isTranslationUnit(Cursor.kind)) { CXTranslationUnit TU = getCursorTU(Cursor); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; for (unsigned I = 0; I != 2; ++I) { if (VisitOrder[I]) { if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && RegionOfInterest.isInvalid()) { for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), TLEnd = CXXUnit->top_level_end(); TL != TLEnd; ++TL) { const Optional
V = handleDeclForVisitation(*TL); if (!V.hasValue()) continue; return V.getValue(); } } else if (VisitDeclContext( CXXUnit->getASTContext().getTranslationUnitDecl())) return true; continue; } // Walk the preprocessing record. if (CXXUnit->getPreprocessor().getPreprocessingRecord()) visitPreprocessedEntitiesInRegion(); } return false; } if (Cursor.kind == CXCursor_CXXBaseSpecifier) { if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { return Visit(BaseTSInfo->getTypeLoc()); } } } if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { const IBOutletCollectionAttr *A = cast
(cxcursor::getCursorAttr(Cursor)); if (const ObjCObjectType *ObjT = A->getInterface()->getAs
()) return Visit(cxcursor::MakeCursorObjCClassRef( ObjT->getInterface(), A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU)); } // If pointing inside a macro definition, check if the token is an identifier // that was ever defined as a macro. In such a case, create a "pseudo" macro // expansion cursor for that token. SourceLocation BeginLoc = RegionOfInterest.getBegin(); if (Cursor.kind == CXCursor_MacroDefinition && BeginLoc == RegionOfInterest.getEnd()) { SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); const MacroInfo *MI = getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); if (MacroDefinitionRecord *MacroDef = checkForMacroInMacroDefinition(MI, Loc, TU)) return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); } // Nothing to visit at the moment. return false; } bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) if (Visit(TSInfo->getTypeLoc())) return true; if (Stmt *Body = B->getBody()) return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); return false; } Optional
CursorVisitor::shouldVisitCursor(CXCursor Cursor) { if (RegionOfInterest.isValid()) { SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); if (Range.isInvalid()) return None; switch (CompareRegionOfInterest(Range)) { case RangeBefore: // This declaration comes before the region of interest; skip it. return None; case RangeAfter: // This declaration comes after the region of interest; we're done. return false; case RangeOverlap: // This declaration overlaps the region of interest; visit it. break; } } return true; } bool CursorVisitor::VisitDeclContext(DeclContext *DC) { DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); // FIXME: Eventually remove. This part of a hack to support proper // iteration over all Decls contained lexically within an ObjC container. SaveAndRestore
DI_saved(DI_current, &I); SaveAndRestore
DE_saved(DE_current, E); for ( ; I != E; ++I) { Decl *D = *I; if (D->getLexicalDeclContext() != DC) continue; const Optional
V = handleDeclForVisitation(D); if (!V.hasValue()) continue; return V.getValue(); } return false; } Optional
CursorVisitor::handleDeclForVisitation(const Decl *D) { CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); // Ignore synthesized ivars here, otherwise if we have something like: // @synthesize prop = _prop; // and '_prop' is not declared, we will encounter a '_prop' ivar before // encountering the 'prop' synthesize declaration and we will think that // we passed the region-of-interest. if (auto *ivarD = dyn_cast
(D)) { if (ivarD->getSynthesize()) return None; } // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol // declarations is a mismatch with the compiler semantics. if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { auto *ID = cast
(D); if (!ID->isThisDeclarationADefinition()) Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { auto *PD = cast
(D); if (!PD->isThisDeclarationADefinition()) Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); } const Optional
V = shouldVisitCursor(Cursor); if (!V.hasValue()) return None; if (!V.getValue()) return false; if (Visit(Cursor, true)) return true; return None; } bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { llvm_unreachable("Translation units are visited directly by Visit()"); } bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { if (VisitTemplateParameters(D->getTemplateParameters())) return true; return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest)); } bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitClassTemplateSpecializationDecl( ClassTemplateSpecializationDecl *D) { bool ShouldVisitBody = false; switch (D->getSpecializationKind()) { case TSK_Undeclared: case TSK_ImplicitInstantiation: // Nothing to visit return false; case TSK_ExplicitInstantiationDeclaration: case TSK_ExplicitInstantiationDefinition: break; case TSK_ExplicitSpecialization: ShouldVisitBody = true; break; } // Visit the template arguments used in the specialization. if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { TypeLoc TL = SpecType->getTypeLoc(); if (TemplateSpecializationTypeLoc TSTLoc = TL.getAs
()) { for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) return true; } } return ShouldVisitBody && VisitCXXRecordDecl(D); } bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( ClassTemplatePartialSpecializationDecl *D) { // FIXME: Visit the "outer" template parameter lists on the TagDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; // Visit the partial specialization arguments. const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) if (VisitTemplateArgumentLoc(TemplateArgs[I])) return true; return VisitCXXRecordDecl(D); } bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { // Visit the default argument. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) if (Visit(DefArg->getTypeLoc())) return true; return false; } bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { if (Expr *Init = D->getInitExpr()) return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { unsigned NumParamList = DD->getNumTemplateParameterLists(); for (unsigned i = 0; i < NumParamList; i++) { TemplateParameterList* Params = DD->getTemplateParameterList(i); if (VisitTemplateParameters(Params)) return true; } if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) if (Visit(TSInfo->getTypeLoc())) return true; // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return false; } /// \brief Compare two base or member initializers based on their source order. static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X, CXXCtorInitializer *const *Y) { return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); } bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { unsigned NumParamList = ND->getNumTemplateParameterLists(); for (unsigned i = 0; i < NumParamList; i++) { TemplateParameterList* Params = ND->getTemplateParameterList(i); if (VisitTemplateParameters(Params)) return true; } if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { // Visit the function declaration's syntactic components in the order // written. This requires a bit of work. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); FunctionTypeLoc FTL = TL.getAs
(); // If we have a function declared directly (without the use of a typedef), // visit just the return type. Otherwise, just visit the function's type // now. if ((FTL && !isa
(ND) && Visit(FTL.getReturnLoc())) || (!FTL && Visit(TL))) return true; // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (!isa
(ND)) if (VisitDeclarationNameInfo(ND->getNameInfo())) return true; // FIXME: Visit explicitly-specified template arguments! // Visit the function parameters, if we have a function type. if (FTL && VisitFunctionTypeLoc(FTL, true)) return true; // FIXME: Attributes? } if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { if (CXXConstructorDecl *Constructor = dyn_cast
(ND)) { // Find the initializers that were written in the source. SmallVector
WrittenInits; for (auto *I : Constructor->inits()) { if (!I->isWritten()) continue; WrittenInits.push_back(I); } // Sort the initializers in source order llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), &CompareCXXCtorInitializers); // Visit the initializers in source order for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { CXXCtorInitializer *Init = WrittenInits[I]; if (Init->isAnyMemberInitializer()) { if (Visit(MakeCursorMemberRef(Init->getAnyMember(), Init->getMemberLocation(), TU))) return true; } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { if (Visit(TInfo->getTypeLoc())) return true; } // Visit the initializer value. if (Expr *Initializer = Init->getInit()) if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) return true; } } if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (Expr *BitWidth = D->getBitWidth()) return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitVarDecl(VarDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (Expr *Init = D->getInit()) return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) if (Expr *DefArg = D->getDefaultArgument()) return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { // FIXME: Visit the "outer" template parameter lists on the FunctionDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; return VisitFunctionDecl(D->getTemplatedDecl()); } bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { // FIXME: Visit the "outer" template parameter lists on the TagDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; return VisitCXXRecordDecl(D->getTemplatedDecl()); } bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { if (VisitTemplateParameters(D->getTemplateParameters())) return true; if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && VisitTemplateArgumentLoc(D->getDefaultArgument())) return true; return false; } bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { // Visit the bound, if it's explicit. if (D->hasExplicitBound()) { if (auto TInfo = D->getTypeSourceInfo()) { if (Visit(TInfo->getTypeLoc())) return true; } } return false; } bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) if (Visit(TSInfo->getTypeLoc())) return true; for (const auto *P : ND->parameters()) { if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) return true; } return ND->isThisDeclarationADefinition() && Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)); } template
static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, SourceManager &SM, SourceLocation EndLoc, SmallVectorImpl
&Decls) { DeclIt next = *DI_current; while (++next != DE_current) { Decl *D_next = *next; if (!D_next) break; SourceLocation L = D_next->getLocStart(); if (!L.isValid()) break; if (SM.isBeforeInTranslationUnit(L, EndLoc)) { *DI_current = next; Decls.push_back(D_next); continue; } break; } } bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially // an @implementation can lexically contain Decls that are not properly // nested in the AST. When we identify such cases, we need to retrofit // this nesting here. if (!DI_current && !FileDI_current) return VisitDeclContext(D); // Scan the Decls that immediately come after the container // in the current DeclContext. If any fall within the // container's lexical region, stash them into a vector // for later processing. SmallVector
DeclsInContainer; SourceLocation EndLoc = D->getSourceRange().getEnd(); SourceManager &SM = AU->getSourceManager(); if (EndLoc.isValid()) { if (DI_current) { addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, DeclsInContainer); } else { addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, DeclsInContainer); } } // The common case. if (DeclsInContainer.empty()) return VisitDeclContext(D); // Get all the Decls in the DeclContext, and sort them with the // additional ones we've collected. Then visit them. for (auto *SubDecl : D->decls()) { if (!SubDecl || SubDecl->getLexicalDeclContext() != D || SubDecl->getLocStart().isInvalid()) continue; DeclsInContainer.push_back(SubDecl); } // Now sort the Decls so that they appear in lexical order. std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), [&SM](Decl *A, Decl *B) { SourceLocation L_A = A->getLocStart(); SourceLocation L_B = B->getLocStart(); assert(L_A.isValid() && L_B.isValid()); return SM.isBeforeInTranslationUnit(L_A, L_B); }); // Now visit the decls. for (SmallVectorImpl
::iterator I = DeclsInContainer.begin(), E = DeclsInContainer.end(); I != E; ++I) { CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); const Optional
&V = shouldVisitCursor(Cursor); if (!V.hasValue()) continue; if (!V.getValue()) return false; if (Visit(Cursor, true)) return true; } return false; } bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), TU))) return true; if (VisitObjCTypeParamList(ND->getTypeParamList())) return true; ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), E = ND->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(ND); } bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { if (!PID->isThisDeclarationADefinition()) return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), E = PID->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(PID); } bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) return true; // FIXME: This implements a workaround with @property declarations also being // installed in the DeclContext for the @interface. Eventually this code // should be removed. ObjCCategoryDecl *CDecl = dyn_cast
(PD->getDeclContext()); if (!CDecl || !CDecl->IsClassExtension()) return false; ObjCInterfaceDecl *ID = CDecl->getClassInterface(); if (!ID) return false; IdentifierInfo *PropertyId = PD->getIdentifier(); ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(cast
(ID), PropertyId, PD->getQueryKind()); if (!prevDecl) return false; // Visit synthesized methods since they will be skipped when visiting // the @interface. if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) return true; if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) return true; return false; } bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { if (!typeParamList) return false; for (auto *typeParam : *typeParamList) { // Visit the type parameter. if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { if (!D->isThisDeclarationADefinition()) { // Forward declaration is treated like a reference. return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); } // Objective-C type parameters. if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) return true; // Issue callbacks for super class. if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), D->getSuperClassLoc(), TU))) return true; if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) if (Visit(SuperClassTInfo->getTypeLoc())) return true; ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), E = D->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(D); } bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { return VisitObjCContainerDecl(D); } bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { // 'ID' could be null when dealing with invalid code. if (ObjCInterfaceDecl *ID = D->getClassInterface()) if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) return true; return VisitObjCImplDecl(D); } bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { #if 0 // Issue callbacks for super class. // FIXME: No source location information! if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), D->getSuperClassLoc(), TU))) return true; #endif return VisitObjCImplDecl(D); } bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) if (PD->isIvarNameSpecified()) return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); return false; } bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), D->getTargetNameLoc(), TU)); } bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; } if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) return true; return VisitDeclarationNameInfo(D->getNameInfo()); } bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), D->getIdentLocation(), TU)); } bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; } return VisitDeclarationNameInfo(D->getNameInfo()); } bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( UnresolvedUsingTypenameDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return false; } bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) { if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest))) return true; if (Visit(MakeCXCursor(D->getMessage(), StmtParent, TU, RegionOfInterest))) return true; return false; } bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { switch (Name.getName().getNameKind()) { case clang::DeclarationName::Identifier: case clang::DeclarationName::CXXLiteralOperatorName: case clang::DeclarationName::CXXOperatorName: case clang::DeclarationName::CXXUsingDirective: return false; case clang::DeclarationName::CXXConstructorName: case clang::DeclarationName::CXXDestructorName: case clang::DeclarationName::CXXConversionFunctionName: if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) return Visit(TSInfo->getTypeLoc()); return false; case clang::DeclarationName::ObjCZeroArgSelector: case clang::DeclarationName::ObjCOneArgSelector: case clang::DeclarationName::ObjCMultiArgSelector: // FIXME: Per-identifier location info? return false; } llvm_unreachable("Invalid DeclarationName::Kind!"); } bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range) { // FIXME: This whole routine is a hack to work around the lack of proper // source information in nested-name-specifiers (PR5791). Since we do have // a beginning source location, we can visit the first component of the // nested-name-specifier, if it's a single-token component. if (!NNS) return false; // Get the first component in the nested-name-specifier. while (NestedNameSpecifier *Prefix = NNS->getPrefix()) NNS = Prefix; switch (NNS->getKind()) { case NestedNameSpecifier::Namespace: return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU)); case NestedNameSpecifier::NamespaceAlias: return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), Range.getBegin(), TU)); case NestedNameSpecifier::TypeSpec: { // If the type has a form where we know that the beginning of the source // range matches up with a reference cursor. Visit the appropriate reference // cursor. const Type *T = NNS->getAsType(); if (const TypedefType *Typedef = dyn_cast
(T)) return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); if (const TagType *Tag = dyn_cast
(T)) return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); if (const TemplateSpecializationType *TST = dyn_cast
(T)) return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); break; } case NestedNameSpecifier::TypeSpecWithTemplate: case NestedNameSpecifier::Global: case NestedNameSpecifier::Identifier: case NestedNameSpecifier::Super: break; } return false; } bool CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { SmallVector
Qualifiers; for (; Qualifier; Qualifier = Qualifier.getPrefix()) Qualifiers.push_back(Qualifier); while (!Qualifiers.empty()) { NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); switch (NNS->getKind()) { case NestedNameSpecifier::Namespace: if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Q.getLocalBeginLoc(), TU))) return true; break; case NestedNameSpecifier::NamespaceAlias: if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), Q.getLocalBeginLoc(), TU))) return true; break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: if (Visit(Q.getTypeLoc())) return true; break; case NestedNameSpecifier::Global: case NestedNameSpecifier::Identifier: case NestedNameSpecifier::Super: break; } } return false; } bool CursorVisitor::VisitTemplateParameters( const TemplateParameterList *Params) { if (!Params) return false; for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { switch (Name.getKind()) { case TemplateName::Template: return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); case TemplateName::OverloadedTemplate: // Visit the overloaded template set. if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) return true; return false; case TemplateName::DependentTemplate: // FIXME: Visit nested-name-specifier. return false; case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier. return Visit(MakeCursorTemplateRef( Name.getAsQualifiedTemplateName()->getDecl(), Loc, TU)); case TemplateName::SubstTemplateTemplateParm: return Visit(MakeCursorTemplateRef( Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU)); case TemplateName::SubstTemplateTemplateParmPack: return Visit(MakeCursorTemplateRef( Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc, TU)); } llvm_unreachable("Invalid TemplateName::Kind!"); } bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { switch (TAL.getArgument().getKind()) { case TemplateArgument::Null: case TemplateArgument::Integral: case TemplateArgument::Pack: return false; case TemplateArgument::Type: if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; case TemplateArgument::Declaration: if (Expr *E = TAL.getSourceDeclExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::NullPtr: if (Expr *E = TAL.getSourceNullPtrExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::Expression: if (Expr *E = TAL.getSourceExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::Template: case TemplateArgument::TemplateExpansion: if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) return true; return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), TAL.getTemplateNameLoc()); } llvm_unreachable("Invalid TemplateArgument::Kind!"); } bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return Visit(TL.getUnqualifiedLoc()); } bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { ASTContext &Context = AU->getASTContext(); // Some builtin types (such as Objective-C's "id", "sel", and // "Class") have associated declarations. Create cursors for those. QualType VisitType; switch (TL.getTypePtr()->getKind()) { case BuiltinType::Void: case BuiltinType::NullPtr: case BuiltinType::Dependent: #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" case BuiltinType::OCLSampler: case BuiltinType::OCLEvent: case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLNDRange: case BuiltinType::OCLReserveID: #define BUILTIN_TYPE(Id, SingletonId) #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: #include "clang/AST/BuiltinTypes.def" break; case BuiltinType::ObjCId: VisitType = Context.getObjCIdType(); break; case BuiltinType::ObjCClass: VisitType = Context.getObjCClassType(); break; case BuiltinType::ObjCSel: VisitType = Context.getObjCSelType(); break; } if (!VisitType.isNull()) { if (const TypedefType *Typedef = VisitType->getAs
()) return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU)); } return false; } bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { if (TL.isDefinition()) return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) return true; for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) { if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc())) return true; } for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), TU))) return true; } return false; } bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { return Visit(TL.getInnerLoc()); } bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { return Visit(TL.getModifiedLoc()); } bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType) { if (!SkipResultType && Visit(TL.getReturnLoc())) return true; for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I) if (Decl *D = TL.getParam(I)) if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) return true; return false; } bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { if (Visit(TL.getElementLoc())) return true; if (Expr *Size = TL.getSizeExpr()) return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) { return Visit(TL.getOriginalLoc()); } bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { return Visit(TL.getOriginalLoc()); } bool CursorVisitor::VisitTemplateSpecializationTypeLoc( TemplateSpecializationTypeLoc TL) { // Visit the template name. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), TL.getTemplateNameLoc())) return true; // Visit the template arguments. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) return true; return false; } bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); } bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { return VisitNestedNameSpecifierLoc(TL.getQualifierLoc()); } bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( DependentTemplateSpecializationTypeLoc TL) { // Visit the nested-name-specifier, if there is one. if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) return true; // Visit the template arguments. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) return true; return false; } bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) return true; return Visit(TL.getNamedTypeLoc()); } bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { return Visit(TL.getPatternLoc()); } bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { if (Expr *E = TL.getUnderlyingExpr()) return Visit(MakeCXCursor(E, StmtParent, TU)); return false; } bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { return Visit(TL.getValueLoc()); } bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) { return Visit(TL.getValueLoc()); } #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ return Visit##PARENT##Loc(TL); \ } DEFAULT_TYPELOC_IMPL(Complex, Type) DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) DEFAULT_TYPELOC_IMPL(Vector, Type) DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) DEFAULT_TYPELOC_IMPL(Record, TagType) DEFAULT_TYPELOC_IMPL(Enum, TagType) DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) DEFAULT_TYPELOC_IMPL(Auto, Type) bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; if (D->isCompleteDefinition()) { for (const auto &I : D->bases()) { if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU))) return true; } } return VisitTagDecl(D); } bool CursorVisitor::VisitAttributes(Decl *D) { for (const auto *I : D->attrs()) if (Visit(MakeCXCursor(I, D, TU))) return true; return false; } //===----------------------------------------------------------------------===// // Data-recursive visitor methods. //===----------------------------------------------------------------------===// namespace { #define DEF_JOB(NAME, DATA, KIND)\ class NAME : public VisitorJob {\ public:\ NAME(const DATA *d, CXCursor parent) : \ VisitorJob(parent, VisitorJob::KIND, d) {} \ static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ const DATA *get() const { return static_cast
(data[0]); }\ }; DEF_JOB(StmtVisit, Stmt, StmtVisitKind) DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) #undef DEF_JOB class ExplicitTemplateArgsVisit : public VisitorJob { public: ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin, const TemplateArgumentLoc *End, CXCursor parent) : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin, End) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == ExplicitTemplateArgsVisitKind; } const TemplateArgumentLoc *begin() const { return static_cast
(data[0]); } const TemplateArgumentLoc *end() { return static_cast
(data[1]); } }; class DeclVisit : public VisitorJob { public: DeclVisit(const Decl *D, CXCursor parent, bool isFirst) : VisitorJob(parent, VisitorJob::DeclVisitKind, D, isFirst ? (void*) 1 : (void*) nullptr) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == DeclVisitKind; } const Decl *get() const { return static_cast
(data[0]); } bool isFirst() const { return data[1] != nullptr; } }; class TypeLocVisit : public VisitorJob { public: TypeLocVisit(TypeLoc tl, CXCursor parent) : VisitorJob(parent, VisitorJob::TypeLocVisitKind, tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == TypeLocVisitKind; } TypeLoc get() const { QualType T = QualType::getFromOpaquePtr(data[0]); return TypeLoc(T, const_cast
(data[1])); } }; class LabelRefVisit : public VisitorJob { public: LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, labelLoc.getPtrEncoding()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::LabelRefVisitKind; } const LabelDecl *get() const { return static_cast
(data[0]); } SourceLocation getLoc() const { return SourceLocation::getFromPtrEncoding(data[1]); } }; class NestedNameSpecifierLocVisit : public VisitorJob { public: NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, Qualifier.getNestedNameSpecifier(), Qualifier.getOpaqueData()) { } static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; } NestedNameSpecifierLoc get() const { return NestedNameSpecifierLoc( const_cast
( static_cast
(data[0])), const_cast
(data[1])); } }; class DeclarationNameInfoVisit : public VisitorJob { public: DeclarationNameInfoVisit(const Stmt *S, CXCursor parent) : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; } DeclarationNameInfo get() const { const Stmt *S = static_cast
(data[0]); switch (S->getStmtClass()) { default: llvm_unreachable("Unhandled Stmt"); case clang::Stmt::MSDependentExistsStmtClass: return cast
(S)->getNameInfo(); case Stmt::CXXDependentScopeMemberExprClass: return cast
(S)->getMemberNameInfo(); case Stmt::DependentScopeDeclRefExprClass: return cast
(S)->getNameInfo(); case Stmt::OMPCriticalDirectiveClass: return cast
(S)->getDirectiveName(); } } }; class MemberRefVisit : public VisitorJob { public: MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent) : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, L.getPtrEncoding()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::MemberRefVisitKind; } const FieldDecl *get() const { return static_cast
(data[0]); } SourceLocation getLoc() const { return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); } }; class EnqueueVisitor : public ConstStmtVisitor
{ friend class OMPClauseEnqueue; VisitorWorkList &WL; CXCursor Parent; public: EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) : WL(wl), Parent(parent) {} void VisitAddrLabelExpr(const AddrLabelExpr *E); void VisitBlockExpr(const BlockExpr *B); void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); void VisitCompoundStmt(const CompoundStmt *S); void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ } void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S); void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E); void VisitCXXNewExpr(const CXXNewExpr *E); void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E); void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E); void VisitCXXTypeidExpr(const CXXTypeidExpr *E); void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E); void VisitCXXUuidofExpr(const CXXUuidofExpr *E); void VisitCXXCatchStmt(const CXXCatchStmt *S); void VisitCXXForRangeStmt(const CXXForRangeStmt *S); void VisitDeclRefExpr(const DeclRefExpr *D); void VisitDeclStmt(const DeclStmt *S); void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E); void VisitDesignatedInitExpr(const DesignatedInitExpr *E); void VisitExplicitCastExpr(const ExplicitCastExpr *E); void VisitForStmt(const ForStmt *FS); void VisitGotoStmt(const GotoStmt *GS); void VisitIfStmt(const IfStmt *If); void VisitInitListExpr(const InitListExpr *IE); void VisitMemberExpr(const MemberExpr *M); void VisitOffsetOfExpr(const OffsetOfExpr *E); void VisitObjCEncodeExpr(const ObjCEncodeExpr *E); void VisitObjCMessageExpr(const ObjCMessageExpr *M); void VisitOverloadExpr(const OverloadExpr *E); void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); void VisitStmt(const Stmt *S); void VisitSwitchStmt(const SwitchStmt *S); void VisitWhileStmt(const WhileStmt *W); void VisitTypeTraitExpr(const TypeTraitExpr *E); void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E); void VisitExpressionTraitExpr(const ExpressionTraitExpr *E); void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U); void VisitVAArgExpr(const VAArgExpr *E); void VisitSizeOfPackExpr(const SizeOfPackExpr *E); void VisitPseudoObjectExpr(const PseudoObjectExpr *E); void VisitOpaqueValueExpr(const OpaqueValueExpr *E); void VisitLambdaExpr(const LambdaExpr *E); void VisitOMPExecutableDirective(const OMPExecutableDirective *D); void VisitOMPLoopDirective(const OMPLoopDirective *D); void VisitOMPParallelDirective(const OMPParallelDirective *D); void VisitOMPSimdDirective(const OMPSimdDirective *D); void VisitOMPForDirective(const OMPForDirective *D); void VisitOMPForSimdDirective(const OMPForSimdDirective *D); void VisitOMPSectionsDirective(const OMPSectionsDirective *D); void VisitOMPSectionDirective(const OMPSectionDirective *D); void VisitOMPSingleDirective(const OMPSingleDirective *D); void VisitOMPMasterDirective(const OMPMasterDirective *D); void VisitOMPCriticalDirective(const OMPCriticalDirective *D); void VisitOMPParallelForDirective(const OMPParallelForDirective *D); void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D); void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D); void VisitOMPTaskDirective(const OMPTaskDirective *D); void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D); void VisitOMPBarrierDirective(const OMPBarrierDirective *D); void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D); void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D); void VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D); void VisitOMPCancelDirective(const OMPCancelDirective *D); void VisitOMPFlushDirective(const OMPFlushDirective *D); void VisitOMPOrderedDirective(const OMPOrderedDirective *D); void VisitOMPAtomicDirective(const OMPAtomicDirective *D); void VisitOMPTargetDirective(const OMPTargetDirective *D); void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D); void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D); void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D); void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D); void VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D); void VisitOMPTeamsDirective(const OMPTeamsDirective *D); void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D); void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D); void VisitOMPDistributeDirective(const OMPDistributeDirective *D); void VisitOMPDistributeParallelForDirective( const OMPDistributeParallelForDirective *D); void VisitOMPDistributeParallelForSimdDirective( const OMPDistributeParallelForSimdDirective *D); void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D); void VisitOMPTargetParallelForSimdDirective( const OMPTargetParallelForSimdDirective *D); private: void AddDeclarationNameInfo(const Stmt *S); void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); void AddExplicitTemplateArgs(const TemplateArgumentLoc *A, unsigned NumTemplateArgs); void AddMemberRef(const FieldDecl *D, SourceLocation L); void AddStmt(const Stmt *S); void AddDecl(const Decl *D, bool isFirst = true); void AddTypeLoc(TypeSourceInfo *TI); void EnqueueChildren(const Stmt *S); void EnqueueChildren(const OMPClause *S); }; } // end anonyous namespace void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) { // 'S' should always be non-null, since it comes from the // statement we are visiting. WL.push_back(DeclarationNameInfoVisit(S, Parent)); } void EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { if (Qualifier) WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); } void EnqueueVisitor::AddStmt(const Stmt *S) { if (S) WL.push_back(StmtVisit(S, Parent)); } void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) { if (D) WL.push_back(DeclVisit(D, Parent, isFirst)); } void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A, unsigned NumTemplateArgs) { WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent)); } void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) { if (D) WL.push_back(MemberRefVisit(D, L, Parent)); } void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { if (TI) WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); } void EnqueueVisitor::EnqueueChildren(const Stmt *S) { unsigned size = WL.size(); for (const Stmt *SubStmt : S->children()) { AddStmt(SubStmt); } if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } namespace { class OMPClauseEnqueue : public ConstOMPClauseVisitor
{ EnqueueVisitor *Visitor; /// \brief Process clauses with list of variables. template
void VisitOMPClauseList(T *Node); public: OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { } #define OPENMP_CLAUSE(Name, Class) \ void Visit##Class(const Class *C); #include "clang/Basic/OpenMPKinds.def" void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C); void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C); }; void OMPClauseEnqueue::VisitOMPClauseWithPreInit( const OMPClauseWithPreInit *C) { Visitor->AddStmt(C->getPreInitStmt()); } void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate( const OMPClauseWithPostUpdate *C) { VisitOMPClauseWithPreInit(C); Visitor->AddStmt(C->getPostUpdateExpr()); } void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) { Visitor->AddStmt(C->getCondition()); } void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) { Visitor->AddStmt(C->getCondition()); } void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) { Visitor->AddStmt(C->getNumThreads()); } void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) { Visitor->AddStmt(C->getSafelen()); } void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) { Visitor->AddStmt(C->getSimdlen()); } void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) { Visitor->AddStmt(C->getNumForLoops()); } void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { } void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { } void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { VisitOMPClauseWithPreInit(C); Visitor->AddStmt(C->getChunkSize()); } void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) { Visitor->AddStmt(C->getNumForLoops()); } void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {} void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {} void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {} void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) { Visitor->AddStmt(C->getDevice()); } void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) { Visitor->AddStmt(C->getNumTeams()); } void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) { Visitor->AddStmt(C->getThreadLimit()); } void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) { Visitor->AddStmt(C->getPriority()); } void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) { Visitor->AddStmt(C->getGrainsize()); } void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) { Visitor->AddStmt(C->getNumTasks()); } void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) { Visitor->AddStmt(C->getHint()); } template
void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { for (const auto *I : Node->varlists()) { Visitor->AddStmt(I); } } void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { VisitOMPClauseList(C); for (const auto *E : C->private_copies()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPFirstprivateClause( const OMPFirstprivateClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPreInit(C); for (const auto *E : C->private_copies()) { Visitor->AddStmt(E); } for (const auto *E : C->inits()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPLastprivateClause( const OMPLastprivateClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPostUpdate(C); for (auto *E : C->private_copies()) { Visitor->AddStmt(E); } for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPostUpdate(C); for (auto *E : C->privates()) { Visitor->AddStmt(E); } for (auto *E : C->lhs_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->rhs_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->reduction_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPostUpdate(C); for (const auto *E : C->privates()) { Visitor->AddStmt(E); } for (const auto *E : C->inits()) { Visitor->AddStmt(E); } for (const auto *E : C->updates()) { Visitor->AddStmt(E); } for (const auto *E : C->finals()) { Visitor->AddStmt(E); } Visitor->AddStmt(C->getStep()); Visitor->AddStmt(C->getCalcStep()); } void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { VisitOMPClauseList(C); Visitor->AddStmt(C->getAlignment()); } void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { VisitOMPClauseList(C); for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) { VisitOMPClauseList(C); for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPDistScheduleClause( const OMPDistScheduleClause *C) { VisitOMPClauseWithPreInit(C); Visitor->AddStmt(C->getChunkSize()); } void OMPClauseEnqueue::VisitOMPDefaultmapClause( const OMPDefaultmapClause * /*C*/) {} void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) { VisitOMPClauseList(C); } } void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { unsigned size = WL.size(); OMPClauseEnqueue Visitor(this); Visitor.Visit(S); if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); } void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { AddDecl(B->getBlockDecl()); } void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { for (auto &I : llvm::reverse(S->body())) AddStmt(I); } void EnqueueVisitor:: VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) { AddStmt(S->getSubStmt()); AddDeclarationNameInfo(S); if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); } void EnqueueVisitor:: VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { if (E->hasExplicitTemplateArgs()) AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); AddDeclarationNameInfo(E); if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); if (!E->isImplicitAccess()) AddStmt(E->getBase()); } void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { // Enqueue the initializer , if any. AddStmt(E->getInitializer()); // Enqueue the array size, if any. AddStmt(E->getArraySize()); // Enqueue the allocated type. AddTypeLoc(E->getAllocatedTypeSourceInfo()); // Enqueue the placement arguments. for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) AddStmt(E->getPlacementArg(I-1)); } void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) AddStmt(CE->getArg(I-1)); AddStmt(CE->getCallee()); AddStmt(CE->getArg(0)); } void EnqueueVisitor::VisitCXXPseudoDestructorExpr( const CXXPseudoDestructorExpr *E) { // Visit the name of the type being destroyed. AddTypeLoc(E->getDestroyedTypeInfo()); // Visit the scope type that looks disturbingly like the nested-name-specifier // but isn't. AddTypeLoc(E->getScopeTypeInfo()); // Visit the nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); // Visit base expression. AddStmt(E->getBase()); } void EnqueueVisitor::VisitCXXScalarValueInitExpr( const CXXScalarValueInitExpr *E) { AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXTemporaryObjectExpr( const CXXTemporaryObjectExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { EnqueueChildren(E); if (E->isTypeOperand()) AddTypeLoc(E->getTypeOperandSourceInfo()); } void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( const CXXUnresolvedConstructExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { EnqueueChildren(E); if (E->isTypeOperand()) AddTypeLoc(E->getTypeOperandSourceInfo()); } void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { EnqueueChildren(S); AddDecl(S->getExceptionDecl()); } void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { AddStmt(S->getBody()); AddStmt(S->getRangeInit()); AddDecl(S->getLoopVariable()); } void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { if (DR->hasExplicitTemplateArgs()) AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs()); WL.push_back(DeclRefExprParts(DR, Parent)); } void EnqueueVisitor::VisitDependentScopeDeclRefExpr( const DependentScopeDeclRefExpr *E) { if (E->hasExplicitTemplateArgs()) AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); AddDeclarationNameInfo(E); AddNestedNameSpecifierLoc(E->getQualifierLoc()); } void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { unsigned size = WL.size(); bool isFirst = true; for (const auto *D : S->decls()) { AddDecl(D, isFirst); isFirst = false; } if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { AddStmt(E->getInit()); for (const DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator()) { if (FieldDecl *Field = D.getField()) AddMemberRef(Field, D.getFieldLoc()); continue; } if (D.isArrayDesignator()) { AddStmt(E->getArrayIndex(D)); continue; } assert(D.isArrayRangeDesignator() && "Unknown designator kind"); AddStmt(E->getArrayRangeEnd(D)); AddStmt(E->getArrayRangeStart(D)); } } void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeInfoAsWritten()); } void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { AddStmt(FS->getBody()); AddStmt(FS->getInc()); AddStmt(FS->getCond()); AddDecl(FS->getConditionVariable()); AddStmt(FS->getInit()); } void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); } void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { AddStmt(If->getElse()); AddStmt(If->getThen()); AddStmt(If->getCond()); AddDecl(If->getConditionVariable()); } void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { // We care about the syntactic form of the initializer list, only. if (InitListExpr *Syntactic = IE->getSyntacticForm()) IE = Syntactic; EnqueueChildren(IE); } void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { WL.push_back(MemberExprParts(M, Parent)); // If the base of the member access expression is an implicit 'this', don't // visit it. // FIXME: If we ever want to show these implicit accesses, this will be // unfortunate. However, clang_getCursor() relies on this behavior. if (M->isImplicitAccess()) return; // Ignore base anonymous struct/union fields, otherwise they will shadow the // real field that that we are interested in. if (auto *SubME = dyn_cast
(M->getBase())) { if (auto *FD = dyn_cast_or_null
(SubME->getMemberDecl())) { if (FD->isAnonymousStructOrUnion()) { AddStmt(SubME->getBase()); return; } } } AddStmt(M->getBase()); } void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { AddTypeLoc(E->getEncodedTypeSourceInfo()); } void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { EnqueueChildren(M); AddTypeLoc(M->getClassReceiverTypeInfo()); } void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { // Visit the components of the offsetof expression. for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { const OffsetOfNode &Node = E->getComponent(I-1); switch (Node.getKind()) { case OffsetOfNode::Array: AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); break; case OffsetOfNode::Field: AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); break; case OffsetOfNode::Identifier: case OffsetOfNode::Base: continue; } } // Visit the type into which we're computing the offset. AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { if (E->hasExplicitTemplateArgs()) AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); WL.push_back(OverloadExprParts(E, Parent)); } void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( const UnaryExprOrTypeTraitExpr *E) { EnqueueChildren(E); if (E->isArgumentType()) AddTypeLoc(E->getArgumentTypeInfo()); } void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); } void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { AddStmt(S->getBody()); AddStmt(S->getCond()); AddDecl(S->getConditionVariable()); } void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { AddStmt(W->getBody()); AddStmt(W->getCond()); AddDecl(W->getConditionVariable()); } void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { for (unsigned I = E->getNumArgs(); I > 0; --I) AddTypeLoc(E->getArg(I-1)); } void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { AddTypeLoc(E->getQueriedTypeSourceInfo()); } void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { EnqueueChildren(E); } void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { VisitOverloadExpr(U); if (!U->isImplicitAccess()) AddStmt(U->getBase()); } void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { AddStmt(E->getSubExpr()); AddTypeLoc(E->getWrittenTypeInfo()); } void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { WL.push_back(SizeOfPackExprParts(E, Parent)); } void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { // If the opaque value has a source expression, just transparently // visit that. This is useful for (e.g.) pseudo-object expressions. if (Expr *SourceExpr = E->getSourceExpr()) return Visit(SourceExpr); } void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { AddStmt(E->getBody()); WL.push_back(LambdaExprParts(E, Parent)); } void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { // Treat the expression like its syntactic form. Visit(E->getSyntacticForm()); } void EnqueueVisitor::VisitOMPExecutableDirective( const OMPExecutableDirective *D) { EnqueueChildren(D); for (ArrayRef
::iterator I = D->clauses().begin(), E = D->clauses().end(); I != E; ++I) EnqueueChildren(*I); } void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { VisitOMPExecutableDirective(D); AddDeclarationNameInfo(D); } void EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPParallelForSimdDirective( const OMPParallelForSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPParallelSectionsDirective( const OMPParallelSectionsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskgroupDirective( const OMPTaskgroupDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetDataDirective(const OMPTargetDataDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetEnterDataDirective( const OMPTargetEnterDataDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetExitDataDirective( const OMPTargetExitDataDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetParallelDirective( const OMPTargetParallelDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetParallelForDirective( const OMPTargetParallelForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCancellationPointDirective( const OMPCancellationPointDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPTaskLoopSimdDirective( const OMPTaskLoopSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPDistributeDirective( const OMPDistributeDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPDistributeParallelForDirective( const OMPDistributeParallelForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective( const OMPDistributeParallelForSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPDistributeSimdDirective( const OMPDistributeSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective( const OMPTargetParallelForSimdDirective *D) { VisitOMPLoopDirective(D); } void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); } bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { if (RegionOfInterest.isValid()) { SourceRange Range = getRawCursorExtent(C); if (Range.isInvalid() || CompareRegionOfInterest(Range)) return false; } return true; } bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { while (!WL.empty()) { // Dequeue the worklist item. VisitorJob LI = WL.pop_back_val(); // Set the Parent field, then back to its old value once we're done. SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); switch (LI.getKind()) { case VisitorJob::DeclVisitKind: { const Decl *D = cast
(&LI)->get(); if (!D) continue; // For now, perform default visitation for Decls. if (Visit(MakeCXCursor(D, TU, RegionOfInterest, cast
(&LI)->isFirst()))) return true; continue; } case VisitorJob::ExplicitTemplateArgsVisitKind: { for (const TemplateArgumentLoc &Arg : *cast
(&LI)) { if (VisitTemplateArgumentLoc(Arg)) return true; } continue; } case VisitorJob::TypeLocVisitKind: { // Perform default visitation for TypeLocs. if (Visit(cast
(&LI)->get())) return true; continue; } case VisitorJob::LabelRefVisitKind: { const LabelDecl *LS = cast
(&LI)->get(); if (LabelStmt *stmt = LS->getStmt()) { if (Visit(MakeCursorLabelRef(stmt, cast
(&LI)->getLoc(), TU))) { return true; } } continue; } case VisitorJob::NestedNameSpecifierLocVisitKind: { NestedNameSpecifierLocVisit *V = cast
(&LI); if (VisitNestedNameSpecifierLoc(V->get())) return true; continue; } case VisitorJob::DeclarationNameInfoVisitKind: { if (VisitDeclarationNameInfo(cast
(&LI) ->get())) return true; continue; } case VisitorJob::MemberRefVisitKind: { MemberRefVisit *V = cast
(&LI); if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) return true; continue; } case VisitorJob::StmtVisitKind: { const Stmt *S = cast
(&LI)->get(); if (!S) continue; // Update the current cursor. CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); if (!IsInRegionOfInterest(Cursor)) continue; switch (Visitor(Cursor, Parent, ClientData)) { case CXChildVisit_Break: return true; case CXChildVisit_Continue: break; case CXChildVisit_Recurse: if (PostChildrenVisitor) WL.push_back(PostChildrenVisit(nullptr, Cursor)); EnqueueWorkList(WL, S); break; } continue; } case VisitorJob::MemberExprPartsKind: { // Handle the other pieces in the MemberExpr besides the base. const MemberExpr *M = cast
(&LI)->get(); // Visit the nested-name-specifier if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (VisitDeclarationNameInfo(M->getMemberNameInfo())) return true; // Visit the explicitly-specified template arguments, if any. if (M->hasExplicitTemplateArgs()) { for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), *ArgEnd = Arg + M->getNumTemplateArgs(); Arg != ArgEnd; ++Arg) { if (VisitTemplateArgumentLoc(*Arg)) return true; } } continue; } case VisitorJob::DeclRefExprPartsKind: { const DeclRefExpr *DR = cast
(&LI)->get(); // Visit nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit declaration name. if (VisitDeclarationNameInfo(DR->getNameInfo())) return true; continue; } case VisitorJob::OverloadExprPartsKind: { const OverloadExpr *O = cast
(&LI)->get(); // Visit the nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (VisitDeclarationNameInfo(O->getNameInfo())) return true; // Visit the overloaded declaration reference. if (Visit(MakeCursorOverloadedDeclRef(O, TU))) return true; continue; } case VisitorJob::SizeOfPackExprPartsKind: { const SizeOfPackExpr *E = cast
(&LI)->get(); NamedDecl *Pack = E->getPack(); if (isa
(Pack)) { if (Visit(MakeCursorTypeRef(cast
(Pack), E->getPackLoc(), TU))) return true; continue; } if (isa
(Pack)) { if (Visit(MakeCursorTemplateRef(cast
(Pack), E->getPackLoc(), TU))) return true; continue; } // Non-type template parameter packs and function parameter packs are // treated like DeclRefExpr cursors. continue; } case VisitorJob::LambdaExprPartsKind: { // Visit captures. const LambdaExpr *E = cast
(&LI)->get(); for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), CEnd = E->explicit_capture_end(); C != CEnd; ++C) { // FIXME: Lambda init-captures. if (!C->capturesVariable()) continue; if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(), TU))) return true; } // Visit parameters and return type, if present. if (E->hasExplicitParameters() || E->hasExplicitResultType()) { TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); if (E->hasExplicitParameters() && E->hasExplicitResultType()) { // Visit the whole type. if (Visit(TL)) return true; } else if (FunctionProtoTypeLoc Proto = TL.getAs
()) { if (E->hasExplicitParameters()) { // Visit parameters. for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) if (Visit(MakeCXCursor(Proto.getParam(I), TU))) return true; } else { // Visit result type. if (Visit(Proto.getReturnLoc())) return true; } } } break; } case VisitorJob::PostChildrenVisitKind: if (PostChildrenVisitor(Parent, ClientData)) return true; break; } } return false; } bool CursorVisitor::Visit(const Stmt *S) { VisitorWorkList *WL = nullptr; if (!WorkListFreeList.empty()) { WL = WorkListFreeList.back(); WL->clear(); WorkListFreeList.pop_back(); } else { WL = new VisitorWorkList(); WorkListCache.push_back(WL); } EnqueueWorkList(*WL, S); bool result = RunVisitorWorkList(*WL); WorkListFreeList.push_back(WL); return result; } namespace { typedef SmallVector
RefNamePieces; RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, const DeclarationNameInfo &NI, SourceRange QLoc, const SourceRange *TemplateArgsLoc = nullptr) { const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; const DeclarationName::NameKind Kind = NI.getName().getNameKind(); RefNamePieces Pieces; if (WantQualifier && QLoc.isValid()) Pieces.push_back(QLoc); if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) Pieces.push_back(NI.getLoc()); if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid()) Pieces.push_back(*TemplateArgsLoc); if (Kind == DeclarationName::CXXOperatorName) { Pieces.push_back(SourceLocation::getFromRawEncoding( NI.getInfo().CXXOperatorName.BeginOpNameLoc)); Pieces.push_back(SourceLocation::getFromRawEncoding( NI.getInfo().CXXOperatorName.EndOpNameLoc)); } if (WantSinglePiece) { SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); Pieces.clear(); Pieces.push_back(R); } return Pieces; } } //===----------------------------------------------------------------------===// // Misc. API hooks. //===----------------------------------------------------------------------===// static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); ::abort(); } namespace { struct RegisterFatalErrorHandler { RegisterFatalErrorHandler() { llvm::install_fatal_error_handler(fatal_error_handler, nullptr); } }; } static llvm::ManagedStatic
RegisterFatalErrorHandlerOnce; extern "C" { CXIndex clang_createIndex(int excludeDeclarationsFromPCH, int displayDiagnostics) { // We use crash recovery to make some of our APIs more reliable, implicitly // enable it. if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) llvm::CrashRecoveryContext::Enable(); // Look through the managed static to trigger construction of the managed // static which registers our fatal error handler. This ensures it is only // registered once. (void)*RegisterFatalErrorHandlerOnce; // Initialize targets for clang module support. llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); CIndexer *CIdxr = new CIndexer(); if (excludeDeclarationsFromPCH) CIdxr->setOnlyLocalDecls(); if (displayDiagnostics) CIdxr->setDisplayDiagnostics(); if (getenv("LIBCLANG_BGPRIO_INDEX")) CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | CXGlobalOpt_ThreadBackgroundPriorityForIndexing); if (getenv("LIBCLANG_BGPRIO_EDIT")) CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | CXGlobalOpt_ThreadBackgroundPriorityForEditing); return CIdxr; } void clang_disposeIndex(CXIndex CIdx) { if (CIdx) delete static_cast
(CIdx); } void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { if (CIdx) static_cast
(CIdx)->setCXGlobalOptFlags(options); } unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { if (CIdx) return static_cast
(CIdx)->getCXGlobalOptFlags(); return 0; } void clang_toggleCrashRecovery(unsigned isEnabled) { if (isEnabled) llvm::CrashRecoveryContext::Enable(); else llvm::CrashRecoveryContext::Disable(); } CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, const char *ast_filename) { CXTranslationUnit TU; enum CXErrorCode Result = clang_createTranslationUnit2(CIdx, ast_filename, &TU); (void)Result; assert((TU && Result == CXError_Success) || (!TU && Result != CXError_Success)); return TU; } enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, const char *ast_filename, CXTranslationUnit *out_TU) { if (out_TU) *out_TU = nullptr; if (!CIdx || !ast_filename || !out_TU) return CXError_InvalidArguments; LOG_FUNC_SECTION { *Log << ast_filename; } CIndexer *CXXIdx = static_cast
(CIdx); FileSystemOptions FileSystemOpts; IntrusiveRefCntPtr
Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions()); std::unique_ptr
AU = ASTUnit::LoadFromASTFile( ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags, FileSystemOpts, /*UseDebugInfo=*/false, CXXIdx->getOnlyLocalDecls(), None, /*CaptureDiagnostics=*/true, /*AllowPCHWithCompilerErrors=*/true, /*UserFilesAreVolatile=*/true); *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release()); return *out_TU ? CXError_Success : CXError_Failure; } unsigned clang_defaultEditingTranslationUnitOptions() { return CXTranslationUnit_PrecompiledPreamble | CXTranslationUnit_CacheCompletionResults; } CXTranslationUnit clang_createTranslationUnitFromSourceFile(CXIndex CIdx, const char *source_filename, int num_command_line_args, const char * const *command_line_args, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files) { unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; return clang_parseTranslationUnit(CIdx, source_filename, command_line_args, num_command_line_args, unsaved_files, num_unsaved_files, Options); } static CXErrorCode clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, ArrayRef
unsaved_files, unsigned options, CXTranslationUnit *out_TU) { // Set up the initial return values. if (out_TU) *out_TU = nullptr; // Check arguments. if (!CIdx || !out_TU) return CXError_InvalidArguments; CIndexer *CXXIdx = static_cast
(CIdx); if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; bool CreatePreambleOnFirstParse = options & CXTranslationUnit_CreatePreambleOnFirstParse; // FIXME: Add a flag for modules. TranslationUnitKind TUKind = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete; bool CacheCodeCompletionResults = options & CXTranslationUnit_CacheCompletionResults; bool IncludeBriefCommentsInCodeCompletion = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies; bool ForSerialization = options & CXTranslationUnit_ForSerialization; // Configure the diagnostics. IntrusiveRefCntPtr
Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)); if (options & CXTranslationUnit_KeepGoing) Diags->setFatalsAsError(true); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar
> DiagCleanup(Diags.get()); std::unique_ptr
> RemappedFiles( new std::vector
()); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar< std::vector
> RemappedCleanup(RemappedFiles.get()); for (auto &UF : unsaved_files) { std::unique_ptr
MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); } std::unique_ptr
> Args( new std::vector
()); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar
> ArgsCleanup(Args.get()); // Since the Clang C library is primarily used by batch tools dealing with // (often very broken) source code, where spell-checking can have a // significant negative impact on performance (particularly when // precompiled headers are involved), we disable it by default. // Only do this if we haven't found a spell-checking-related argument. bool FoundSpellCheckingArgument = false; for (int I = 0; I != num_command_line_args; ++I) { if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || strcmp(command_line_args[I], "-fspell-checking") == 0) { FoundSpellCheckingArgument = true; break; } } Args->insert(Args->end(), command_line_args, command_line_args + num_command_line_args); if (!FoundSpellCheckingArgument) Args->insert(Args->begin() + 1, "-fno-spell-checking"); // The 'source_filename' argument is optional. If the caller does not // specify it then it is assumed that the source file is specified // in the actual argument list. // Put the source file after command_line_args otherwise if '-x' flag is // present it will be unused. if (source_filename) Args->push_back(source_filename); // Do we need the detailed preprocessing record? if (options & CXTranslationUnit_DetailedPreprocessingRecord) { Args->push_back("-Xclang"); Args->push_back("-detailed-preprocessing-record"); } unsigned NumErrors = Diags->getClient()->getNumErrors(); std::unique_ptr
ErrUnit; // Unless the user specified that they want the preamble on the first parse // set it up to be created on the first reparse. This makes the first parse // faster, trading for a slower (first) reparse. unsigned PrecompilePreambleAfterNParses = !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse; std::unique_ptr
Unit(ASTUnit::LoadFromCommandLine( Args->data(), Args->data() + Args->size(), CXXIdx->getPCHContainerOperations(), Diags, CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), /*CaptureDiagnostics=*/true, *RemappedFiles.get(), /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses, TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, /*UserFilesAreVolatile=*/true, ForSerialization, CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(), &ErrUnit)); // Early failures in LoadFromCommandLine may return with ErrUnit unset. if (!Unit && !ErrUnit) return CXError_ASTReadError; if (NumErrors != Diags->getClient()->getNumErrors()) { // Make sure to check that 'Unit' is non-NULL. if (CXXIdx->getDisplayDiagnostics()) printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); } if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) return CXError_ASTReadError; *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release()); return *out_TU ? CXError_Success : CXError_Failure; } CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options) { CXTranslationUnit TU; enum CXErrorCode Result = clang_parseTranslationUnit2( CIdx, source_filename, command_line_args, num_command_line_args, unsaved_files, num_unsaved_files, options, &TU); (void)Result; assert((TU && Result == CXError_Success) || (!TU && Result != CXError_Success)); return TU; } enum CXErrorCode clang_parseTranslationUnit2( CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options, CXTranslationUnit *out_TU) { SmallVector
Args; Args.push_back("clang"); Args.append(command_line_args, command_line_args + num_command_line_args); return clang_parseTranslationUnit2FullArgv( CIdx, source_filename, Args.data(), Args.size(), unsaved_files, num_unsaved_files, options, out_TU); } enum CXErrorCode clang_parseTranslationUnit2FullArgv( CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options, CXTranslationUnit *out_TU) { LOG_FUNC_SECTION { *Log << source_filename << ": "; for (int i = 0; i != num_command_line_args; ++i) *Log << command_line_args[i] << " "; } if (num_unsaved_files && !unsaved_files) return CXError_InvalidArguments; CXErrorCode result = CXError_Failure; auto ParseTranslationUnitImpl = [=, &result] { result = clang_parseTranslationUnit_Impl( CIdx, source_filename, command_line_args, num_command_line_args, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU); }; llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, ParseTranslationUnitImpl)) { fprintf(stderr, "libclang: crash detected during parsing: {\n"); fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); fprintf(stderr, " 'command_line_args' : ["); for (int i = 0; i != num_command_line_args; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "'%s'", command_line_args[i]); } fprintf(stderr, "],\n"); fprintf(stderr, " 'unsaved_files' : ["); for (unsigned i = 0; i != num_unsaved_files; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, unsaved_files[i].Length); } fprintf(stderr, "],\n"); fprintf(stderr, " 'options' : %d,\n", options); fprintf(stderr, "}\n"); return CXError_Crashed; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { if (CXTranslationUnit *TU = out_TU) PrintLibclangResourceUsage(*TU); } return result; } CXString clang_Type_getObjCEncoding(CXType CT) { CXTranslationUnit tu = static_cast
(CT.data[1]); ASTContext &Ctx = getASTUnit(tu)->getASTContext(); std::string encoding; Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding); return cxstring::createDup(encoding); } static const IdentifierInfo *getMacroIdentifier(CXCursor C) { if (C.kind == CXCursor_MacroDefinition) { if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C)) return MDR->getName(); } else if (C.kind == CXCursor_MacroExpansion) { MacroExpansionCursor ME = getCursorMacroExpansion(C); return ME.getName(); } return nullptr; } unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) { const IdentifierInfo *II = getMacroIdentifier(C); if (!II) { return false; } ASTUnit *ASTU = getCursorASTUnit(C); Preprocessor &PP = ASTU->getPreprocessor(); if (const MacroInfo *MI = PP.getMacroInfo(II)) return MI->isFunctionLike(); return false; } unsigned clang_Cursor_isMacroBuiltin(CXCursor C) { const IdentifierInfo *II = getMacroIdentifier(C); if (!II) { return false; } ASTUnit *ASTU = getCursorASTUnit(C); Preprocessor &PP = ASTU->getPreprocessor(); if (const MacroInfo *MI = PP.getMacroInfo(II)) return MI->isBuiltinMacro(); return false; } unsigned clang_Cursor_isFunctionInlined(CXCursor C) { const Decl *D = getCursorDecl(C); const FunctionDecl *FD = dyn_cast_or_null
(D); if (!FD) { return false; } return FD->isInlined(); } static StringLiteral* getCFSTR_value(CallExpr *callExpr) { if (callExpr->getNumArgs() != 1) { return nullptr; } StringLiteral *S = nullptr; auto *arg = callExpr->getArg(0); if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) { ImplicitCastExpr *I = static_cast
(arg); auto *subExpr = I->getSubExprAsWritten(); if(subExpr->getStmtClass() != Stmt::StringLiteralClass){ return nullptr; } S = static_cast
(I->getSubExprAsWritten()); } else if (arg->getStmtClass() == Stmt::StringLiteralClass) { S = static_cast
(callExpr->getArg(0)); } else { return nullptr; } return S; } struct ExprEvalResult { CXEvalResultKind EvalType; union { int intVal; double floatVal; char *stringVal; } EvalData; ~ExprEvalResult() { if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float && EvalType != CXEval_Int) { delete EvalData.stringVal; } } }; void clang_EvalResult_dispose(CXEvalResult E) { delete static_cast
(E); } CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) { if (!E) { return CXEval_UnExposed; } return ((ExprEvalResult *)E)->EvalType; } int clang_EvalResult_getAsInt(CXEvalResult E) { if (!E) { return 0; } return ((ExprEvalResult *)E)->EvalData.intVal; } double clang_EvalResult_getAsDouble(CXEvalResult E) { if (!E) { return 0; } return ((ExprEvalResult *)E)->EvalData.floatVal; } const char* clang_EvalResult_getAsStr(CXEvalResult E) { if (!E) { return nullptr; } return ((ExprEvalResult *)E)->EvalData.stringVal; } static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) { Expr::EvalResult ER; ASTContext &ctx = getCursorContext(C); if (!expr) return nullptr; expr = expr->IgnoreParens(); if (!expr->EvaluateAsRValue(ER, ctx)) return nullptr; QualType rettype; CallExpr *callExpr; auto result = llvm::make_unique
(); result->EvalType = CXEval_UnExposed; if (ER.Val.isInt()) { result->EvalType = CXEval_Int; result->EvalData.intVal = ER.Val.getInt().getExtValue(); return result.release(); } if (ER.Val.isFloat()) { llvm::SmallVector
Buffer; ER.Val.getFloat().toString(Buffer); std::string floatStr(Buffer.data(), Buffer.size()); result->EvalType = CXEval_Float; bool ignored; llvm::APFloat apFloat = ER.Val.getFloat(); apFloat.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven, &ignored); result->EvalData.floatVal = apFloat.convertToDouble(); return result.release(); } if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) { const ImplicitCastExpr *I = dyn_cast
(expr); auto *subExpr = I->getSubExprAsWritten(); if (subExpr->getStmtClass() == Stmt::StringLiteralClass || subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) { const StringLiteral *StrE = nullptr; const ObjCStringLiteral *ObjCExpr; ObjCExpr = dyn_cast
(subExpr); if (ObjCExpr) { StrE = ObjCExpr->getString(); result->EvalType = CXEval_ObjCStrLiteral; } else { StrE = cast
(I->getSubExprAsWritten()); result->EvalType = CXEval_StrLiteral; } std::string strRef(StrE->getString().str()); result->EvalData.stringVal = new char[strRef.size() + 1]; strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); result->EvalData.stringVal[strRef.size()] = '\0'; return result.release(); } } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass || expr->getStmtClass() == Stmt::StringLiteralClass) { const StringLiteral *StrE = nullptr; const ObjCStringLiteral *ObjCExpr; ObjCExpr = dyn_cast
(expr); if (ObjCExpr) { StrE = ObjCExpr->getString(); result->EvalType = CXEval_ObjCStrLiteral; } else { StrE = cast
(expr); result->EvalType = CXEval_StrLiteral; } std::string strRef(StrE->getString().str()); result->EvalData.stringVal = new char[strRef.size() + 1]; strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); result->EvalData.stringVal[strRef.size()] = '\0'; return result.release(); } if (expr->getStmtClass() == Stmt::CStyleCastExprClass) { CStyleCastExpr *CC = static_cast
(expr); rettype = CC->getType(); if (rettype.getAsString() == "CFStringRef" && CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) { callExpr = static_cast
(CC->getSubExpr()); StringLiteral *S = getCFSTR_value(callExpr); if (S) { std::string strLiteral(S->getString().str()); result->EvalType = CXEval_CFStr; result->EvalData.stringVal = new char[strLiteral.size() + 1]; strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), strLiteral.size()); result->EvalData.stringVal[strLiteral.size()] = '\0'; return result.release(); } } } else if (expr->getStmtClass() == Stmt::CallExprClass) { callExpr = static_cast
(expr); rettype = callExpr->getCallReturnType(ctx); if (rettype->isVectorType() || callExpr->getNumArgs() > 1) return nullptr; if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) { if (callExpr->getNumArgs() == 1 && !callExpr->getArg(0)->getType()->isIntegralType(ctx)) return nullptr; } else if (rettype.getAsString() == "CFStringRef") { StringLiteral *S = getCFSTR_value(callExpr); if (S) { std::string strLiteral(S->getString().str()); result->EvalType = CXEval_CFStr; result->EvalData.stringVal = new char[strLiteral.size() + 1]; strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), strLiteral.size()); result->EvalData.stringVal[strLiteral.size()] = '\0'; return result.release(); } } } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) { DeclRefExpr *D = static_cast
(expr); ValueDecl *V = D->getDecl(); if (V->getKind() == Decl::Function) { std::string strName = V->getNameAsString(); result->EvalType = CXEval_Other; result->EvalData.stringVal = new char[strName.size() + 1]; strncpy(result->EvalData.stringVal, strName.c_str(), strName.size()); result->EvalData.stringVal[strName.size()] = '\0'; return result.release(); } } return nullptr; } CXEvalResult clang_Cursor_Evaluate(CXCursor C) { const Decl *D = getCursorDecl(C); if (D) { const Expr *expr = nullptr; if (auto *Var = dyn_cast
(D)) { expr = Var->getInit(); } else if (auto *Field = dyn_cast
(D)) { expr = Field->getInClassInitializer(); } if (expr) return const_cast
(reinterpret_cast
( evaluateExpr(const_cast
(expr), C))); return nullptr; } const CompoundStmt *compoundStmt = dyn_cast_or_null
(getCursorStmt(C)); if (compoundStmt) { Expr *expr = nullptr; for (auto *bodyIterator : compoundStmt->body()) { if ((expr = dyn_cast
(bodyIterator))) { break; } } if (expr) return const_cast
( reinterpret_cast
(evaluateExpr(expr, C))); } return nullptr; } unsigned clang_Cursor_hasAttrs(CXCursor C) { const Decl *D = getCursorDecl(C); if (!D) { return 0; } if (D->hasAttrs()) { return 1; } return 0; } unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { return CXSaveTranslationUnit_None; } static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU, const char *FileName, unsigned options) { CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); bool hadError = cxtu::getASTUnit(TU)->Save(FileName); return hadError ? CXSaveError_Unknown : CXSaveError_None; } int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, unsigned options) { LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; } if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return CXSaveError_InvalidTU; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (!CXXUnit->hasSema()) return CXSaveError_InvalidTU; CXSaveError result; auto SaveTranslationUnitImpl = [=, &result]() { result = clang_saveTranslationUnit_Impl(TU, FileName, options); }; if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() || getenv("LIBCLANG_NOTHREADS")) { SaveTranslationUnitImpl(); if (getenv("LIBCLANG_RESOURCE_USAGE")) PrintLibclangResourceUsage(TU); return result; } // We have an AST that has invalid nodes due to compiler errors. // Use a crash recovery thread for protection. llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, SaveTranslationUnitImpl)) { fprintf(stderr, "libclang: crash detected during AST saving: {\n"); fprintf(stderr, " 'filename' : '%s'\n", FileName); fprintf(stderr, " 'options' : %d,\n", options); fprintf(stderr, "}\n"); return CXSaveError_Unknown; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { PrintLibclangResourceUsage(TU); } return result; } void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { if (CTUnit) { // If the translation unit has been marked as unsafe to free, just discard // it. ASTUnit *Unit = cxtu::getASTUnit(CTUnit); if (Unit && Unit->isUnsafeToFree()) return; delete cxtu::getASTUnit(CTUnit); delete CTUnit->StringPool; delete static_cast
(CTUnit->Diagnostics); disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); delete CTUnit->CommentToXML; delete CTUnit; } } unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { return CXReparse_None; } static CXErrorCode clang_reparseTranslationUnit_Impl(CXTranslationUnit TU, ArrayRef
unsaved_files, unsigned options) { // Check arguments. if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return CXError_InvalidArguments; } // Reset the associated diagnostics. delete static_cast
(TU->Diagnostics); TU->Diagnostics = nullptr; CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) setThreadBackgroundPriority(); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); std::unique_ptr
> RemappedFiles( new std::vector
()); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar< std::vector
> RemappedCleanup(RemappedFiles.get()); for (auto &UF : unsaved_files) { std::unique_ptr
MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); } if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(), *RemappedFiles.get())) return CXError_Success; if (isASTReadError(CXXUnit)) return CXError_ASTReadError; return CXError_Failure; } int clang_reparseTranslationUnit(CXTranslationUnit TU, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files, unsigned options) { LOG_FUNC_SECTION { *Log << TU; } if (num_unsaved_files && !unsaved_files) return CXError_InvalidArguments; CXErrorCode result; auto ReparseTranslationUnitImpl = [=, &result]() { result = clang_reparseTranslationUnit_Impl( TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options); }; if (getenv("LIBCLANG_NOTHREADS")) { ReparseTranslationUnitImpl(); return result; } llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, ReparseTranslationUnitImpl)) { fprintf(stderr, "libclang: crash detected during reparsing\n"); cxtu::getASTUnit(TU)->setUnsafeToFree(true); return CXError_Crashed; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) PrintLibclangResourceUsage(TU); return result; } CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { if (isNotUsableTU(CTUnit)) { LOG_BAD_TU(CTUnit); return cxstring::createEmpty(); } ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); return cxstring::createDup(CXXUnit->getOriginalSourceFileName()); } CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullCursor(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); } } // end: extern "C" //===----------------------------------------------------------------------===// // CXFile Operations. //===----------------------------------------------------------------------===// extern "C" { CXString clang_getFileName(CXFile SFile) { if (!SFile) return cxstring::createNull(); FileEntry *FEnt = static_cast
(SFile); return cxstring::createRef(FEnt->getName()); } time_t clang_getFileTime(CXFile SFile) { if (!SFile) return 0; FileEntry *FEnt = static_cast
(SFile); return FEnt->getModificationTime(); } CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return nullptr; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); FileManager &FMgr = CXXUnit->getFileManager(); return const_cast
(FMgr.getFile(file_name)); } unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return 0; } if (!file) return 0; ASTUnit *CXXUnit = cxtu::getASTUnit(TU); FileEntry *FEnt = static_cast
(file); return CXXUnit->getPreprocessor().getHeaderSearchInfo() .isFileMultipleIncludeGuarded(FEnt); } int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) { if (!file || !outID) return 1; FileEntry *FEnt = static_cast
(file); const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID(); outID->data[0] = ID.getDevice(); outID->data[1] = ID.getFile(); outID->data[2] = FEnt->getModificationTime(); return 0; } int clang_File_isEqual(CXFile file1, CXFile file2) { if (file1 == file2) return true; if (!file1 || !file2) return false; FileEntry *FEnt1 = static_cast
(file1); FileEntry *FEnt2 = static_cast
(file2); return FEnt1->getUniqueID() == FEnt2->getUniqueID(); } } // end: extern "C" //===----------------------------------------------------------------------===// // CXCursor Operations. //===----------------------------------------------------------------------===// static const Decl *getDeclFromExpr(const Stmt *E) { if (const ImplicitCastExpr *CE = dyn_cast
(E)) return getDeclFromExpr(CE->getSubExpr()); if (const DeclRefExpr *RefExpr = dyn_cast
(E)) return RefExpr->getDecl(); if (const MemberExpr *ME = dyn_cast
(E)) return ME->getMemberDecl(); if (const ObjCIvarRefExpr *RE = dyn_cast
(E)) return RE->getDecl(); if (const ObjCPropertyRefExpr *PRE = dyn_cast
(E)) { if (PRE->isExplicitProperty()) return PRE->getExplicitProperty(); // It could be messaging both getter and setter as in: // ++myobj.myprop; // in which case prefer to associate the setter since it is less obvious // from inspecting the source that the setter is going to get called. if (PRE->isMessagingSetter()) return PRE->getImplicitPropertySetter(); return PRE->getImplicitPropertyGetter(); } if (const PseudoObjectExpr *POE = dyn_cast
(E)) return getDeclFromExpr(POE->getSyntacticForm()); if (const OpaqueValueExpr *OVE = dyn_cast
(E)) if (Expr *Src = OVE->getSourceExpr()) return getDeclFromExpr(Src); if (const CallExpr *CE = dyn_cast
(E)) return getDeclFromExpr(CE->getCallee()); if (const CXXConstructExpr *CE = dyn_cast
(E)) if (!CE->isElidable()) return CE->getConstructor(); if (const CXXInheritedCtorInitExpr *CE = dyn_cast
(E)) return CE->getConstructor(); if (const ObjCMessageExpr *OME = dyn_cast
(E)) return OME->getMethodDecl(); if (const ObjCProtocolExpr *PE = dyn_cast
(E)) return PE->getProtocol(); if (const SubstNonTypeTemplateParmPackExpr *NTTP = dyn_cast
(E)) return NTTP->getParameterPack(); if (const SizeOfPackExpr *SizeOfPack = dyn_cast
(E)) if (isa
(SizeOfPack->getPack()) || isa
(SizeOfPack->getPack())) return SizeOfPack->getPack(); return nullptr; } static SourceLocation getLocationFromExpr(const Expr *E) { if (const ImplicitCastExpr *CE = dyn_cast
(E)) return getLocationFromExpr(CE->getSubExpr()); if (const ObjCMessageExpr *Msg = dyn_cast
(E)) return /*FIXME:*/Msg->getLeftLoc(); if (const DeclRefExpr *DRE = dyn_cast
(E)) return DRE->getLocation(); if (const MemberExpr *Member = dyn_cast
(E)) return Member->getMemberLoc(); if (const ObjCIvarRefExpr *Ivar = dyn_cast
(E)) return Ivar->getLocation(); if (const SizeOfPackExpr *SizeOfPack = dyn_cast
(E)) return SizeOfPack->getPackLoc(); if (const ObjCPropertyRefExpr *PropRef = dyn_cast
(E)) return PropRef->getLocation(); return E->getLocStart(); } extern "C" { unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor, CXClientData client_data) { CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, /*VisitPreprocessorLast=*/false); return CursorVis.VisitChildren(parent); } #ifndef __has_feature #define __has_feature(x) 0 #endif #if __has_feature(blocks) typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; return block(cursor, parent); } #else // If we are compiled with a compiler that doesn't have native blocks support, // define and call the block manually, so the typedef struct _CXChildVisitResult { void *isa; int flags; int reserved; enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, CXCursor); } *CXCursorVisitorBlock; static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; return block->invoke(block, cursor, parent); } #endif unsigned clang_visitChildrenWithBlock(CXCursor parent, CXCursorVisitorBlock block) { return clang_visitChildren(parent, visitWithBlock, block); } static CXString getDeclSpelling(const Decl *D) { if (!D) return cxstring::createEmpty(); const NamedDecl *ND = dyn_cast
(D); if (!ND) { if (const ObjCPropertyImplDecl *PropImpl = dyn_cast
(D)) if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) return cxstring::createDup(Property->getIdentifier()->getName()); if (const ImportDecl *ImportD = dyn_cast
(D)) if (Module *Mod = ImportD->getImportedModule()) return cxstring::createDup(Mod->getFullModuleName()); return cxstring::createEmpty(); } if (const ObjCMethodDecl *OMD = dyn_cast
(ND)) return cxstring::createDup(OMD->getSelector().getAsString()); if (const ObjCCategoryImplDecl *CIMP = dyn_cast
(ND)) // No, this isn't the same as the code below. getIdentifier() is non-virtual // and returns different names. NamedDecl returns the class name and // ObjCCategoryImplDecl returns the category name. return cxstring::createRef(CIMP->getIdentifier()->getNameStart()); if (isa
(D)) return cxstring::createEmpty(); SmallString<1024> S; llvm::raw_svector_ostream os(S); ND->printName(os); return cxstring::createDup(os.str()); } CXString clang_getCursorSpelling(CXCursor C) { if (clang_isTranslationUnit(C.kind)) return clang_getTranslationUnitSpelling(getCursorTU(C)); if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: { const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; return cxstring::createRef(Super->getIdentifier()->getNameStart()); } case CXCursor_ObjCClassRef: { const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; return cxstring::createRef(Class->getIdentifier()->getNameStart()); } case CXCursor_ObjCProtocolRef: { const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; assert(OID && "getCursorSpelling(): Missing protocol decl"); return cxstring::createRef(OID->getIdentifier()->getNameStart()); } case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); return cxstring::createDup(B->getType().getAsString()); } case CXCursor_TypeRef: { const TypeDecl *Type = getCursorTypeRef(C).first; assert(Type && "Missing type decl"); return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type). getAsString()); } case CXCursor_TemplateRef: { const TemplateDecl *Template = getCursorTemplateRef(C).first; assert(Template && "Missing template decl"); return cxstring::createDup(Template->getNameAsString()); } case CXCursor_NamespaceRef: { const NamedDecl *NS = getCursorNamespaceRef(C).first; assert(NS && "Missing namespace decl"); return cxstring::createDup(NS->getNameAsString()); } case CXCursor_MemberRef: { const FieldDecl *Field = getCursorMemberRef(C).first; assert(Field && "Missing member decl"); return cxstring::createDup(Field->getNameAsString()); } case CXCursor_LabelRef: { const LabelStmt *Label = getCursorLabelRef(C).first; assert(Label && "Missing label"); return cxstring::createRef(Label->getName()); } case CXCursor_OverloadedDeclRef: { OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; if (const Decl *D = Storage.dyn_cast
()) { if (const NamedDecl *ND = dyn_cast
(D)) return cxstring::createDup(ND->getNameAsString()); return cxstring::createEmpty(); } if (const OverloadExpr *E = Storage.dyn_cast
()) return cxstring::createDup(E->getName().getAsString()); OverloadedTemplateStorage *Ovl = Storage.get
(); if (Ovl->size() == 0) return cxstring::createEmpty(); return cxstring::createDup((*Ovl->begin())->getNameAsString()); } case CXCursor_VariableRef: { const VarDecl *Var = getCursorVariableRef(C).first; assert(Var && "Missing variable decl"); return cxstring::createDup(Var->getNameAsString()); } default: return cxstring::createRef("
"); } } if (clang_isExpression(C.kind)) { const Expr *E = getCursorExpr(C); if (C.kind == CXCursor_ObjCStringLiteral || C.kind == CXCursor_StringLiteral) { const StringLiteral *SLit; if (const ObjCStringLiteral *OSL = dyn_cast
(E)) { SLit = OSL->getString(); } else { SLit = cast
(E); } SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); SLit->outputString(OS); return cxstring::createDup(OS.str()); } const Decl *D = getDeclFromExpr(getCursorExpr(C)); if (D) return getDeclSpelling(D); return cxstring::createEmpty(); } if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const LabelStmt *Label = dyn_cast_or_null
(S)) return cxstring::createRef(Label->getName()); return cxstring::createEmpty(); } if (C.kind == CXCursor_MacroExpansion) return cxstring::createRef(getCursorMacroExpansion(C).getName() ->getNameStart()); if (C.kind == CXCursor_MacroDefinition) return cxstring::createRef(getCursorMacroDefinition(C)->getName() ->getNameStart()); if (C.kind == CXCursor_InclusionDirective) return cxstring::createDup(getCursorInclusionDirective(C)->getFileName()); if (clang_isDeclaration(C.kind)) return getDeclSpelling(getCursorDecl(C)); if (C.kind == CXCursor_AnnotateAttr) { const AnnotateAttr *AA = cast
(cxcursor::getCursorAttr(C)); return cxstring::createDup(AA->getAnnotation()); } if (C.kind == CXCursor_AsmLabelAttr) { const AsmLabelAttr *AA = cast
(cxcursor::getCursorAttr(C)); return cxstring::createDup(AA->getLabel()); } if (C.kind == CXCursor_PackedAttr) { return cxstring::createRef("packed"); } if (C.kind == CXCursor_VisibilityAttr) { const VisibilityAttr *AA = cast
(cxcursor::getCursorAttr(C)); switch (AA->getVisibility()) { case VisibilityAttr::VisibilityType::Default: return cxstring::createRef("default"); case VisibilityAttr::VisibilityType::Hidden: return cxstring::createRef("hidden"); case VisibilityAttr::VisibilityType::Protected: return cxstring::createRef("protected"); } llvm_unreachable("unknown visibility type"); } return cxstring::createEmpty(); } CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex, unsigned options) { if (clang_Cursor_isNull(C)) return clang_getNullRange(); ASTContext &Ctx = getCursorContext(C); if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const LabelStmt *Label = dyn_cast_or_null
(S)) { if (pieceIndex > 0) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); } return clang_getNullRange(); } if (C.kind == CXCursor_ObjCMessageExpr) { if (const ObjCMessageExpr * ME = dyn_cast_or_null
(getCursorExpr(C))) { if (pieceIndex >= ME->getNumSelectorLocs()) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); } } if (C.kind == CXCursor_ObjCInstanceMethodDecl || C.kind == CXCursor_ObjCClassMethodDecl) { if (const ObjCMethodDecl * MD = dyn_cast_or_null
(getCursorDecl(C))) { if (pieceIndex >= MD->getNumSelectorLocs()) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); } } if (C.kind == CXCursor_ObjCCategoryDecl || C.kind == CXCursor_ObjCCategoryImplDecl) { if (pieceIndex > 0) return clang_getNullRange(); if (const ObjCCategoryDecl * CD = dyn_cast_or_null
(getCursorDecl(C))) return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); if (const ObjCCategoryImplDecl * CID = dyn_cast_or_null
(getCursorDecl(C))) return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); } if (C.kind == CXCursor_ModuleImportDecl) { if (pieceIndex > 0) return clang_getNullRange(); if (const ImportDecl *ImportD = dyn_cast_or_null
(getCursorDecl(C))) { ArrayRef
Locs = ImportD->getIdentifierLocs(); if (!Locs.empty()) return cxloc::translateSourceRange(Ctx, SourceRange(Locs.front(), Locs.back())); } return clang_getNullRange(); } if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor || C.kind == CXCursor_ConversionFunction) { if (pieceIndex > 0) return clang_getNullRange(); if (const FunctionDecl *FD = dyn_cast_or_null
(getCursorDecl(C))) { DeclarationNameInfo FunctionName = FD->getNameInfo(); return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange()); } return clang_getNullRange(); } // FIXME: A CXCursor_InclusionDirective should give the location of the // filename, but we don't keep track of this. // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation // but we don't keep track of this. // FIXME: A CXCursor_AsmLabelAttr should give the location of the label // but we don't keep track of this. // Default handling, give the location of the cursor. if (pieceIndex > 0) return clang_getNullRange(); CXSourceLocation CXLoc = clang_getCursorLocation(C); SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); return cxloc::translateSourceRange(Ctx, Loc); } CXString clang_Cursor_getMangling(CXCursor C) { if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) return cxstring::createEmpty(); // Mangling only works for functions and variables. const Decl *D = getCursorDecl(C); if (!D || !(isa
(D) || isa
(D))) return cxstring::createEmpty(); ASTContext &Ctx = D->getASTContext(); index::CodegenNameGenerator CGNameGen(Ctx); return cxstring::createDup(CGNameGen.getName(D)); } CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) { if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) return nullptr; const Decl *D = getCursorDecl(C); if (!(isa
(D) || isa
(D))) return nullptr; ASTContext &Ctx = D->getASTContext(); index::CodegenNameGenerator CGNameGen(Ctx); std::vector
Manglings = CGNameGen.getAllManglings(D); return cxstring::createSet(Manglings); } CXString clang_getCursorDisplayName(CXCursor C) { if (!clang_isDeclaration(C.kind)) return clang_getCursorSpelling(C); const Decl *D = getCursorDecl(C); if (!D) return cxstring::createEmpty(); PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); if (const FunctionTemplateDecl *FunTmpl = dyn_cast
(D)) D = FunTmpl->getTemplatedDecl(); if (const FunctionDecl *Function = dyn_cast
(D)) { SmallString<64> Str; llvm::raw_svector_ostream OS(Str); OS << *Function; if (Function->getPrimaryTemplate()) OS << "<>"; OS << "("; for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { if (I) OS << ", "; OS << Function->getParamDecl(I)->getType().getAsString(Policy); } if (Function->isVariadic()) { if (Function->getNumParams()) OS << ", "; OS << "..."; } OS << ")"; return cxstring::createDup(OS.str()); } if (const ClassTemplateDecl *ClassTemplate = dyn_cast
(D)) { SmallString<64> Str; llvm::raw_svector_ostream OS(Str); OS << *ClassTemplate; OS << "<"; TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); for (unsigned I = 0, N = Params->size(); I != N; ++I) { if (I) OS << ", "; NamedDecl *Param = Params->getParam(I); if (Param->getIdentifier()) { OS << Param->getIdentifier()->getName(); continue; } // There is no parameter name, which makes this tricky. Try to come up // with something useful that isn't too long. if (TemplateTypeParmDecl *TTP = dyn_cast
(Param)) OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); else if (NonTypeTemplateParmDecl *NTTP = dyn_cast
(Param)) OS << NTTP->getType().getAsString(Policy); else OS << "template<...> class"; } OS << ">"; return cxstring::createDup(OS.str()); } if (const ClassTemplateSpecializationDecl *ClassSpec = dyn_cast
(D)) { // If the type was explicitly written, use that. if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) return cxstring::createDup(TSInfo->getType().getAsString(Policy)); SmallString<128> Str; llvm::raw_svector_ostream OS(Str); OS << *ClassSpec; TemplateSpecializationType::PrintTemplateArgumentList( OS, ClassSpec->getTemplateArgs().asArray(), Policy); return cxstring::createDup(OS.str()); } return clang_getCursorSpelling(C); } CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { switch (Kind) { case CXCursor_FunctionDecl: return cxstring::createRef("FunctionDecl"); case CXCursor_TypedefDecl: return cxstring::createRef("TypedefDecl"); case CXCursor_EnumDecl: return cxstring::createRef("EnumDecl"); case CXCursor_EnumConstantDecl: return cxstring::createRef("EnumConstantDecl"); case CXCursor_StructDecl: return cxstring::createRef("StructDecl"); case CXCursor_UnionDecl: return cxstring::createRef("UnionDecl"); case CXCursor_ClassDecl: return cxstring::createRef("ClassDecl"); case CXCursor_FieldDecl: return cxstring::createRef("FieldDecl"); case CXCursor_VarDecl: return cxstring::createRef("VarDecl"); case CXCursor_ParmDecl: return cxstring::createRef("ParmDecl"); case CXCursor_ObjCInterfaceDecl: return cxstring::createRef("ObjCInterfaceDecl"); case CXCursor_ObjCCategoryDecl: return cxstring::createRef("ObjCCategoryDecl"); case CXCursor_ObjCProtocolDecl: return cxstring::createRef("ObjCProtocolDecl"); case CXCursor_ObjCPropertyDecl: return cxstring::createRef("ObjCPropertyDecl"); case CXCursor_ObjCIvarDecl: return cxstring::createRef("ObjCIvarDecl"); case CXCursor_ObjCInstanceMethodDecl: return cxstring::createRef("ObjCInstanceMethodDecl"); case CXCursor_ObjCClassMethodDecl: return cxstring::createRef("ObjCClassMethodDecl"); case CXCursor_ObjCImplementationDecl: return cxstring::createRef("ObjCImplementationDecl"); case CXCursor_ObjCCategoryImplDecl: return cxstring::createRef("ObjCCategoryImplDecl"); case CXCursor_CXXMethod: return cxstring::createRef("CXXMethod"); case CXCursor_UnexposedDecl: return cxstring::createRef("UnexposedDecl"); case CXCursor_ObjCSuperClassRef: return cxstring::createRef("ObjCSuperClassRef"); case CXCursor_ObjCProtocolRef: return cxstring::createRef("ObjCProtocolRef"); case CXCursor_ObjCClassRef: return cxstring::createRef("ObjCClassRef"); case CXCursor_TypeRef: return cxstring::createRef("TypeRef"); case CXCursor_TemplateRef: return cxstring::createRef("TemplateRef"); case CXCursor_NamespaceRef: return cxstring::createRef("NamespaceRef"); case CXCursor_MemberRef: return cxstring::createRef("MemberRef"); case CXCursor_LabelRef: return cxstring::createRef("LabelRef"); case CXCursor_OverloadedDeclRef: return cxstring::createRef("OverloadedDeclRef"); case CXCursor_VariableRef: return cxstring::createRef("VariableRef"); case CXCursor_IntegerLiteral: return cxstring::createRef("IntegerLiteral"); case CXCursor_FloatingLiteral: return cxstring::createRef("FloatingLiteral"); case CXCursor_ImaginaryLiteral: return cxstring::createRef("ImaginaryLiteral"); case CXCursor_StringLiteral: return cxstring::createRef("StringLiteral"); case CXCursor_CharacterLiteral: return cxstring::createRef("CharacterLiteral"); case CXCursor_ParenExpr: return cxstring::createRef("ParenExpr"); case CXCursor_UnaryOperator: return cxstring::createRef("UnaryOperator"); case CXCursor_ArraySubscriptExpr: return cxstring::createRef("ArraySubscriptExpr"); case CXCursor_OMPArraySectionExpr: return cxstring::createRef("OMPArraySectionExpr"); case CXCursor_BinaryOperator: return cxstring::createRef("BinaryOperator"); case CXCursor_CompoundAssignOperator: return cxstring::createRef("CompoundAssignOperator"); case CXCursor_ConditionalOperator: return cxstring::createRef("ConditionalOperator"); case CXCursor_CStyleCastExpr: return cxstring::createRef("CStyleCastExpr"); case CXCursor_CompoundLiteralExpr: return cxstring::createRef("CompoundLiteralExpr"); case CXCursor_InitListExpr: return cxstring::createRef("InitListExpr"); case CXCursor_AddrLabelExpr: return cxstring::createRef("AddrLabelExpr"); case CXCursor_StmtExpr: return cxstring::createRef("StmtExpr"); case CXCursor_GenericSelectionExpr: return cxstring::createRef("GenericSelectionExpr"); case CXCursor_GNUNullExpr: return cxstring::createRef("GNUNullExpr"); case CXCursor_CXXStaticCastExpr: return cxstring::createRef("CXXStaticCastExpr"); case CXCursor_CXXDynamicCastExpr: return cxstring::createRef("CXXDynamicCastExpr"); case CXCursor_CXXReinterpretCastExpr: return cxstring::createRef("CXXReinterpretCastExpr"); case CXCursor_CXXConstCastExpr: return cxstring::createRef("CXXConstCastExpr"); case CXCursor_CXXFunctionalCastExpr: return cxstring::createRef("CXXFunctionalCastExpr"); case CXCursor_CXXTypeidExpr: return cxstring::createRef("CXXTypeidExpr"); case CXCursor_CXXBoolLiteralExpr: return cxstring::createRef("CXXBoolLiteralExpr"); case CXCursor_CXXNullPtrLiteralExpr: return cxstring::createRef("CXXNullPtrLiteralExpr"); case CXCursor_CXXThisExpr: return cxstring::createRef("CXXThisExpr"); case CXCursor_CXXThrowExpr: return cxstring::createRef("CXXThrowExpr"); case CXCursor_CXXNewExpr: return cxstring::createRef("CXXNewExpr"); case CXCursor_CXXDeleteExpr: return cxstring::createRef("CXXDeleteExpr"); case CXCursor_UnaryExpr: return cxstring::createRef("UnaryExpr"); case CXCursor_ObjCStringLiteral: return cxstring::createRef("ObjCStringLiteral"); case CXCursor_ObjCBoolLiteralExpr: return cxstring::createRef("ObjCBoolLiteralExpr"); case CXCursor_ObjCSelfExpr: return cxstring::createRef("ObjCSelfExpr"); case CXCursor_ObjCEncodeExpr: return cxstring::createRef("ObjCEncodeExpr"); case CXCursor_ObjCSelectorExpr: return cxstring::createRef("ObjCSelectorExpr"); case CXCursor_ObjCProtocolExpr: return cxstring::createRef("ObjCProtocolExpr"); case CXCursor_ObjCBridgedCastExpr: return cxstring::createRef("ObjCBridgedCastExpr"); case CXCursor_BlockExpr: return cxstring::createRef("BlockExpr"); case CXCursor_PackExpansionExpr: return cxstring::createRef("PackExpansionExpr"); case CXCursor_SizeOfPackExpr: return cxstring::createRef("SizeOfPackExpr"); case CXCursor_LambdaExpr: return cxstring::createRef("LambdaExpr"); case CXCursor_UnexposedExpr: return cxstring::createRef("UnexposedExpr"); case CXCursor_DeclRefExpr: return cxstring::createRef("DeclRefExpr"); case CXCursor_MemberRefExpr: return cxstring::createRef("MemberRefExpr"); case CXCursor_CallExpr: return cxstring::createRef("CallExpr"); case CXCursor_ObjCMessageExpr: return cxstring::createRef("ObjCMessageExpr"); case CXCursor_UnexposedStmt: return cxstring::createRef("UnexposedStmt"); case CXCursor_DeclStmt: return cxstring::createRef("DeclStmt"); case CXCursor_LabelStmt: return cxstring::createRef("LabelStmt"); case CXCursor_CompoundStmt: return cxstring::createRef("CompoundStmt"); case CXCursor_CaseStmt: return cxstring::createRef("CaseStmt"); case CXCursor_DefaultStmt: return cxstring::createRef("DefaultStmt"); case CXCursor_IfStmt: return cxstring::createRef("IfStmt"); case CXCursor_SwitchStmt: return cxstring::createRef("SwitchStmt"); case CXCursor_WhileStmt: return cxstring::createRef("WhileStmt"); case CXCursor_DoStmt: return cxstring::createRef("DoStmt"); case CXCursor_ForStmt: return cxstring::createRef("ForStmt"); case CXCursor_GotoStmt: return cxstring::createRef("GotoStmt"); case CXCursor_IndirectGotoStmt: return cxstring::createRef("IndirectGotoStmt"); case CXCursor_ContinueStmt: return cxstring::createRef("ContinueStmt"); case CXCursor_BreakStmt: return cxstring::createRef("BreakStmt"); case CXCursor_ReturnStmt: return cxstring::createRef("ReturnStmt"); case CXCursor_GCCAsmStmt: return cxstring::createRef("GCCAsmStmt"); case CXCursor_MSAsmStmt: return cxstring::createRef("MSAsmStmt"); case CXCursor_ObjCAtTryStmt: return cxstring::createRef("ObjCAtTryStmt"); case CXCursor_ObjCAtCatchStmt: return cxstring::createRef("ObjCAtCatchStmt"); case CXCursor_ObjCAtFinallyStmt: return cxstring::createRef("ObjCAtFinallyStmt"); case CXCursor_ObjCAtThrowStmt: return cxstring::createRef("ObjCAtThrowStmt"); case CXCursor_ObjCAtSynchronizedStmt: return cxstring::createRef("ObjCAtSynchronizedStmt"); case CXCursor_ObjCAutoreleasePoolStmt: return cxstring::createRef("ObjCAutoreleasePoolStmt"); case CXCursor_ObjCForCollectionStmt: return cxstring::createRef("ObjCForCollectionStmt"); case CXCursor_CXXCatchStmt: return cxstring::createRef("CXXCatchStmt"); case CXCursor_CXXTryStmt: return cxstring::createRef("CXXTryStmt"); case CXCursor_CXXForRangeStmt: return cxstring::createRef("CXXForRangeStmt"); case CXCursor_SEHTryStmt: return cxstring::createRef("SEHTryStmt"); case CXCursor_SEHExceptStmt: return cxstring::createRef("SEHExceptStmt"); case CXCursor_SEHFinallyStmt: return cxstring::createRef("SEHFinallyStmt"); case CXCursor_SEHLeaveStmt: return cxstring::createRef("SEHLeaveStmt"); case CXCursor_NullStmt: return cxstring::createRef("NullStmt"); case CXCursor_InvalidFile: return cxstring::createRef("InvalidFile"); case CXCursor_InvalidCode: return cxstring::createRef("InvalidCode"); case CXCursor_NoDeclFound: return cxstring::createRef("NoDeclFound"); case CXCursor_NotImplemented: return cxstring::createRef("NotImplemented"); case CXCursor_TranslationUnit: return cxstring::createRef("TranslationUnit"); case CXCursor_UnexposedAttr: return cxstring::createRef("UnexposedAttr"); case CXCursor_IBActionAttr: return cxstring::createRef("attribute(ibaction)"); case CXCursor_IBOutletAttr: return cxstring::createRef("attribute(iboutlet)"); case CXCursor_IBOutletCollectionAttr: return cxstring::createRef("attribute(iboutletcollection)"); case CXCursor_CXXFinalAttr: return cxstring::createRef("attribute(final)"); case CXCursor_CXXOverrideAttr: return cxstring::createRef("attribute(override)"); case CXCursor_AnnotateAttr: return cxstring::createRef("attribute(annotate)"); case CXCursor_AsmLabelAttr: return cxstring::createRef("asm label"); case CXCursor_PackedAttr: return cxstring::createRef("attribute(packed)"); case CXCursor_PureAttr: return cxstring::createRef("attribute(pure)"); case CXCursor_ConstAttr: return cxstring::createRef("attribute(const)"); case CXCursor_NoDuplicateAttr: return cxstring::createRef("attribute(noduplicate)"); case CXCursor_CUDAConstantAttr: return cxstring::createRef("attribute(constant)"); case CXCursor_CUDADeviceAttr: return cxstring::createRef("attribute(device)"); case CXCursor_CUDAGlobalAttr: return cxstring::createRef("attribute(global)"); case CXCursor_CUDAHostAttr: return cxstring::createRef("attribute(host)"); case CXCursor_CUDASharedAttr: return cxstring::createRef("attribute(shared)"); case CXCursor_VisibilityAttr: return cxstring::createRef("attribute(visibility)"); case CXCursor_DLLExport: return cxstring::createRef("attribute(dllexport)"); case CXCursor_DLLImport: return cxstring::createRef("attribute(dllimport)"); case CXCursor_PreprocessingDirective: return cxstring::createRef("preprocessing directive"); case CXCursor_MacroDefinition: return cxstring::createRef("macro definition"); case CXCursor_MacroExpansion: return cxstring::createRef("macro expansion"); case CXCursor_InclusionDirective: return cxstring::createRef("inclusion directive"); case CXCursor_Namespace: return cxstring::createRef("Namespace"); case CXCursor_LinkageSpec: return cxstring::createRef("LinkageSpec"); case CXCursor_CXXBaseSpecifier: return cxstring::createRef("C++ base class specifier"); case CXCursor_Constructor: return cxstring::createRef("CXXConstructor"); case CXCursor_Destructor: return cxstring::createRef("CXXDestructor"); case CXCursor_ConversionFunction: return cxstring::createRef("CXXConversion"); case CXCursor_TemplateTypeParameter: return cxstring::createRef("TemplateTypeParameter"); case CXCursor_NonTypeTemplateParameter: return cxstring::createRef("NonTypeTemplateParameter"); case CXCursor_TemplateTemplateParameter: return cxstring::createRef("TemplateTemplateParameter"); case CXCursor_FunctionTemplate: return cxstring::createRef("FunctionTemplate"); case CXCursor_ClassTemplate: return cxstring::createRef("ClassTemplate"); case CXCursor_ClassTemplatePartialSpecialization: return cxstring::createRef("ClassTemplatePartialSpecialization"); case CXCursor_NamespaceAlias: return cxstring::createRef("NamespaceAlias"); case CXCursor_UsingDirective: return cxstring::createRef("UsingDirective"); case CXCursor_UsingDeclaration: return cxstring::createRef("UsingDeclaration"); case CXCursor_TypeAliasDecl: return cxstring::createRef("TypeAliasDecl"); case CXCursor_ObjCSynthesizeDecl: return cxstring::createRef("ObjCSynthesizeDecl"); case CXCursor_ObjCDynamicDecl: return cxstring::createRef("ObjCDynamicDecl"); case CXCursor_CXXAccessSpecifier: return cxstring::createRef("CXXAccessSpecifier"); case CXCursor_ModuleImportDecl: return cxstring::createRef("ModuleImport"); case CXCursor_OMPParallelDirective: return cxstring::createRef("OMPParallelDirective"); case CXCursor_OMPSimdDirective: return cxstring::createRef("OMPSimdDirective"); case CXCursor_OMPForDirective: return cxstring::createRef("OMPForDirective"); case CXCursor_OMPForSimdDirective: return cxstring::createRef("OMPForSimdDirective"); case CXCursor_OMPSectionsDirective: return cxstring::createRef("OMPSectionsDirective"); case CXCursor_OMPSectionDirective: return cxstring::createRef("OMPSectionDirective"); case CXCursor_OMPSingleDirective: return cxstring::createRef("OMPSingleDirective"); case CXCursor_OMPMasterDirective: return cxstring::createRef("OMPMasterDirective"); case CXCursor_OMPCriticalDirective: return cxstring::createRef("OMPCriticalDirective"); case CXCursor_OMPParallelForDirective: return cxstring::createRef("OMPParallelForDirective"); case CXCursor_OMPParallelForSimdDirective: return cxstring::createRef("OMPParallelForSimdDirective"); case CXCursor_OMPParallelSectionsDirective: return cxstring::createRef("OMPParallelSectionsDirective"); case CXCursor_OMPTaskDirective: return cxstring::createRef("OMPTaskDirective"); case CXCursor_OMPTaskyieldDirective: return cxstring::createRef("OMPTaskyieldDirective"); case CXCursor_OMPBarrierDirective: return cxstring::createRef("OMPBarrierDirective"); case CXCursor_OMPTaskwaitDirective: return cxstring::createRef("OMPTaskwaitDirective"); case CXCursor_OMPTaskgroupDirective: return cxstring::createRef("OMPTaskgroupDirective"); case CXCursor_OMPFlushDirective: return cxstring::createRef("OMPFlushDirective"); case CXCursor_OMPOrderedDirective: return cxstring::createRef("OMPOrderedDirective"); case CXCursor_OMPAtomicDirective: return cxstring::createRef("OMPAtomicDirective"); case CXCursor_OMPTargetDirective: return cxstring::createRef("OMPTargetDirective"); case CXCursor_OMPTargetDataDirective: return cxstring::createRef("OMPTargetDataDirective"); case CXCursor_OMPTargetEnterDataDirective: return cxstring::createRef("OMPTargetEnterDataDirective"); case CXCursor_OMPTargetExitDataDirective: return cxstring::createRef("OMPTargetExitDataDirective"); case CXCursor_OMPTargetParallelDirective: return cxstring::createRef("OMPTargetParallelDirective"); case CXCursor_OMPTargetParallelForDirective: return cxstring::createRef("OMPTargetParallelForDirective"); case CXCursor_OMPTargetUpdateDirective: return cxstring::createRef("OMPTargetUpdateDirective"); case CXCursor_OMPTeamsDirective: return cxstring::createRef("OMPTeamsDirective"); case CXCursor_OMPCancellationPointDirective: return cxstring::createRef("OMPCancellationPointDirective"); case CXCursor_OMPCancelDirective: return cxstring::createRef("OMPCancelDirective"); case CXCursor_OMPTaskLoopDirective: return cxstring::createRef("OMPTaskLoopDirective"); case CXCursor_OMPTaskLoopSimdDirective: return cxstring::createRef("OMPTaskLoopSimdDirective"); case CXCursor_OMPDistributeDirective: return cxstring::createRef("OMPDistributeDirective"); case CXCursor_OMPDistributeParallelForDirective: return cxstring::createRef("OMPDistributeParallelForDirective"); case CXCursor_OMPDistributeParallelForSimdDirective: return cxstring::createRef("OMPDistributeParallelForSimdDirective"); case CXCursor_OMPDistributeSimdDirective: return cxstring::createRef("OMPDistributeSimdDirective"); case CXCursor_OMPTargetParallelForSimdDirective: return cxstring::createRef("OMPTargetParallelForSimdDirective"); case CXCursor_OverloadCandidate: return cxstring::createRef("OverloadCandidate"); case CXCursor_TypeAliasTemplateDecl: return cxstring::createRef("TypeAliasTemplateDecl"); case CXCursor_StaticAssert: return cxstring::createRef("StaticAssert"); } llvm_unreachable("Unhandled CXCursorKind"); } struct GetCursorData { SourceLocation TokenBeginLoc; bool PointsAtMacroArgExpansion; bool VisitedObjCPropertyImplDecl; SourceLocation VisitedDeclaratorDeclStartLoc; CXCursor &BestCursor; GetCursorData(SourceManager &SM, SourceLocation tokenBegin, CXCursor &outputCursor) : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); VisitedObjCPropertyImplDecl = false; } }; static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { GetCursorData *Data = static_cast
(client_data); CXCursor *BestCursor = &Data->BestCursor; // If we point inside a macro argument we should provide info of what the // token is so use the actual cursor, don't replace it with a macro expansion // cursor. if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) return CXChildVisit_Recurse; if (clang_isDeclaration(cursor.kind)) { // Avoid having the implicit methods override the property decls. if (const ObjCMethodDecl *MD = dyn_cast_or_null
(getCursorDecl(cursor))) { if (MD->isImplicit()) return CXChildVisit_Break; } else if (const ObjCInterfaceDecl *ID = dyn_cast_or_null
(getCursorDecl(cursor))) { // Check that when we have multiple @class references in the same line, // that later ones do not override the previous ones. // If we have: // @class Foo, Bar; // source ranges for both start at '@', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || BestCursor->kind == CXCursor_ObjCClassRef) if (const ObjCInterfaceDecl *PrevID = dyn_cast_or_null
(getCursorDecl(*BestCursor))){ if (PrevID != ID && !PrevID->isThisDeclarationADefinition() && !ID->isThisDeclarationADefinition()) return CXChildVisit_Break; } } else if (const DeclaratorDecl *DD = dyn_cast_or_null
(getCursorDecl(cursor))) { SourceLocation StartLoc = DD->getSourceRange().getBegin(); // Check that when we have multiple declarators in the same line, // that later ones do not override the previous ones. // If we have: // int Foo, Bar; // source ranges for both start at 'int', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) return CXChildVisit_Break; Data->VisitedDeclaratorDeclStartLoc = StartLoc; } else if (const ObjCPropertyImplDecl *PropImp = dyn_cast_or_null
(getCursorDecl(cursor))) { (void)PropImp; // Check that when we have multiple @synthesize in the same line, // that later ones do not override the previous ones. // If we have: // @synthesize Foo, Bar; // source ranges for both start at '@', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (Data->VisitedObjCPropertyImplDecl) return CXChildVisit_Break; Data->VisitedObjCPropertyImplDecl = true; } } if (clang_isExpression(cursor.kind) && clang_isDeclaration(BestCursor->kind)) { if (const Decl *D = getCursorDecl(*BestCursor)) { // Avoid having the cursor of an expression replace the declaration cursor // when the expression source range overlaps the declaration range. // This can happen for C++ constructor expressions whose range generally // include the variable declaration, e.g.: // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && D->getLocation() == Data->TokenBeginLoc) return CXChildVisit_Break; } } // If our current best cursor is the construction of a temporary object, // don't replace that cursor with a type reference, because we want // clang_getCursor() to point at the constructor. if (clang_isExpression(BestCursor->kind) && isa
(getCursorExpr(*BestCursor)) && cursor.kind == CXCursor_TypeRef) { // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it // as having the actual point on the type reference. *BestCursor = getTypeRefedCallExprCursor(*BestCursor); return CXChildVisit_Recurse; } // If we already have an Objective-C superclass reference, don't // update it further. if (BestCursor->kind == CXCursor_ObjCSuperClassRef) return CXChildVisit_Break; *BestCursor = cursor; return CXChildVisit_Recurse; } CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullCursor(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); SourceLocation SLoc = cxloc::translateSourceLocation(Loc); CXCursor Result = cxcursor::getCursor(TU, SLoc); LOG_FUNC_SECTION { CXFile SearchFile; unsigned SearchLine, SearchColumn; CXFile ResultFile; unsigned ResultLine, ResultColumn; CXString SearchFileName, ResultFileName, KindSpelling, USR; const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; CXSourceLocation ResultLoc = clang_getCursorLocation(Result); clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, nullptr); clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn, nullptr); SearchFileName = clang_getFileName(SearchFile); ResultFileName = clang_getFileName(ResultFile); KindSpelling = clang_getCursorKindSpelling(Result.kind); USR = clang_getCursorUSR(Result); *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName), SearchLine, SearchColumn, clang_getCString(KindSpelling)) << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName), ResultLine, ResultColumn, clang_getCString(USR), IsDef); clang_disposeString(SearchFileName); clang_disposeString(ResultFileName); clang_disposeString(KindSpelling); clang_disposeString(USR); CXCursor Definition = clang_getCursorDefinition(Result); if (!clang_equalCursors(Definition, clang_getNullCursor())) { CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); CXString DefinitionKindSpelling = clang_getCursorKindSpelling(Definition.kind); CXFile DefinitionFile; unsigned DefinitionLine, DefinitionColumn; clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine, &DefinitionColumn, nullptr); CXString DefinitionFileName = clang_getFileName(DefinitionFile); *Log << llvm::format(" -> %s(%s:%d:%d)", clang_getCString(DefinitionKindSpelling), clang_getCString(DefinitionFileName), DefinitionLine, DefinitionColumn); clang_disposeString(DefinitionFileName); clang_disposeString(DefinitionKindSpelling); } } return Result; } CXCursor clang_getNullCursor(void) { return MakeCXCursorInvalid(CXCursor_InvalidFile); } unsigned clang_equalCursors(CXCursor X, CXCursor Y) { // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we // can't set consistently. For example, when visiting a DeclStmt we will set // it but we don't set it on the result of clang_getCursorDefinition for // a reference of the same declaration. // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works // when visiting a DeclStmt currently, the AST should be enhanced to be able // to provide that kind of info. if (clang_isDeclaration(X.kind)) X.data[1] = nullptr; if (clang_isDeclaration(Y.kind)) Y.data[1] = nullptr; return X == Y; } unsigned clang_hashCursor(CXCursor C) { unsigned Index = 0; if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) Index = 1; return llvm::DenseMapInfo
>::getHashValue( std::make_pair(C.kind, C.data[Index])); } unsigned clang_isInvalid(enum CXCursorKind K) { return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; } unsigned clang_isDeclaration(enum CXCursorKind K) { return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); } unsigned clang_isReference(enum CXCursorKind K) { return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; } unsigned clang_isExpression(enum CXCursorKind K) { return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; } unsigned clang_isStatement(enum CXCursorKind K) { return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; } unsigned clang_isAttribute(enum CXCursorKind K) { return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; } unsigned clang_isTranslationUnit(enum CXCursorKind K) { return K == CXCursor_TranslationUnit; } unsigned clang_isPreprocessing(enum CXCursorKind K) { return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; } unsigned clang_isUnexposed(enum CXCursorKind K) { switch (K) { case CXCursor_UnexposedDecl: case CXCursor_UnexposedExpr: case CXCursor_UnexposedStmt: case CXCursor_UnexposedAttr: return true; default: return false; } } CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; } CXSourceLocation clang_getCursorLocation(CXCursor C) { if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: { std::pair
P = getCursorObjCSuperClassRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_ObjCProtocolRef: { std::pair
P = getCursorObjCProtocolRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_ObjCClassRef: { std::pair
P = getCursorObjCClassRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_TypeRef: { std::pair
P = getCursorTypeRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_TemplateRef: { std::pair
P = getCursorTemplateRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_NamespaceRef: { std::pair
P = getCursorNamespaceRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_MemberRef: { std::pair
P = getCursorMemberRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_VariableRef: { std::pair
P = getCursorVariableRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); if (!BaseSpec) return clang_getNullLocation(); if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) return cxloc::translateSourceLocation(getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc()); return cxloc::translateSourceLocation(getCursorContext(C), BaseSpec->getLocStart()); } case CXCursor_LabelRef: { std::pair
P = getCursorLabelRef(C); return cxloc::translateSourceLocation(getCursorContext(C), P.second); } case CXCursor_OverloadedDeclRef: return cxloc::translateSourceLocation(getCursorContext(C), getCursorOverloadedDeclRef(C).second); default: // FIXME: Need a way to enumerate all non-reference cases. llvm_unreachable("Missed a reference kind"); } } if (clang_isExpression(C.kind)) return cxloc::translateSourceLocation(getCursorContext(C), getLocationFromExpr(getCursorExpr(C))); if (clang_isStatement(C.kind)) return cxloc::translateSourceLocation(getCursorContext(C), getCursorStmt(C)->getLocStart()); if (C.kind == CXCursor_PreprocessingDirective) { SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_MacroExpansion) { SourceLocation L = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_MacroDefinition) { SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_InclusionDirective) { SourceLocation L = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (clang_isAttribute(C.kind)) { SourceLocation L = cxcursor::getCursorAttr(C)->getLocation(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (!clang_isDeclaration(C.kind)) return clang_getNullLocation(); const Decl *D = getCursorDecl(C); if (!D) return clang_getNullLocation(); SourceLocation Loc = D->getLocation(); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast
(D)) { if (!cxcursor::isFirstInDeclGroup(C)) Loc = VD->getLocation(); } // For ObjC methods, give the start location of the method name. if (const ObjCMethodDecl *MD = dyn_cast
(D)) Loc = MD->getSelectorStartLoc(); return cxloc::translateSourceLocation(getCursorContext(C), Loc); } } // end extern "C" CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { assert(TU); // Guard against an invalid SourceLocation, or we may assert in one // of the following calls. if (SLoc.isInvalid()) return clang_getNullCursor(); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); // Translate the given source location to make it point at the beginning of // the token under the cursor. SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), CXXUnit->getASTContext().getLangOpts()); CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); if (SLoc.isValid()) { GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, SourceLocation(SLoc)); CursorVis.visitFileRegion(); } return Result; } static SourceRange getRawCursorExtent(CXCursor C) { if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: return getCursorObjCSuperClassRef(C).second; case CXCursor_ObjCProtocolRef: return getCursorObjCProtocolRef(C).second; case CXCursor_ObjCClassRef: return getCursorObjCClassRef(C).second; case CXCursor_TypeRef: return getCursorTypeRef(C).second; case CXCursor_TemplateRef: return getCursorTemplateRef(C).second; case CXCursor_NamespaceRef: return getCursorNamespaceRef(C).second; case CXCursor_MemberRef: return getCursorMemberRef(C).second; case CXCursor_CXXBaseSpecifier: return getCursorCXXBaseSpecifier(C)->getSourceRange(); case CXCursor_LabelRef: return getCursorLabelRef(C).second; case CXCursor_OverloadedDeclRef: return getCursorOverloadedDeclRef(C).second; case CXCursor_VariableRef: return getCursorVariableRef(C).second; default: // FIXME: Need a way to enumerate all non-reference cases. llvm_unreachable("Missed a reference kind"); } } if (clang_isExpression(C.kind)) return getCursorExpr(C)->getSourceRange(); if (clang_isStatement(C.kind)) return getCursorStmt(C)->getSourceRange(); if (clang_isAttribute(C.kind)) return getCursorAttr(C)->getRange(); if (C.kind == CXCursor_PreprocessingDirective) return cxcursor::getCursorPreprocessingDirective(C); if (C.kind == CXCursor_MacroExpansion) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_MacroDefinition) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_InclusionDirective) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_TranslationUnit) { ASTUnit *TU = getCursorASTUnit(C); FileID MainID = TU->getSourceManager().getMainFileID(); SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); return SourceRange(Start, End); } if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return SourceRange(); SourceRange R = D->getSourceRange(); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast
(D)) { if (!cxcursor::isFirstInDeclGroup(C)) R.setBegin(VD->getLocation()); } return R; } return SourceRange(); } /// \brief Retrieves the "raw" cursor extent, which is then extended to include /// the decl-specifier-seq for declarations. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return SourceRange(); SourceRange R = D->getSourceRange(); // Adjust the start of the location for declarations preceded by // declaration specifiers. SourceLocation StartLoc; if (const DeclaratorDecl *DD = dyn_cast
(D)) { if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) StartLoc = TI->getTypeLoc().getLocStart(); } else if (const TypedefDecl *Typedef = dyn_cast
(D)) { if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) StartLoc = TI->getTypeLoc().getLocStart(); } if (StartLoc.isValid() && R.getBegin().isValid() && SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) R.setBegin(StartLoc); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast
(D)) { if (!cxcursor::isFirstInDeclGroup(C)) R.setBegin(VD->getLocation()); } return R; } return getRawCursorExtent(C); } extern "C" { CXSourceRange clang_getCursorExtent(CXCursor C) { SourceRange R = getRawCursorExtent(C); if (R.isInvalid()) return clang_getNullRange(); return cxloc::translateSourceRange(getCursorContext(C), R); } CXCursor clang_getCursorReferenced(CXCursor C) { if (clang_isInvalid(C.kind)) return clang_getNullCursor(); CXTranslationUnit tu = getCursorTU(C); if (clang_isDeclaration(C.kind)) { const Decl *D = getCursorDecl(C); if (!D) return clang_getNullCursor(); if (const UsingDecl *Using = dyn_cast
(D)) return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); if (const ObjCPropertyImplDecl *PropImpl = dyn_cast
(D)) if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) return MakeCXCursor(Property, tu); return C; } if (clang_isExpression(C.kind)) { const Expr *E = getCursorExpr(C); const Decl *D = getDeclFromExpr(E); if (D) { CXCursor declCursor = MakeCXCursor(D, tu); declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), declCursor); return declCursor; } if (const OverloadExpr *Ovl = dyn_cast_or_null
(E)) return MakeCursorOverloadedDeclRef(Ovl, tu); return clang_getNullCursor(); } if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const GotoStmt *Goto = dyn_cast_or_null
(S)) if (LabelDecl *label = Goto->getLabel()) if (LabelStmt *labelS = label->getStmt()) return MakeCXCursor(labelS, getCursorDecl(C), tu); return clang_getNullCursor(); } if (C.kind == CXCursor_MacroExpansion) { if (const MacroDefinitionRecord *Def = getCursorMacroExpansion(C).getDefinition()) return MakeMacroDefinitionCursor(Def, tu); } if (!clang_isReference(C.kind)) return clang_getNullCursor(); switch (C.kind) { case CXCursor_ObjCSuperClassRef: return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); case CXCursor_ObjCProtocolRef: { const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; if (const ObjCProtocolDecl *Def = Prot->getDefinition()) return MakeCXCursor(Def, tu); return MakeCXCursor(Prot, tu); } case CXCursor_ObjCClassRef: { const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; if (const ObjCInterfaceDecl *Def = Class->getDefinition()) return MakeCXCursor(Def, tu); return MakeCXCursor(Class, tu); } case CXCursor_TypeRef: return MakeCXCursor(getCursorTypeRef(C).first, tu ); case CXCursor_TemplateRef: return MakeCXCursor(getCursorTemplateRef(C).first, tu ); case CXCursor_NamespaceRef: return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); case CXCursor_MemberRef: return MakeCXCursor(getCursorMemberRef(C).first, tu ); case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu )); } case CXCursor_LabelRef: // FIXME: We end up faking the "parent" declaration here because we // don't want to make CXCursor larger. return MakeCXCursor(getCursorLabelRef(C).first, cxtu::getASTUnit(tu)->getASTContext() .getTranslationUnitDecl(), tu); case CXCursor_OverloadedDeclRef: return C; case CXCursor_VariableRef: return MakeCXCursor(getCursorVariableRef(C).first, tu); default: // We would prefer to enumerate all non-reference cursor kinds here. llvm_unreachable("Unhandled reference cursor kind"); } } CXCursor clang_getCursorDefinition(CXCursor C) { if (clang_isInvalid(C.kind)) return clang_getNullCursor(); CXTranslationUnit TU = getCursorTU(C); bool WasReference = false; if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { C = clang_getCursorReferenced(C); WasReference = true; } if (C.kind == CXCursor_MacroExpansion) return clang_getCursorReferenced(C); if (!clang_isDeclaration(C.kind)) return clang_getNullCursor(); const Decl *D = getCursorDecl(C); if (!D) return clang_getNullCursor(); switch (D->getKind()) { // Declaration kinds that don't really separate the notions of // declaration and definition. case Decl::Namespace: case Decl::Typedef: case Decl::TypeAlias: case Decl::TypeAliasTemplate: case Decl::TemplateTypeParm: case Decl::EnumConstant: case Decl::Field: case Decl::MSProperty: case Decl::IndirectField: case Decl::ObjCIvar: case Decl::ObjCAtDefsField: case Decl::ImplicitParam: case Decl::ParmVar: case Decl::NonTypeTemplateParm: case Decl::TemplateTemplateParm: case Decl::ObjCCategoryImpl: case Decl::ObjCImplementation: case Decl::AccessSpec: case Decl::LinkageSpec: case Decl::ObjCPropertyImpl: case Decl::FileScopeAsm: case Decl::StaticAssert: case Decl::Block: case Decl::Captured: case Decl::OMPCapturedExpr: case Decl::Label: // FIXME: Is this right?? case Decl::ClassScopeFunctionSpecialization: case Decl::Import: case Decl::OMPThreadPrivate: case Decl::OMPDeclareReduction: case Decl::ObjCTypeParam: case Decl::BuiltinTemplate: case Decl::PragmaComment: case Decl::PragmaDetectMismatch: return C; // Declaration kinds that don't make any sense here, but are // nonetheless harmless. case Decl::Empty: case Decl::TranslationUnit: case Decl::ExternCContext: break; // Declaration kinds for which the definition is not resolvable. case Decl::UnresolvedUsingTypename: case Decl::UnresolvedUsingValue: break; case Decl::UsingDirective: return MakeCXCursor(cast
(D)->getNominatedNamespace(), TU); case Decl::NamespaceAlias: return MakeCXCursor(cast
(D)->getNamespace(), TU); case Decl::Enum: case Decl::Record: case Decl::CXXRecord: case Decl::ClassTemplateSpecialization: case Decl::ClassTemplatePartialSpecialization: if (TagDecl *Def = cast
(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::Function: case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: case Decl::CXXConversion: { const FunctionDecl *Def = nullptr; if (cast
(D)->getBody(Def)) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::Var: case Decl::VarTemplateSpecialization: case Decl::VarTemplatePartialSpecialization: { // Ask the variable if it has a definition. if (const VarDecl *Def = cast
(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::FunctionTemplate: { const FunctionDecl *Def = nullptr; if (cast
(D)->getTemplatedDecl()->getBody(Def)) return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); return clang_getNullCursor(); } case Decl::ClassTemplate: { if (RecordDecl *Def = cast
(D)->getTemplatedDecl() ->getDefinition()) return MakeCXCursor(cast
(Def)->getDescribedClassTemplate(), TU); return clang_getNullCursor(); } case Decl::VarTemplate: { if (VarDecl *Def = cast
(D)->getTemplatedDecl()->getDefinition()) return MakeCXCursor(cast
(Def)->getDescribedVarTemplate(), TU); return clang_getNullCursor(); } case Decl::Using: return MakeCursorOverloadedDeclRef(cast
(D), D->getLocation(), TU); case Decl::UsingShadow: case Decl::ConstructorUsingShadow: return clang_getCursorDefinition( MakeCXCursor(cast
(D)->getTargetDecl(), TU)); case Decl::ObjCMethod: { const ObjCMethodDecl *Method = cast
(D); if (Method->isThisDeclarationADefinition()) return C; // Dig out the method definition in the associated // @implementation, if we have it. // FIXME: The ASTs should make finding the definition easier. if (const ObjCInterfaceDecl *Class = dyn_cast
(Method->getDeclContext())) if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), Method->isInstanceMethod())) if (Def->isThisDeclarationADefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::ObjCCategory: if (ObjCCategoryImplDecl *Impl = cast
(D)->getImplementation()) return MakeCXCursor(Impl, TU); return clang_getNullCursor(); case Decl::ObjCProtocol: if (const ObjCProtocolDecl *Def = cast
(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::ObjCInterface: { // There are two notions of a "definition" for an Objective-C // class: the interface and its implementation. When we resolved a // reference to an Objective-C class, produce the @interface as // the definition; when we were provided with the interface, // produce the @implementation as the definition. const ObjCInterfaceDecl *IFace = cast
(D); if (WasReference) { if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) return MakeCXCursor(Def, TU); } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) return MakeCXCursor(Impl, TU); return clang_getNullCursor(); } case Decl::ObjCProperty: // FIXME: We don't really know where to find the // ObjCPropertyImplDecls that implement this property. return clang_getNullCursor(); case Decl::ObjCCompatibleAlias: if (const ObjCInterfaceDecl *Class = cast
(D)->getClassInterface()) if (const ObjCInterfaceDecl *Def = Class->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::Friend: if (NamedDecl *Friend = cast