1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the main API hooks in the Clang-C Source Indexing
13 //===----------------------------------------------------------------------===//
15 #include "CIndexDiagnostic.h"
19 #include "CXSourceLocation.h"
21 #include "CXTranslationUnit.h"
23 #include "CursorVisitor.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Basic/DiagnosticCategories.h"
28 #include "clang/Basic/DiagnosticIDs.h"
29 #include "clang/Basic/Stack.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/ASTUnit.h"
33 #include "clang/Frontend/CompilerInstance.h"
34 #include "clang/Index/CodegenNameGenerator.h"
35 #include "clang/Index/CommentToXML.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Config/llvm-config.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/CrashRecoveryContext.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Mutex.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/Threading.h"
55 #include "llvm/Support/Timer.h"
56 #include "llvm/Support/raw_ostream.h"
58 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59 #define USE_DARWIN_THREADS
62 #ifdef USE_DARWIN_THREADS
66 using namespace clang;
67 using namespace clang::cxcursor;
68 using namespace clang::cxtu;
69 using namespace clang::cxindex;
71 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
76 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->TheASTUnit = AU.release();
79 D->StringPool = new cxstring::CXStringPool();
80 D->Diagnostics = nullptr;
81 D->OverridenCursorsPool = createOverridenCXCursorsPool();
82 D->CommentToXML = nullptr;
83 D->ParsingOptions = 0;
88 bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
100 cxtu::CXTUOwner::~CXTUOwner() {
102 clang_disposeTranslationUnit(TU);
105 /// Compare two source ranges to determine their relative position in
106 /// the translation unit.
107 static RangeComparisonResult RangeCompare(SourceManager &SM,
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
121 /// Determine if a source location falls within, before, or after a
122 /// a given source range.
123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
136 /// Translate a Clang source range into a CIndex source range.
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
148 bool IsTokenRange = R.isTokenRange();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
150 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
151 EndLoc = Expansion.getEnd();
152 IsTokenRange = Expansion.isTokenRange();
154 if (IsTokenRange && EndLoc.isValid()) {
155 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
157 EndLoc = EndLoc.getLocWithOffset(Length);
160 CXSourceRange Result = {
162 R.getBegin().getRawEncoding(),
163 EndLoc.getRawEncoding()
168 //===----------------------------------------------------------------------===//
170 //===----------------------------------------------------------------------===//
172 static SourceRange getRawCursorExtent(CXCursor C);
173 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
176 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
177 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
180 /// Visit the given cursor and, if requested by the visitor,
183 /// \param Cursor the cursor to visit.
185 /// \param CheckedRegionOfInterest if true, then the caller already checked
186 /// that this cursor is within the region of interest.
188 /// \returns true if the visitation should be aborted, false if it
190 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
191 if (clang_isInvalid(Cursor.kind))
194 if (clang_isDeclaration(Cursor.kind)) {
195 const Decl *D = getCursorDecl(Cursor);
197 assert(0 && "Invalid declaration cursor");
198 return true; // abort.
201 // Ignore implicit declarations, unless it's an objc method because
202 // currently we should report implicit methods for properties when indexing.
203 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
207 // If we have a range of interest, and this cursor doesn't intersect with it,
209 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
210 SourceRange Range = getRawCursorExtent(Cursor);
211 if (Range.isInvalid() || CompareRegionOfInterest(Range))
215 switch (Visitor(Cursor, Parent, ClientData)) {
216 case CXChildVisit_Break:
219 case CXChildVisit_Continue:
222 case CXChildVisit_Recurse: {
223 bool ret = VisitChildren(Cursor);
224 if (PostChildrenVisitor)
225 if (PostChildrenVisitor(Cursor, ClientData))
231 llvm_unreachable("Invalid CXChildVisitResult!");
234 static bool visitPreprocessedEntitiesInRange(SourceRange R,
235 PreprocessingRecord &PPRec,
236 CursorVisitor &Visitor) {
237 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
240 if (!Visitor.shouldVisitIncludedEntities()) {
241 // If the begin/end of the range lie in the same FileID, do the optimization
242 // where we skip preprocessed entities that do not come from the same FileID.
243 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
244 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
248 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
249 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
253 bool CursorVisitor::visitFileRegion() {
254 if (RegionOfInterest.isInvalid())
257 ASTUnit *Unit = cxtu::getASTUnit(TU);
258 SourceManager &SM = Unit->getSourceManager();
260 std::pair<FileID, unsigned>
261 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
262 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
264 if (End.first != Begin.first) {
265 // If the end does not reside in the same file, try to recover by
266 // picking the end of the file of begin location.
267 End.first = Begin.first;
268 End.second = SM.getFileIDSize(Begin.first);
271 assert(Begin.first == End.first);
272 if (Begin.second > End.second)
275 FileID File = Begin.first;
276 unsigned Offset = Begin.second;
277 unsigned Length = End.second - Begin.second;
279 if (!VisitDeclsOnly && !VisitPreprocessorLast)
280 if (visitPreprocessedEntitiesInRegion())
281 return true; // visitation break.
283 if (visitDeclsFromFileRegion(File, Offset, Length))
284 return true; // visitation break.
286 if (!VisitDeclsOnly && VisitPreprocessorLast)
287 return visitPreprocessedEntitiesInRegion();
292 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
296 for (DeclContext *DeclDC = D->getLexicalDeclContext();
297 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
304 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
305 unsigned Offset, unsigned Length) {
306 ASTUnit *Unit = cxtu::getASTUnit(TU);
307 SourceManager &SM = Unit->getSourceManager();
308 SourceRange Range = RegionOfInterest;
310 SmallVector<Decl *, 16> Decls;
311 Unit->findFileRegionDecls(File, Offset, Length, Decls);
313 // If we didn't find any file level decls for the file, try looking at the
314 // file that it was included from.
315 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
316 bool Invalid = false;
317 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
321 SourceLocation Outer;
322 if (SLEntry.isFile())
323 Outer = SLEntry.getFile().getIncludeLoc();
325 Outer = SLEntry.getExpansion().getExpansionLocStart();
326 if (Outer.isInvalid())
329 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
331 Unit->findFileRegionDecls(File, Offset, Length, Decls);
334 assert(!Decls.empty());
336 bool VisitedAtLeastOnce = false;
337 DeclContext *CurDC = nullptr;
338 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
339 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
341 if (D->getSourceRange().isInvalid())
344 if (isInLexicalContext(D, CurDC))
347 CurDC = dyn_cast<DeclContext>(D);
349 if (TagDecl *TD = dyn_cast<TagDecl>(D))
350 if (!TD->isFreeStanding())
353 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
354 if (CompRes == RangeBefore)
356 if (CompRes == RangeAfter)
359 assert(CompRes == RangeOverlap);
360 VisitedAtLeastOnce = true;
362 if (isa<ObjCContainerDecl>(D)) {
363 FileDI_current = &DIt;
366 FileDI_current = nullptr;
369 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
370 return true; // visitation break.
373 if (VisitedAtLeastOnce)
376 // No Decls overlapped with the range. Move up the lexical context until there
377 // is a context that contains the range or we reach the translation unit
379 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
380 : (*(DIt-1))->getLexicalDeclContext();
382 while (DC && !DC->isTranslationUnit()) {
383 Decl *D = cast<Decl>(DC);
384 SourceRange CurDeclRange = D->getSourceRange();
385 if (CurDeclRange.isInvalid())
388 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
389 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
390 return true; // visitation break.
393 DC = D->getLexicalDeclContext();
399 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
400 if (!AU->getPreprocessor().getPreprocessingRecord())
403 PreprocessingRecord &PPRec
404 = *AU->getPreprocessor().getPreprocessingRecord();
405 SourceManager &SM = AU->getSourceManager();
407 if (RegionOfInterest.isValid()) {
408 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
409 SourceLocation B = MappedRange.getBegin();
410 SourceLocation E = MappedRange.getEnd();
412 if (AU->isInPreambleFileID(B)) {
413 if (SM.isLoadedSourceLocation(E))
414 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
417 // Beginning of range lies in the preamble but it also extends beyond
418 // it into the main file. Split the range into 2 parts, one covering
419 // the preamble and another covering the main file. This allows subsequent
420 // calls to visitPreprocessedEntitiesInRange to accept a source range that
421 // lies in the same FileID, allowing it to skip preprocessed entities that
422 // do not come from the same FileID.
424 visitPreprocessedEntitiesInRange(
425 SourceRange(B, AU->getEndOfPreambleFileID()),
427 if (breaked) return true;
428 return visitPreprocessedEntitiesInRange(
429 SourceRange(AU->getStartOfMainFileID(), E),
433 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
437 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
440 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
443 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
446 template<typename InputIterator>
447 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
449 PreprocessingRecord &PPRec,
451 for (; First != Last; ++First) {
452 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
455 PreprocessedEntity *PPE = *First;
459 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
460 if (Visit(MakeMacroExpansionCursor(ME, TU)))
466 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
467 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
473 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
474 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
484 /// Visit the children of the given cursor.
486 /// \returns true if the visitation should be aborted, false if it
488 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
489 if (clang_isReference(Cursor.kind) &&
490 Cursor.kind != CXCursor_CXXBaseSpecifier) {
491 // By definition, references have no children.
495 // Set the Parent field to Cursor, then back to its old value once we're
497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
499 if (clang_isDeclaration(Cursor.kind)) {
500 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
504 return VisitAttributes(D) || Visit(D);
507 if (clang_isStatement(Cursor.kind)) {
508 if (const Stmt *S = getCursorStmt(Cursor))
514 if (clang_isExpression(Cursor.kind)) {
515 if (const Expr *E = getCursorExpr(Cursor))
521 if (clang_isTranslationUnit(Cursor.kind)) {
522 CXTranslationUnit TU = getCursorTU(Cursor);
523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
525 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
526 for (unsigned I = 0; I != 2; ++I) {
528 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
529 RegionOfInterest.isInvalid()) {
530 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
531 TLEnd = CXXUnit->top_level_end();
533 const Optional<bool> V = handleDeclForVisitation(*TL);
538 } else if (VisitDeclContext(
539 CXXUnit->getASTContext().getTranslationUnitDecl()))
544 // Walk the preprocessing record.
545 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
546 visitPreprocessedEntitiesInRegion();
552 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
553 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
554 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
555 return Visit(BaseTSInfo->getTypeLoc());
560 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
561 const IBOutletCollectionAttr *A =
562 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
563 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
564 return Visit(cxcursor::MakeCursorObjCClassRef(
565 ObjT->getInterface(),
566 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
569 // If pointing inside a macro definition, check if the token is an identifier
570 // that was ever defined as a macro. In such a case, create a "pseudo" macro
571 // expansion cursor for that token.
572 SourceLocation BeginLoc = RegionOfInterest.getBegin();
573 if (Cursor.kind == CXCursor_MacroDefinition &&
574 BeginLoc == RegionOfInterest.getEnd()) {
575 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
576 const MacroInfo *MI =
577 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
578 if (MacroDefinitionRecord *MacroDef =
579 checkForMacroInMacroDefinition(MI, Loc, TU))
580 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
583 // Nothing to visit at the moment.
587 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
588 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
589 if (Visit(TSInfo->getTypeLoc()))
592 if (Stmt *Body = B->getBody())
593 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
598 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
599 if (RegionOfInterest.isValid()) {
600 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
601 if (Range.isInvalid())
604 switch (CompareRegionOfInterest(Range)) {
606 // This declaration comes before the region of interest; skip it.
610 // This declaration comes after the region of interest; we're done.
614 // This declaration overlaps the region of interest; visit it.
621 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
622 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
624 // FIXME: Eventually remove. This part of a hack to support proper
625 // iteration over all Decls contained lexically within an ObjC container.
626 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
627 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
629 for ( ; I != E; ++I) {
631 if (D->getLexicalDeclContext() != DC)
633 const Optional<bool> V = handleDeclForVisitation(D);
641 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
642 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
644 // Ignore synthesized ivars here, otherwise if we have something like:
645 // @synthesize prop = _prop;
646 // and '_prop' is not declared, we will encounter a '_prop' ivar before
647 // encountering the 'prop' synthesize declaration and we will think that
648 // we passed the region-of-interest.
649 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
650 if (ivarD->getSynthesize())
654 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
655 // declarations is a mismatch with the compiler semantics.
656 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
657 auto *ID = cast<ObjCInterfaceDecl>(D);
658 if (!ID->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
661 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
662 auto *PD = cast<ObjCProtocolDecl>(D);
663 if (!PD->isThisDeclarationADefinition())
664 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
667 const Optional<bool> V = shouldVisitCursor(Cursor);
672 if (Visit(Cursor, true))
677 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
678 llvm_unreachable("Translation units are visited directly by Visit()");
681 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
682 if (VisitTemplateParameters(D->getTemplateParameters()))
685 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
688 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
695 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
696 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
697 return Visit(TSInfo->getTypeLoc());
702 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
703 return VisitDeclContext(D);
706 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
707 ClassTemplateSpecializationDecl *D) {
708 bool ShouldVisitBody = false;
709 switch (D->getSpecializationKind()) {
711 case TSK_ImplicitInstantiation:
715 case TSK_ExplicitInstantiationDeclaration:
716 case TSK_ExplicitInstantiationDefinition:
719 case TSK_ExplicitSpecialization:
720 ShouldVisitBody = true;
724 // Visit the template arguments used in the specialization.
725 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
726 TypeLoc TL = SpecType->getTypeLoc();
727 if (TemplateSpecializationTypeLoc TSTLoc =
728 TL.getAs<TemplateSpecializationTypeLoc>()) {
729 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
730 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
735 return ShouldVisitBody && VisitCXXRecordDecl(D);
738 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
739 ClassTemplatePartialSpecializationDecl *D) {
740 // FIXME: Visit the "outer" template parameter lists on the TagDecl
741 // before visiting these template parameters.
742 if (VisitTemplateParameters(D->getTemplateParameters()))
745 // Visit the partial specialization arguments.
746 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
747 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
748 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
749 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
752 return VisitCXXRecordDecl(D);
755 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
756 // Visit the default argument.
757 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
758 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
759 if (Visit(DefArg->getTypeLoc()))
765 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
766 if (Expr *Init = D->getInitExpr())
767 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
771 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
772 unsigned NumParamList = DD->getNumTemplateParameterLists();
773 for (unsigned i = 0; i < NumParamList; i++) {
774 TemplateParameterList* Params = DD->getTemplateParameterList(i);
775 if (VisitTemplateParameters(Params))
779 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
780 if (Visit(TSInfo->getTypeLoc()))
783 // Visit the nested-name-specifier, if present.
784 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
785 if (VisitNestedNameSpecifierLoc(QualifierLoc))
791 static bool HasTrailingReturnType(FunctionDecl *ND) {
792 const QualType Ty = ND->getType();
793 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
794 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
795 return FT->hasTrailingReturn();
801 /// Compare two base or member initializers based on their source order.
802 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
803 CXXCtorInitializer *const *Y) {
804 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
807 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
808 unsigned NumParamList = ND->getNumTemplateParameterLists();
809 for (unsigned i = 0; i < NumParamList; i++) {
810 TemplateParameterList* Params = ND->getTemplateParameterList(i);
811 if (VisitTemplateParameters(Params))
815 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
816 // Visit the function declaration's syntactic components in the order
817 // written. This requires a bit of work.
818 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
819 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
820 const bool HasTrailingRT = HasTrailingReturnType(ND);
822 // If we have a function declared directly (without the use of a typedef),
823 // visit just the return type. Otherwise, just visit the function's type
825 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
826 Visit(FTL.getReturnLoc())) ||
830 // Visit the nested-name-specifier, if present.
831 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
832 if (VisitNestedNameSpecifierLoc(QualifierLoc))
835 // Visit the declaration name.
836 if (!isa<CXXDestructorDecl>(ND))
837 if (VisitDeclarationNameInfo(ND->getNameInfo()))
840 // FIXME: Visit explicitly-specified template arguments!
842 // Visit the function parameters, if we have a function type.
843 if (FTL && VisitFunctionTypeLoc(FTL, true))
846 // Visit the function's trailing return type.
847 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
850 // FIXME: Attributes?
853 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
855 // Find the initializers that were written in the source.
856 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
857 for (auto *I : Constructor->inits()) {
861 WrittenInits.push_back(I);
864 // Sort the initializers in source order
865 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
866 &CompareCXXCtorInitializers);
868 // Visit the initializers in source order
869 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
870 CXXCtorInitializer *Init = WrittenInits[I];
871 if (Init->isAnyMemberInitializer()) {
872 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
873 Init->getMemberLocation(), TU)))
875 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
876 if (Visit(TInfo->getTypeLoc()))
880 // Visit the initializer value.
881 if (Expr *Initializer = Init->getInit())
882 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
887 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
894 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
895 if (VisitDeclaratorDecl(D))
898 if (Expr *BitWidth = D->getBitWidth())
899 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
901 if (Expr *Init = D->getInClassInitializer())
902 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
907 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
908 if (VisitDeclaratorDecl(D))
911 if (Expr *Init = D->getInit())
912 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
917 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
918 if (VisitDeclaratorDecl(D))
921 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
922 if (Expr *DefArg = D->getDefaultArgument())
923 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
928 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
929 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
930 // before visiting these template parameters.
931 if (VisitTemplateParameters(D->getTemplateParameters()))
934 auto* FD = D->getTemplatedDecl();
935 return VisitAttributes(FD) || VisitFunctionDecl(FD);
938 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
939 // FIXME: Visit the "outer" template parameter lists on the TagDecl
940 // before visiting these template parameters.
941 if (VisitTemplateParameters(D->getTemplateParameters()))
944 auto* CD = D->getTemplatedDecl();
945 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
948 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
949 if (VisitTemplateParameters(D->getTemplateParameters()))
952 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
953 VisitTemplateArgumentLoc(D->getDefaultArgument()))
959 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
960 // Visit the bound, if it's explicit.
961 if (D->hasExplicitBound()) {
962 if (auto TInfo = D->getTypeSourceInfo()) {
963 if (Visit(TInfo->getTypeLoc()))
971 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
972 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
973 if (Visit(TSInfo->getTypeLoc()))
976 for (const auto *P : ND->parameters()) {
977 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
981 return ND->isThisDeclarationADefinition() &&
982 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
985 template <typename DeclIt>
986 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
987 SourceManager &SM, SourceLocation EndLoc,
988 SmallVectorImpl<Decl *> &Decls) {
989 DeclIt next = *DI_current;
990 while (++next != DE_current) {
991 Decl *D_next = *next;
994 SourceLocation L = D_next->getBeginLoc();
997 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
999 Decls.push_back(D_next);
1006 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1007 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1008 // an @implementation can lexically contain Decls that are not properly
1009 // nested in the AST. When we identify such cases, we need to retrofit
1010 // this nesting here.
1011 if (!DI_current && !FileDI_current)
1012 return VisitDeclContext(D);
1014 // Scan the Decls that immediately come after the container
1015 // in the current DeclContext. If any fall within the
1016 // container's lexical region, stash them into a vector
1017 // for later processing.
1018 SmallVector<Decl *, 24> DeclsInContainer;
1019 SourceLocation EndLoc = D->getSourceRange().getEnd();
1020 SourceManager &SM = AU->getSourceManager();
1021 if (EndLoc.isValid()) {
1023 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1026 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1032 if (DeclsInContainer.empty())
1033 return VisitDeclContext(D);
1035 // Get all the Decls in the DeclContext, and sort them with the
1036 // additional ones we've collected. Then visit them.
1037 for (auto *SubDecl : D->decls()) {
1038 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1039 SubDecl->getBeginLoc().isInvalid())
1041 DeclsInContainer.push_back(SubDecl);
1044 // Now sort the Decls so that they appear in lexical order.
1045 llvm::sort(DeclsInContainer,
1046 [&SM](Decl *A, Decl *B) {
1047 SourceLocation L_A = A->getBeginLoc();
1048 SourceLocation L_B = B->getBeginLoc();
1049 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
1050 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1054 // Now visit the decls.
1055 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1056 E = DeclsInContainer.end(); I != E; ++I) {
1057 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1058 const Optional<bool> &V = shouldVisitCursor(Cursor);
1063 if (Visit(Cursor, true))
1069 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1070 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1074 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1077 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1078 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1079 E = ND->protocol_end(); I != E; ++I, ++PL)
1080 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1083 return VisitObjCContainerDecl(ND);
1086 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1087 if (!PID->isThisDeclarationADefinition())
1088 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1090 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1091 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1092 E = PID->protocol_end(); I != E; ++I, ++PL)
1093 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1096 return VisitObjCContainerDecl(PID);
1099 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1100 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1103 // FIXME: This implements a workaround with @property declarations also being
1104 // installed in the DeclContext for the @interface. Eventually this code
1105 // should be removed.
1106 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1107 if (!CDecl || !CDecl->IsClassExtension())
1110 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1114 IdentifierInfo *PropertyId = PD->getIdentifier();
1115 ObjCPropertyDecl *prevDecl =
1116 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1117 PD->getQueryKind());
1122 // Visit synthesized methods since they will be skipped when visiting
1124 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1125 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1126 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1129 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1130 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1131 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1137 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1141 for (auto *typeParam : *typeParamList) {
1142 // Visit the type parameter.
1143 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1150 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1151 if (!D->isThisDeclarationADefinition()) {
1152 // Forward declaration is treated like a reference.
1153 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1156 // Objective-C type parameters.
1157 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1160 // Issue callbacks for super class.
1161 if (D->getSuperClass() &&
1162 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1163 D->getSuperClassLoc(),
1167 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1168 if (Visit(SuperClassTInfo->getTypeLoc()))
1171 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1172 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1173 E = D->protocol_end(); I != E; ++I, ++PL)
1174 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1177 return VisitObjCContainerDecl(D);
1180 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1181 return VisitObjCContainerDecl(D);
1184 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1185 // 'ID' could be null when dealing with invalid code.
1186 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1187 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1190 return VisitObjCImplDecl(D);
1193 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1195 // Issue callbacks for super class.
1196 // FIXME: No source location information!
1197 if (D->getSuperClass() &&
1198 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1199 D->getSuperClassLoc(),
1204 return VisitObjCImplDecl(D);
1207 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1208 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1209 if (PD->isIvarNameSpecified())
1210 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1215 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1216 return VisitDeclContext(D);
1219 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1220 // Visit nested-name-specifier.
1221 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1225 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1226 D->getTargetNameLoc(), TU));
1229 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1230 // Visit nested-name-specifier.
1231 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1236 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1239 return VisitDeclarationNameInfo(D->getNameInfo());
1242 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1243 // Visit nested-name-specifier.
1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1248 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1249 D->getIdentLocation(), TU));
1252 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1253 // Visit nested-name-specifier.
1254 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1259 return VisitDeclarationNameInfo(D->getNameInfo());
1262 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1263 UnresolvedUsingTypenameDecl *D) {
1264 // Visit nested-name-specifier.
1265 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1266 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1272 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1273 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1275 if (StringLiteral *Message = D->getMessage())
1276 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1281 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1282 if (NamedDecl *FriendD = D->getFriendDecl()) {
1283 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1285 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1286 if (Visit(TI->getTypeLoc()))
1292 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1293 switch (Name.getName().getNameKind()) {
1294 case clang::DeclarationName::Identifier:
1295 case clang::DeclarationName::CXXLiteralOperatorName:
1296 case clang::DeclarationName::CXXDeductionGuideName:
1297 case clang::DeclarationName::CXXOperatorName:
1298 case clang::DeclarationName::CXXUsingDirective:
1301 case clang::DeclarationName::CXXConstructorName:
1302 case clang::DeclarationName::CXXDestructorName:
1303 case clang::DeclarationName::CXXConversionFunctionName:
1304 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1305 return Visit(TSInfo->getTypeLoc());
1308 case clang::DeclarationName::ObjCZeroArgSelector:
1309 case clang::DeclarationName::ObjCOneArgSelector:
1310 case clang::DeclarationName::ObjCMultiArgSelector:
1311 // FIXME: Per-identifier location info?
1315 llvm_unreachable("Invalid DeclarationName::Kind!");
1318 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1319 SourceRange Range) {
1320 // FIXME: This whole routine is a hack to work around the lack of proper
1321 // source information in nested-name-specifiers (PR5791). Since we do have
1322 // a beginning source location, we can visit the first component of the
1323 // nested-name-specifier, if it's a single-token component.
1327 // Get the first component in the nested-name-specifier.
1328 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1331 switch (NNS->getKind()) {
1332 case NestedNameSpecifier::Namespace:
1333 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1336 case NestedNameSpecifier::NamespaceAlias:
1337 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1338 Range.getBegin(), TU));
1340 case NestedNameSpecifier::TypeSpec: {
1341 // If the type has a form where we know that the beginning of the source
1342 // range matches up with a reference cursor. Visit the appropriate reference
1344 const Type *T = NNS->getAsType();
1345 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1346 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1347 if (const TagType *Tag = dyn_cast<TagType>(T))
1348 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1349 if (const TemplateSpecializationType *TST
1350 = dyn_cast<TemplateSpecializationType>(T))
1351 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1355 case NestedNameSpecifier::TypeSpecWithTemplate:
1356 case NestedNameSpecifier::Global:
1357 case NestedNameSpecifier::Identifier:
1358 case NestedNameSpecifier::Super:
1366 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1367 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1368 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1369 Qualifiers.push_back(Qualifier);
1371 while (!Qualifiers.empty()) {
1372 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1373 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1374 switch (NNS->getKind()) {
1375 case NestedNameSpecifier::Namespace:
1376 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1377 Q.getLocalBeginLoc(),
1383 case NestedNameSpecifier::NamespaceAlias:
1384 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1385 Q.getLocalBeginLoc(),
1391 case NestedNameSpecifier::TypeSpec:
1392 case NestedNameSpecifier::TypeSpecWithTemplate:
1393 if (Visit(Q.getTypeLoc()))
1398 case NestedNameSpecifier::Global:
1399 case NestedNameSpecifier::Identifier:
1400 case NestedNameSpecifier::Super:
1408 bool CursorVisitor::VisitTemplateParameters(
1409 const TemplateParameterList *Params) {
1413 for (TemplateParameterList::const_iterator P = Params->begin(),
1414 PEnd = Params->end();
1416 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1423 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1424 switch (Name.getKind()) {
1425 case TemplateName::Template:
1426 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1428 case TemplateName::OverloadedTemplate:
1429 // Visit the overloaded template set.
1430 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1435 case TemplateName::DependentTemplate:
1436 // FIXME: Visit nested-name-specifier.
1439 case TemplateName::QualifiedTemplate:
1440 // FIXME: Visit nested-name-specifier.
1441 return Visit(MakeCursorTemplateRef(
1442 Name.getAsQualifiedTemplateName()->getDecl(),
1445 case TemplateName::SubstTemplateTemplateParm:
1446 return Visit(MakeCursorTemplateRef(
1447 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 case TemplateName::SubstTemplateTemplateParmPack:
1451 return Visit(MakeCursorTemplateRef(
1452 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1456 llvm_unreachable("Invalid TemplateName::Kind!");
1459 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1460 switch (TAL.getArgument().getKind()) {
1461 case TemplateArgument::Null:
1462 case TemplateArgument::Integral:
1463 case TemplateArgument::Pack:
1466 case TemplateArgument::Type:
1467 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1468 return Visit(TSInfo->getTypeLoc());
1471 case TemplateArgument::Declaration:
1472 if (Expr *E = TAL.getSourceDeclExpression())
1473 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 case TemplateArgument::NullPtr:
1477 if (Expr *E = TAL.getSourceNullPtrExpression())
1478 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 case TemplateArgument::Expression:
1482 if (Expr *E = TAL.getSourceExpression())
1483 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 case TemplateArgument::Template:
1487 case TemplateArgument::TemplateExpansion:
1488 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1492 TAL.getTemplateNameLoc());
1495 llvm_unreachable("Invalid TemplateArgument::Kind!");
1498 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1499 return VisitDeclContext(D);
1502 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1503 return Visit(TL.getUnqualifiedLoc());
1506 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1507 ASTContext &Context = AU->getASTContext();
1509 // Some builtin types (such as Objective-C's "id", "sel", and
1510 // "Class") have associated declarations. Create cursors for those.
1512 switch (TL.getTypePtr()->getKind()) {
1514 case BuiltinType::Void:
1515 case BuiltinType::NullPtr:
1516 case BuiltinType::Dependent:
1517 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1518 case BuiltinType::Id:
1519 #include "clang/Basic/OpenCLImageTypes.def"
1520 #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1521 case BuiltinType::Id:
1522 #include "clang/Basic/OpenCLExtensionTypes.def"
1523 case BuiltinType::OCLSampler:
1524 case BuiltinType::OCLEvent:
1525 case BuiltinType::OCLClkEvent:
1526 case BuiltinType::OCLQueue:
1527 case BuiltinType::OCLReserveID:
1528 #define BUILTIN_TYPE(Id, SingletonId)
1529 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1531 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1532 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1533 #include "clang/AST/BuiltinTypes.def"
1536 case BuiltinType::ObjCId:
1537 VisitType = Context.getObjCIdType();
1540 case BuiltinType::ObjCClass:
1541 VisitType = Context.getObjCClassType();
1544 case BuiltinType::ObjCSel:
1545 VisitType = Context.getObjCSelType();
1549 if (!VisitType.isNull()) {
1550 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1551 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1558 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1559 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1562 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1563 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1566 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1567 if (TL.isDefinition())
1568 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1570 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1573 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1574 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1577 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1578 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1581 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1582 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1584 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1585 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1593 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1594 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1597 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1598 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1602 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1603 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1611 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1612 return Visit(TL.getPointeeLoc());
1615 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1616 return Visit(TL.getInnerLoc());
1619 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1620 return Visit(TL.getPointeeLoc());
1623 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1624 return Visit(TL.getPointeeLoc());
1627 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1628 return Visit(TL.getPointeeLoc());
1631 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1632 return Visit(TL.getPointeeLoc());
1635 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1636 return Visit(TL.getPointeeLoc());
1639 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1640 return Visit(TL.getModifiedLoc());
1643 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1644 bool SkipResultType) {
1645 if (!SkipResultType && Visit(TL.getReturnLoc()))
1648 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1649 if (Decl *D = TL.getParam(I))
1650 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1656 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1657 if (Visit(TL.getElementLoc()))
1660 if (Expr *Size = TL.getSizeExpr())
1661 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1666 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1667 return Visit(TL.getOriginalLoc());
1670 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1671 return Visit(TL.getOriginalLoc());
1674 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1675 DeducedTemplateSpecializationTypeLoc TL) {
1676 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1677 TL.getTemplateNameLoc()))
1683 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1684 TemplateSpecializationTypeLoc TL) {
1685 // Visit the template name.
1686 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1687 TL.getTemplateNameLoc()))
1690 // Visit the template arguments.
1691 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1692 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1698 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1699 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1702 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1703 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1704 return Visit(TSInfo->getTypeLoc());
1709 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1710 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1711 return Visit(TSInfo->getTypeLoc());
1716 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1717 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1720 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1721 DependentTemplateSpecializationTypeLoc TL) {
1722 // Visit the nested-name-specifier, if there is one.
1723 if (TL.getQualifierLoc() &&
1724 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1727 // Visit the template arguments.
1728 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1729 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1735 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1736 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1739 return Visit(TL.getNamedTypeLoc());
1742 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1743 return Visit(TL.getPatternLoc());
1746 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1747 if (Expr *E = TL.getUnderlyingExpr())
1748 return Visit(MakeCXCursor(E, StmtParent, TU));
1753 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1754 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1757 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1758 return Visit(TL.getValueLoc());
1761 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1762 return Visit(TL.getValueLoc());
1765 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1766 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1767 return Visit##PARENT##Loc(TL); \
1770 DEFAULT_TYPELOC_IMPL(Complex, Type)
1771 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1772 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1773 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1774 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1775 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
1776 DEFAULT_TYPELOC_IMPL(DependentVector, Type)
1777 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1778 DEFAULT_TYPELOC_IMPL(Vector, Type)
1779 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1780 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1781 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1782 DEFAULT_TYPELOC_IMPL(Record, TagType)
1783 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1784 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1785 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1786 DEFAULT_TYPELOC_IMPL(Auto, Type)
1788 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1789 // Visit the nested-name-specifier, if present.
1790 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1791 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1794 if (D->isCompleteDefinition()) {
1795 for (const auto &I : D->bases()) {
1796 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1801 return VisitTagDecl(D);
1804 bool CursorVisitor::VisitAttributes(Decl *D) {
1805 for (const auto *I : D->attrs())
1806 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1807 !I->isImplicit()) &&
1808 Visit(MakeCXCursor(I, D, TU)))
1814 //===----------------------------------------------------------------------===//
1815 // Data-recursive visitor methods.
1816 //===----------------------------------------------------------------------===//
1819 #define DEF_JOB(NAME, DATA, KIND)\
1820 class NAME : public VisitorJob {\
1822 NAME(const DATA *d, CXCursor parent) : \
1823 VisitorJob(parent, VisitorJob::KIND, d) {} \
1824 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1825 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1828 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1829 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1830 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1831 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1832 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1833 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1834 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1837 class ExplicitTemplateArgsVisit : public VisitorJob {
1839 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1840 const TemplateArgumentLoc *End, CXCursor parent)
1841 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1843 static bool classof(const VisitorJob *VJ) {
1844 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1846 const TemplateArgumentLoc *begin() const {
1847 return static_cast<const TemplateArgumentLoc *>(data[0]);
1849 const TemplateArgumentLoc *end() {
1850 return static_cast<const TemplateArgumentLoc *>(data[1]);
1853 class DeclVisit : public VisitorJob {
1855 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1856 VisitorJob(parent, VisitorJob::DeclVisitKind,
1857 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == DeclVisitKind;
1861 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1862 bool isFirst() const { return data[1] != nullptr; }
1864 class TypeLocVisit : public VisitorJob {
1866 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1867 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1868 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1870 static bool classof(const VisitorJob *VJ) {
1871 return VJ->getKind() == TypeLocVisitKind;
1874 TypeLoc get() const {
1875 QualType T = QualType::getFromOpaquePtr(data[0]);
1876 return TypeLoc(T, const_cast<void *>(data[1]));
1880 class LabelRefVisit : public VisitorJob {
1882 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1883 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1884 labelLoc.getPtrEncoding()) {}
1886 static bool classof(const VisitorJob *VJ) {
1887 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1889 const LabelDecl *get() const {
1890 return static_cast<const LabelDecl *>(data[0]);
1892 SourceLocation getLoc() const {
1893 return SourceLocation::getFromPtrEncoding(data[1]); }
1896 class NestedNameSpecifierLocVisit : public VisitorJob {
1898 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1899 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1900 Qualifier.getNestedNameSpecifier(),
1901 Qualifier.getOpaqueData()) { }
1903 static bool classof(const VisitorJob *VJ) {
1904 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1907 NestedNameSpecifierLoc get() const {
1908 return NestedNameSpecifierLoc(
1909 const_cast<NestedNameSpecifier *>(
1910 static_cast<const NestedNameSpecifier *>(data[0])),
1911 const_cast<void *>(data[1]));
1915 class DeclarationNameInfoVisit : public VisitorJob {
1917 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1918 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1919 static bool classof(const VisitorJob *VJ) {
1920 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1922 DeclarationNameInfo get() const {
1923 const Stmt *S = static_cast<const Stmt *>(data[0]);
1924 switch (S->getStmtClass()) {
1926 llvm_unreachable("Unhandled Stmt");
1927 case clang::Stmt::MSDependentExistsStmtClass:
1928 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1929 case Stmt::CXXDependentScopeMemberExprClass:
1930 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1931 case Stmt::DependentScopeDeclRefExprClass:
1932 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1933 case Stmt::OMPCriticalDirectiveClass:
1934 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1938 class MemberRefVisit : public VisitorJob {
1940 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1941 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1942 L.getPtrEncoding()) {}
1943 static bool classof(const VisitorJob *VJ) {
1944 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1946 const FieldDecl *get() const {
1947 return static_cast<const FieldDecl *>(data[0]);
1949 SourceLocation getLoc() const {
1950 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1953 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1954 friend class OMPClauseEnqueue;
1955 VisitorWorkList &WL;
1958 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1959 : WL(wl), Parent(parent) {}
1961 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1962 void VisitBlockExpr(const BlockExpr *B);
1963 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1964 void VisitCompoundStmt(const CompoundStmt *S);
1965 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1966 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1967 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1968 void VisitCXXNewExpr(const CXXNewExpr *E);
1969 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1970 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1971 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1972 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1973 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1974 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1975 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1976 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1977 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1978 void VisitDeclRefExpr(const DeclRefExpr *D);
1979 void VisitDeclStmt(const DeclStmt *S);
1980 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1981 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1982 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1983 void VisitForStmt(const ForStmt *FS);
1984 void VisitGotoStmt(const GotoStmt *GS);
1985 void VisitIfStmt(const IfStmt *If);
1986 void VisitInitListExpr(const InitListExpr *IE);
1987 void VisitMemberExpr(const MemberExpr *M);
1988 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1989 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1990 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1991 void VisitOverloadExpr(const OverloadExpr *E);
1992 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1993 void VisitStmt(const Stmt *S);
1994 void VisitSwitchStmt(const SwitchStmt *S);
1995 void VisitWhileStmt(const WhileStmt *W);
1996 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1997 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1998 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1999 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2000 void VisitVAArgExpr(const VAArgExpr *E);
2001 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2002 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2003 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2004 void VisitLambdaExpr(const LambdaExpr *E);
2005 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2006 void VisitOMPLoopDirective(const OMPLoopDirective *D);
2007 void VisitOMPParallelDirective(const OMPParallelDirective *D);
2008 void VisitOMPSimdDirective(const OMPSimdDirective *D);
2009 void VisitOMPForDirective(const OMPForDirective *D);
2010 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2011 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2012 void VisitOMPSectionDirective(const OMPSectionDirective *D);
2013 void VisitOMPSingleDirective(const OMPSingleDirective *D);
2014 void VisitOMPMasterDirective(const OMPMasterDirective *D);
2015 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2016 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2017 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2018 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2019 void VisitOMPTaskDirective(const OMPTaskDirective *D);
2020 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2021 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2022 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2023 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2025 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2026 void VisitOMPCancelDirective(const OMPCancelDirective *D);
2027 void VisitOMPFlushDirective(const OMPFlushDirective *D);
2028 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2029 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2030 void VisitOMPTargetDirective(const OMPTargetDirective *D);
2031 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2032 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2033 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2034 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2036 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2037 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2038 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2039 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2040 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2041 void VisitOMPDistributeParallelForDirective(
2042 const OMPDistributeParallelForDirective *D);
2043 void VisitOMPDistributeParallelForSimdDirective(
2044 const OMPDistributeParallelForSimdDirective *D);
2045 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2046 void VisitOMPTargetParallelForSimdDirective(
2047 const OMPTargetParallelForSimdDirective *D);
2048 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2049 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2050 void VisitOMPTeamsDistributeSimdDirective(
2051 const OMPTeamsDistributeSimdDirective *D);
2052 void VisitOMPTeamsDistributeParallelForSimdDirective(
2053 const OMPTeamsDistributeParallelForSimdDirective *D);
2054 void VisitOMPTeamsDistributeParallelForDirective(
2055 const OMPTeamsDistributeParallelForDirective *D);
2056 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2057 void VisitOMPTargetTeamsDistributeDirective(
2058 const OMPTargetTeamsDistributeDirective *D);
2059 void VisitOMPTargetTeamsDistributeParallelForDirective(
2060 const OMPTargetTeamsDistributeParallelForDirective *D);
2061 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2062 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2063 void VisitOMPTargetTeamsDistributeSimdDirective(
2064 const OMPTargetTeamsDistributeSimdDirective *D);
2067 void AddDeclarationNameInfo(const Stmt *S);
2068 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2069 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2070 unsigned NumTemplateArgs);
2071 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2072 void AddStmt(const Stmt *S);
2073 void AddDecl(const Decl *D, bool isFirst = true);
2074 void AddTypeLoc(TypeSourceInfo *TI);
2075 void EnqueueChildren(const Stmt *S);
2076 void EnqueueChildren(const OMPClause *S);
2078 } // end anonyous namespace
2080 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2081 // 'S' should always be non-null, since it comes from the
2082 // statement we are visiting.
2083 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2087 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2089 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2092 void EnqueueVisitor::AddStmt(const Stmt *S) {
2094 WL.push_back(StmtVisit(S, Parent));
2096 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2098 WL.push_back(DeclVisit(D, Parent, isFirst));
2100 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2101 unsigned NumTemplateArgs) {
2102 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2104 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2106 WL.push_back(MemberRefVisit(D, L, Parent));
2108 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2110 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2112 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2113 unsigned size = WL.size();
2114 for (const Stmt *SubStmt : S->children()) {
2117 if (size == WL.size())
2119 // Now reverse the entries we just added. This will match the DFS
2120 // ordering performed by the worklist.
2121 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2125 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2126 EnqueueVisitor *Visitor;
2127 /// Process clauses with list of variables.
2128 template <typename T>
2129 void VisitOMPClauseList(T *Node);
2131 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2132 #define OPENMP_CLAUSE(Name, Class) \
2133 void Visit##Class(const Class *C);
2134 #include "clang/Basic/OpenMPKinds.def"
2135 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2136 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2139 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2140 const OMPClauseWithPreInit *C) {
2141 Visitor->AddStmt(C->getPreInitStmt());
2144 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2145 const OMPClauseWithPostUpdate *C) {
2146 VisitOMPClauseWithPreInit(C);
2147 Visitor->AddStmt(C->getPostUpdateExpr());
2150 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2151 VisitOMPClauseWithPreInit(C);
2152 Visitor->AddStmt(C->getCondition());
2155 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2156 Visitor->AddStmt(C->getCondition());
2159 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2160 VisitOMPClauseWithPreInit(C);
2161 Visitor->AddStmt(C->getNumThreads());
2164 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2165 Visitor->AddStmt(C->getSafelen());
2168 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2169 Visitor->AddStmt(C->getSimdlen());
2172 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2173 Visitor->AddStmt(C->getNumForLoops());
2176 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2178 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2180 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2181 VisitOMPClauseWithPreInit(C);
2182 Visitor->AddStmt(C->getChunkSize());
2185 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2186 Visitor->AddStmt(C->getNumForLoops());
2189 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2191 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2193 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2195 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2197 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2199 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2201 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2203 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2205 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2207 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2209 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2211 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2212 const OMPUnifiedAddressClause *) {}
2214 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2215 const OMPUnifiedSharedMemoryClause *) {}
2217 void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2218 const OMPReverseOffloadClause *) {}
2220 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2221 const OMPDynamicAllocatorsClause *) {}
2223 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2224 const OMPAtomicDefaultMemOrderClause *) {}
2226 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2227 Visitor->AddStmt(C->getDevice());
2230 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2231 VisitOMPClauseWithPreInit(C);
2232 Visitor->AddStmt(C->getNumTeams());
2235 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2236 VisitOMPClauseWithPreInit(C);
2237 Visitor->AddStmt(C->getThreadLimit());
2240 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2241 Visitor->AddStmt(C->getPriority());
2244 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2245 Visitor->AddStmt(C->getGrainsize());
2248 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2249 Visitor->AddStmt(C->getNumTasks());
2252 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2253 Visitor->AddStmt(C->getHint());
2256 template<typename T>
2257 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2258 for (const auto *I : Node->varlists()) {
2259 Visitor->AddStmt(I);
2263 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2264 VisitOMPClauseList(C);
2265 for (const auto *E : C->private_copies()) {
2266 Visitor->AddStmt(E);
2269 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2270 const OMPFirstprivateClause *C) {
2271 VisitOMPClauseList(C);
2272 VisitOMPClauseWithPreInit(C);
2273 for (const auto *E : C->private_copies()) {
2274 Visitor->AddStmt(E);
2276 for (const auto *E : C->inits()) {
2277 Visitor->AddStmt(E);
2280 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2281 const OMPLastprivateClause *C) {
2282 VisitOMPClauseList(C);
2283 VisitOMPClauseWithPostUpdate(C);
2284 for (auto *E : C->private_copies()) {
2285 Visitor->AddStmt(E);
2287 for (auto *E : C->source_exprs()) {
2288 Visitor->AddStmt(E);
2290 for (auto *E : C->destination_exprs()) {
2291 Visitor->AddStmt(E);
2293 for (auto *E : C->assignment_ops()) {
2294 Visitor->AddStmt(E);
2297 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2298 VisitOMPClauseList(C);
2300 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2301 VisitOMPClauseList(C);
2302 VisitOMPClauseWithPostUpdate(C);
2303 for (auto *E : C->privates()) {
2304 Visitor->AddStmt(E);
2306 for (auto *E : C->lhs_exprs()) {
2307 Visitor->AddStmt(E);
2309 for (auto *E : C->rhs_exprs()) {
2310 Visitor->AddStmt(E);
2312 for (auto *E : C->reduction_ops()) {
2313 Visitor->AddStmt(E);
2316 void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2317 const OMPTaskReductionClause *C) {
2318 VisitOMPClauseList(C);
2319 VisitOMPClauseWithPostUpdate(C);
2320 for (auto *E : C->privates()) {
2321 Visitor->AddStmt(E);
2323 for (auto *E : C->lhs_exprs()) {
2324 Visitor->AddStmt(E);
2326 for (auto *E : C->rhs_exprs()) {
2327 Visitor->AddStmt(E);
2329 for (auto *E : C->reduction_ops()) {
2330 Visitor->AddStmt(E);
2333 void OMPClauseEnqueue::VisitOMPInReductionClause(
2334 const OMPInReductionClause *C) {
2335 VisitOMPClauseList(C);
2336 VisitOMPClauseWithPostUpdate(C);
2337 for (auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2340 for (auto *E : C->lhs_exprs()) {
2341 Visitor->AddStmt(E);
2343 for (auto *E : C->rhs_exprs()) {
2344 Visitor->AddStmt(E);
2346 for (auto *E : C->reduction_ops()) {
2347 Visitor->AddStmt(E);
2349 for (auto *E : C->taskgroup_descriptors())
2350 Visitor->AddStmt(E);
2352 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2353 VisitOMPClauseList(C);
2354 VisitOMPClauseWithPostUpdate(C);
2355 for (const auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2358 for (const auto *E : C->inits()) {
2359 Visitor->AddStmt(E);
2361 for (const auto *E : C->updates()) {
2362 Visitor->AddStmt(E);
2364 for (const auto *E : C->finals()) {
2365 Visitor->AddStmt(E);
2367 Visitor->AddStmt(C->getStep());
2368 Visitor->AddStmt(C->getCalcStep());
2370 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2371 VisitOMPClauseList(C);
2372 Visitor->AddStmt(C->getAlignment());
2374 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2375 VisitOMPClauseList(C);
2376 for (auto *E : C->source_exprs()) {
2377 Visitor->AddStmt(E);
2379 for (auto *E : C->destination_exprs()) {
2380 Visitor->AddStmt(E);
2382 for (auto *E : C->assignment_ops()) {
2383 Visitor->AddStmt(E);
2387 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2388 VisitOMPClauseList(C);
2389 for (auto *E : C->source_exprs()) {
2390 Visitor->AddStmt(E);
2392 for (auto *E : C->destination_exprs()) {
2393 Visitor->AddStmt(E);
2395 for (auto *E : C->assignment_ops()) {
2396 Visitor->AddStmt(E);
2399 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2400 VisitOMPClauseList(C);
2402 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2403 VisitOMPClauseList(C);
2405 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2406 VisitOMPClauseList(C);
2408 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2409 const OMPDistScheduleClause *C) {
2410 VisitOMPClauseWithPreInit(C);
2411 Visitor->AddStmt(C->getChunkSize());
2413 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2414 const OMPDefaultmapClause * /*C*/) {}
2415 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2416 VisitOMPClauseList(C);
2418 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2419 VisitOMPClauseList(C);
2421 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2422 VisitOMPClauseList(C);
2424 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2425 VisitOMPClauseList(C);
2429 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2430 unsigned size = WL.size();
2431 OMPClauseEnqueue Visitor(this);
2433 if (size == WL.size())
2435 // Now reverse the entries we just added. This will match the DFS
2436 // ordering performed by the worklist.
2437 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2440 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2441 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2443 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2444 AddDecl(B->getBlockDecl());
2446 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2448 AddTypeLoc(E->getTypeSourceInfo());
2450 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2451 for (auto &I : llvm::reverse(S->body()))
2454 void EnqueueVisitor::
2455 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2456 AddStmt(S->getSubStmt());
2457 AddDeclarationNameInfo(S);
2458 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2459 AddNestedNameSpecifierLoc(QualifierLoc);
2462 void EnqueueVisitor::
2463 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2464 if (E->hasExplicitTemplateArgs())
2465 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2466 AddDeclarationNameInfo(E);
2467 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2468 AddNestedNameSpecifierLoc(QualifierLoc);
2469 if (!E->isImplicitAccess())
2470 AddStmt(E->getBase());
2472 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2473 // Enqueue the initializer , if any.
2474 AddStmt(E->getInitializer());
2475 // Enqueue the array size, if any.
2476 AddStmt(E->getArraySize());
2477 // Enqueue the allocated type.
2478 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2479 // Enqueue the placement arguments.
2480 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2481 AddStmt(E->getPlacementArg(I-1));
2483 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2484 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2485 AddStmt(CE->getArg(I-1));
2486 AddStmt(CE->getCallee());
2487 AddStmt(CE->getArg(0));
2489 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2490 const CXXPseudoDestructorExpr *E) {
2491 // Visit the name of the type being destroyed.
2492 AddTypeLoc(E->getDestroyedTypeInfo());
2493 // Visit the scope type that looks disturbingly like the nested-name-specifier
2495 AddTypeLoc(E->getScopeTypeInfo());
2496 // Visit the nested-name-specifier.
2497 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2498 AddNestedNameSpecifierLoc(QualifierLoc);
2499 // Visit base expression.
2500 AddStmt(E->getBase());
2502 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2503 const CXXScalarValueInitExpr *E) {
2504 AddTypeLoc(E->getTypeSourceInfo());
2506 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2507 const CXXTemporaryObjectExpr *E) {
2509 AddTypeLoc(E->getTypeSourceInfo());
2511 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2513 if (E->isTypeOperand())
2514 AddTypeLoc(E->getTypeOperandSourceInfo());
2517 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2518 const CXXUnresolvedConstructExpr *E) {
2520 AddTypeLoc(E->getTypeSourceInfo());
2522 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2524 if (E->isTypeOperand())
2525 AddTypeLoc(E->getTypeOperandSourceInfo());
2528 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2530 AddDecl(S->getExceptionDecl());
2533 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2534 AddStmt(S->getBody());
2535 AddStmt(S->getRangeInit());
2536 AddDecl(S->getLoopVariable());
2539 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2540 if (DR->hasExplicitTemplateArgs())
2541 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2542 WL.push_back(DeclRefExprParts(DR, Parent));
2544 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2545 const DependentScopeDeclRefExpr *E) {
2546 if (E->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2548 AddDeclarationNameInfo(E);
2549 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2551 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2552 unsigned size = WL.size();
2553 bool isFirst = true;
2554 for (const auto *D : S->decls()) {
2555 AddDecl(D, isFirst);
2558 if (size == WL.size())
2560 // Now reverse the entries we just added. This will match the DFS
2561 // ordering performed by the worklist.
2562 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2565 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2566 AddStmt(E->getInit());
2567 for (const DesignatedInitExpr::Designator &D :
2568 llvm::reverse(E->designators())) {
2569 if (D.isFieldDesignator()) {
2570 if (FieldDecl *Field = D.getField())
2571 AddMemberRef(Field, D.getFieldLoc());
2574 if (D.isArrayDesignator()) {
2575 AddStmt(E->getArrayIndex(D));
2578 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2579 AddStmt(E->getArrayRangeEnd(D));
2580 AddStmt(E->getArrayRangeStart(D));
2583 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2585 AddTypeLoc(E->getTypeInfoAsWritten());
2587 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2588 AddStmt(FS->getBody());
2589 AddStmt(FS->getInc());
2590 AddStmt(FS->getCond());
2591 AddDecl(FS->getConditionVariable());
2592 AddStmt(FS->getInit());
2594 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2595 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2597 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2598 AddStmt(If->getElse());
2599 AddStmt(If->getThen());
2600 AddStmt(If->getCond());
2601 AddDecl(If->getConditionVariable());
2603 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2604 // We care about the syntactic form of the initializer list, only.
2605 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2607 EnqueueChildren(IE);
2609 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2610 WL.push_back(MemberExprParts(M, Parent));
2612 // If the base of the member access expression is an implicit 'this', don't
2614 // FIXME: If we ever want to show these implicit accesses, this will be
2615 // unfortunate. However, clang_getCursor() relies on this behavior.
2616 if (M->isImplicitAccess())
2619 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2620 // real field that we are interested in.
2621 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2622 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2623 if (FD->isAnonymousStructOrUnion()) {
2624 AddStmt(SubME->getBase());
2630 AddStmt(M->getBase());
2632 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2633 AddTypeLoc(E->getEncodedTypeSourceInfo());
2635 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2637 AddTypeLoc(M->getClassReceiverTypeInfo());
2639 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2640 // Visit the components of the offsetof expression.
2641 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2642 const OffsetOfNode &Node = E->getComponent(I-1);
2643 switch (Node.getKind()) {
2644 case OffsetOfNode::Array:
2645 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2647 case OffsetOfNode::Field:
2648 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2650 case OffsetOfNode::Identifier:
2651 case OffsetOfNode::Base:
2655 // Visit the type into which we're computing the offset.
2656 AddTypeLoc(E->getTypeSourceInfo());
2658 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2659 if (E->hasExplicitTemplateArgs())
2660 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2661 WL.push_back(OverloadExprParts(E, Parent));
2663 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2664 const UnaryExprOrTypeTraitExpr *E) {
2666 if (E->isArgumentType())
2667 AddTypeLoc(E->getArgumentTypeInfo());
2669 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2672 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2673 AddStmt(S->getBody());
2674 AddStmt(S->getCond());
2675 AddDecl(S->getConditionVariable());
2678 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2679 AddStmt(W->getBody());
2680 AddStmt(W->getCond());
2681 AddDecl(W->getConditionVariable());
2684 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2685 for (unsigned I = E->getNumArgs(); I > 0; --I)
2686 AddTypeLoc(E->getArg(I-1));
2689 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2690 AddTypeLoc(E->getQueriedTypeSourceInfo());
2693 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2697 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2698 VisitOverloadExpr(U);
2699 if (!U->isImplicitAccess())
2700 AddStmt(U->getBase());
2702 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2703 AddStmt(E->getSubExpr());
2704 AddTypeLoc(E->getWrittenTypeInfo());
2706 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2707 WL.push_back(SizeOfPackExprParts(E, Parent));
2709 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2710 // If the opaque value has a source expression, just transparently
2711 // visit that. This is useful for (e.g.) pseudo-object expressions.
2712 if (Expr *SourceExpr = E->getSourceExpr())
2713 return Visit(SourceExpr);
2715 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2716 AddStmt(E->getBody());
2717 WL.push_back(LambdaExprParts(E, Parent));
2719 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2720 // Treat the expression like its syntactic form.
2721 Visit(E->getSyntacticForm());
2724 void EnqueueVisitor::VisitOMPExecutableDirective(
2725 const OMPExecutableDirective *D) {
2727 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2728 E = D->clauses().end();
2730 EnqueueChildren(*I);
2733 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2734 VisitOMPExecutableDirective(D);
2737 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2738 VisitOMPExecutableDirective(D);
2741 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2742 VisitOMPLoopDirective(D);
2745 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2746 VisitOMPLoopDirective(D);
2749 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2750 VisitOMPLoopDirective(D);
2753 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2754 VisitOMPExecutableDirective(D);
2757 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2758 VisitOMPExecutableDirective(D);
2761 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2762 VisitOMPExecutableDirective(D);
2765 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2766 VisitOMPExecutableDirective(D);
2769 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771 AddDeclarationNameInfo(D);
2775 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2776 VisitOMPLoopDirective(D);
2779 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2780 const OMPParallelForSimdDirective *D) {
2781 VisitOMPLoopDirective(D);
2784 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2785 const OMPParallelSectionsDirective *D) {
2786 VisitOMPExecutableDirective(D);
2789 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2790 VisitOMPExecutableDirective(D);
2794 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2795 VisitOMPExecutableDirective(D);
2798 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2799 VisitOMPExecutableDirective(D);
2802 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2803 VisitOMPExecutableDirective(D);
2806 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2807 const OMPTaskgroupDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809 if (const Expr *E = D->getReductionRef())
2813 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2814 VisitOMPExecutableDirective(D);
2817 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2818 VisitOMPExecutableDirective(D);
2821 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2822 VisitOMPExecutableDirective(D);
2825 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2826 VisitOMPExecutableDirective(D);
2829 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2830 OMPTargetDataDirective *D) {
2831 VisitOMPExecutableDirective(D);
2834 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2835 const OMPTargetEnterDataDirective *D) {
2836 VisitOMPExecutableDirective(D);
2839 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2840 const OMPTargetExitDataDirective *D) {
2841 VisitOMPExecutableDirective(D);
2844 void EnqueueVisitor::VisitOMPTargetParallelDirective(
2845 const OMPTargetParallelDirective *D) {
2846 VisitOMPExecutableDirective(D);
2849 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2850 const OMPTargetParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2854 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2855 VisitOMPExecutableDirective(D);
2858 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2859 const OMPCancellationPointDirective *D) {
2860 VisitOMPExecutableDirective(D);
2863 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2864 VisitOMPExecutableDirective(D);
2867 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2868 VisitOMPLoopDirective(D);
2871 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2872 const OMPTaskLoopSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2876 void EnqueueVisitor::VisitOMPDistributeDirective(
2877 const OMPDistributeDirective *D) {
2878 VisitOMPLoopDirective(D);
2881 void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2882 const OMPDistributeParallelForDirective *D) {
2883 VisitOMPLoopDirective(D);
2886 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2887 const OMPDistributeParallelForSimdDirective *D) {
2888 VisitOMPLoopDirective(D);
2891 void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2892 const OMPDistributeSimdDirective *D) {
2893 VisitOMPLoopDirective(D);
2896 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2897 const OMPTargetParallelForSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2901 void EnqueueVisitor::VisitOMPTargetSimdDirective(
2902 const OMPTargetSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2906 void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2907 const OMPTeamsDistributeDirective *D) {
2908 VisitOMPLoopDirective(D);
2911 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2912 const OMPTeamsDistributeSimdDirective *D) {
2913 VisitOMPLoopDirective(D);
2916 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2917 const OMPTeamsDistributeParallelForSimdDirective *D) {
2918 VisitOMPLoopDirective(D);
2921 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2922 const OMPTeamsDistributeParallelForDirective *D) {
2923 VisitOMPLoopDirective(D);
2926 void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2927 const OMPTargetTeamsDirective *D) {
2928 VisitOMPExecutableDirective(D);
2931 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2932 const OMPTargetTeamsDistributeDirective *D) {
2933 VisitOMPLoopDirective(D);
2936 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2937 const OMPTargetTeamsDistributeParallelForDirective *D) {
2938 VisitOMPLoopDirective(D);
2941 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2942 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2946 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2947 const OMPTargetTeamsDistributeSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2951 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2952 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2955 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2956 if (RegionOfInterest.isValid()) {
2957 SourceRange Range = getRawCursorExtent(C);
2958 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2964 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2965 while (!WL.empty()) {
2966 // Dequeue the worklist item.
2967 VisitorJob LI = WL.pop_back_val();
2969 // Set the Parent field, then back to its old value once we're done.
2970 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2972 switch (LI.getKind()) {
2973 case VisitorJob::DeclVisitKind: {
2974 const Decl *D = cast<DeclVisit>(&LI)->get();
2978 // For now, perform default visitation for Decls.
2979 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2980 cast<DeclVisit>(&LI)->isFirst())))
2985 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2986 for (const TemplateArgumentLoc &Arg :
2987 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2988 if (VisitTemplateArgumentLoc(Arg))
2993 case VisitorJob::TypeLocVisitKind: {
2994 // Perform default visitation for TypeLocs.
2995 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2999 case VisitorJob::LabelRefVisitKind: {
3000 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3001 if (LabelStmt *stmt = LS->getStmt()) {
3002 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3010 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3011 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3012 if (VisitNestedNameSpecifierLoc(V->get()))
3017 case VisitorJob::DeclarationNameInfoVisitKind: {
3018 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3023 case VisitorJob::MemberRefVisitKind: {
3024 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3025 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3029 case VisitorJob::StmtVisitKind: {
3030 const Stmt *S = cast<StmtVisit>(&LI)->get();
3034 // Update the current cursor.
3035 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3036 if (!IsInRegionOfInterest(Cursor))
3038 switch (Visitor(Cursor, Parent, ClientData)) {
3039 case CXChildVisit_Break: return true;
3040 case CXChildVisit_Continue: break;
3041 case CXChildVisit_Recurse:
3042 if (PostChildrenVisitor)
3043 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3044 EnqueueWorkList(WL, S);
3049 case VisitorJob::MemberExprPartsKind: {
3050 // Handle the other pieces in the MemberExpr besides the base.
3051 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3053 // Visit the nested-name-specifier
3054 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3055 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3058 // Visit the declaration name.
3059 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3062 // Visit the explicitly-specified template arguments, if any.
3063 if (M->hasExplicitTemplateArgs()) {
3064 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3065 *ArgEnd = Arg + M->getNumTemplateArgs();
3066 Arg != ArgEnd; ++Arg) {
3067 if (VisitTemplateArgumentLoc(*Arg))
3073 case VisitorJob::DeclRefExprPartsKind: {
3074 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3075 // Visit nested-name-specifier, if present.
3076 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3077 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3079 // Visit declaration name.
3080 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3084 case VisitorJob::OverloadExprPartsKind: {
3085 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3086 // Visit the nested-name-specifier.
3087 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3090 // Visit the declaration name.
3091 if (VisitDeclarationNameInfo(O->getNameInfo()))
3093 // Visit the overloaded declaration reference.
3094 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3098 case VisitorJob::SizeOfPackExprPartsKind: {
3099 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3100 NamedDecl *Pack = E->getPack();
3101 if (isa<TemplateTypeParmDecl>(Pack)) {
3102 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3103 E->getPackLoc(), TU)))
3109 if (isa<TemplateTemplateParmDecl>(Pack)) {
3110 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3111 E->getPackLoc(), TU)))
3117 // Non-type template parameter packs and function parameter packs are
3118 // treated like DeclRefExpr cursors.
3122 case VisitorJob::LambdaExprPartsKind: {
3124 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3125 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3126 CEnd = E->explicit_capture_end();
3128 // FIXME: Lambda init-captures.
3129 if (!C->capturesVariable())
3132 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3138 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3139 // Visit parameters and return type, if present.
3140 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3141 if (E->hasExplicitParameters()) {
3142 // Visit parameters.
3143 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3144 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3147 if (E->hasExplicitResultType()) {
3148 // Visit result type.
3149 if (Visit(Proto.getReturnLoc()))
3156 case VisitorJob::PostChildrenVisitKind:
3157 if (PostChildrenVisitor(Parent, ClientData))
3165 bool CursorVisitor::Visit(const Stmt *S) {
3166 VisitorWorkList *WL = nullptr;
3167 if (!WorkListFreeList.empty()) {
3168 WL = WorkListFreeList.back();
3170 WorkListFreeList.pop_back();
3173 WL = new VisitorWorkList();
3174 WorkListCache.push_back(WL);
3176 EnqueueWorkList(*WL, S);
3177 bool result = RunVisitorWorkList(*WL);
3178 WorkListFreeList.push_back(WL);
3183 typedef SmallVector<SourceRange, 4> RefNamePieces;
3184 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3185 const DeclarationNameInfo &NI, SourceRange QLoc,
3186 const SourceRange *TemplateArgsLoc = nullptr) {
3187 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3188 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3189 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3191 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3193 RefNamePieces Pieces;
3195 if (WantQualifier && QLoc.isValid())
3196 Pieces.push_back(QLoc);
3198 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3199 Pieces.push_back(NI.getLoc());
3201 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3202 Pieces.push_back(*TemplateArgsLoc);
3204 if (Kind == DeclarationName::CXXOperatorName) {
3205 Pieces.push_back(SourceLocation::getFromRawEncoding(
3206 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3211 if (WantSinglePiece) {
3212 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3214 Pieces.push_back(R);
3221 //===----------------------------------------------------------------------===//
3223 //===----------------------------------------------------------------------===//
3225 static void fatal_error_handler(void *user_data, const std::string& reason,
3226 bool gen_crash_diag) {
3227 // Write the result out to stderr avoiding errs() because raw_ostreams can
3228 // call report_fatal_error.
3229 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3234 struct RegisterFatalErrorHandler {
3235 RegisterFatalErrorHandler() {
3236 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3241 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3243 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3244 int displayDiagnostics) {
3245 // We use crash recovery to make some of our APIs more reliable, implicitly
3247 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3248 llvm::CrashRecoveryContext::Enable();
3250 // Look through the managed static to trigger construction of the managed
3251 // static which registers our fatal error handler. This ensures it is only
3253 (void)*RegisterFatalErrorHandlerOnce;
3255 // Initialize targets for clang module support.
3256 llvm::InitializeAllTargets();
3257 llvm::InitializeAllTargetMCs();
3258 llvm::InitializeAllAsmPrinters();
3259 llvm::InitializeAllAsmParsers();
3261 CIndexer *CIdxr = new CIndexer();
3263 if (excludeDeclarationsFromPCH)
3264 CIdxr->setOnlyLocalDecls();
3265 if (displayDiagnostics)
3266 CIdxr->setDisplayDiagnostics();
3268 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3269 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3270 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3271 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3272 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3273 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3278 void clang_disposeIndex(CXIndex CIdx) {
3280 delete static_cast<CIndexer *>(CIdx);
3283 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3285 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3288 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3290 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3294 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3297 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3300 void clang_toggleCrashRecovery(unsigned isEnabled) {
3302 llvm::CrashRecoveryContext::Enable();
3304 llvm::CrashRecoveryContext::Disable();
3307 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3308 const char *ast_filename) {
3309 CXTranslationUnit TU;
3310 enum CXErrorCode Result =
3311 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3313 assert((TU && Result == CXError_Success) ||
3314 (!TU && Result != CXError_Success));
3318 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3319 const char *ast_filename,
3320 CXTranslationUnit *out_TU) {
3324 if (!CIdx || !ast_filename || !out_TU)
3325 return CXError_InvalidArguments;
3328 *Log << ast_filename;
3331 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3332 FileSystemOptions FileSystemOpts;
3334 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3335 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3336 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3337 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3338 ASTUnit::LoadEverything, Diags,
3339 FileSystemOpts, /*UseDebugInfo=*/false,
3340 CXXIdx->getOnlyLocalDecls(), None,
3341 /*CaptureDiagnostics=*/true,
3342 /*AllowPCHWithCompilerErrors=*/true,
3343 /*UserFilesAreVolatile=*/true);
3344 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3345 return *out_TU ? CXError_Success : CXError_Failure;
3348 unsigned clang_defaultEditingTranslationUnitOptions() {
3349 return CXTranslationUnit_PrecompiledPreamble |
3350 CXTranslationUnit_CacheCompletionResults;
3354 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3355 const char *source_filename,
3356 int num_command_line_args,
3357 const char * const *command_line_args,
3358 unsigned num_unsaved_files,
3359 struct CXUnsavedFile *unsaved_files) {
3360 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3361 return clang_parseTranslationUnit(CIdx, source_filename,
3362 command_line_args, num_command_line_args,
3363 unsaved_files, num_unsaved_files,
3368 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3369 const char *const *command_line_args,
3370 int num_command_line_args,
3371 ArrayRef<CXUnsavedFile> unsaved_files,
3372 unsigned options, CXTranslationUnit *out_TU) {
3373 // Set up the initial return values.
3378 if (!CIdx || !out_TU)
3379 return CXError_InvalidArguments;
3381 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3383 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3384 setThreadBackgroundPriority();
3386 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3387 bool CreatePreambleOnFirstParse =
3388 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3389 // FIXME: Add a flag for modules.
3390 TranslationUnitKind TUKind
3391 = (options & (CXTranslationUnit_Incomplete |
3392 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
3393 bool CacheCodeCompletionResults
3394 = options & CXTranslationUnit_CacheCompletionResults;
3395 bool IncludeBriefCommentsInCodeCompletion
3396 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3397 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3398 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3399 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3400 if (options & CXTranslationUnit_SkipFunctionBodies) {
3401 SkipFunctionBodies =
3402 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3403 ? SkipFunctionBodiesScope::Preamble
3404 : SkipFunctionBodiesScope::PreambleAndMainFile;
3407 // Configure the diagnostics.
3408 IntrusiveRefCntPtr<DiagnosticsEngine>
3409 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3411 if (options & CXTranslationUnit_KeepGoing)
3412 Diags->setSuppressAfterFatalError(false);
3414 // Recover resources if we crash before exiting this function.
3415 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3416 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3417 DiagCleanup(Diags.get());
3419 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3420 new std::vector<ASTUnit::RemappedFile>());
3422 // Recover resources if we crash before exiting this function.
3423 llvm::CrashRecoveryContextCleanupRegistrar<
3424 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3426 for (auto &UF : unsaved_files) {
3427 std::unique_ptr<llvm::MemoryBuffer> MB =
3428 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3429 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3432 std::unique_ptr<std::vector<const char *>> Args(
3433 new std::vector<const char *>());
3435 // Recover resources if we crash before exiting this method.
3436 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3437 ArgsCleanup(Args.get());
3439 // Since the Clang C library is primarily used by batch tools dealing with
3440 // (often very broken) source code, where spell-checking can have a
3441 // significant negative impact on performance (particularly when
3442 // precompiled headers are involved), we disable it by default.
3443 // Only do this if we haven't found a spell-checking-related argument.
3444 bool FoundSpellCheckingArgument = false;
3445 for (int I = 0; I != num_command_line_args; ++I) {
3446 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3447 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3448 FoundSpellCheckingArgument = true;
3452 Args->insert(Args->end(), command_line_args,
3453 command_line_args + num_command_line_args);
3455 if (!FoundSpellCheckingArgument)
3456 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3458 // The 'source_filename' argument is optional. If the caller does not
3459 // specify it then it is assumed that the source file is specified
3460 // in the actual argument list.
3461 // Put the source file after command_line_args otherwise if '-x' flag is
3462 // present it will be unused.
3463 if (source_filename)
3464 Args->push_back(source_filename);
3466 // Do we need the detailed preprocessing record?
3467 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3468 Args->push_back("-Xclang");
3469 Args->push_back("-detailed-preprocessing-record");
3472 // Suppress any editor placeholder diagnostics.
3473 Args->push_back("-fallow-editor-placeholders");
3475 unsigned NumErrors = Diags->getClient()->getNumErrors();
3476 std::unique_ptr<ASTUnit> ErrUnit;
3477 // Unless the user specified that they want the preamble on the first parse
3478 // set it up to be created on the first reparse. This makes the first parse
3479 // faster, trading for a slower (first) reparse.
3480 unsigned PrecompilePreambleAfterNParses =
3481 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3483 LibclangInvocationReporter InvocationReporter(
3484 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3485 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3487 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3488 Args->data(), Args->data() + Args->size(),
3489 CXXIdx->getPCHContainerOperations(), Diags,
3490 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3491 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3492 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3493 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3494 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3495 /*UserFilesAreVolatile=*/true, ForSerialization,
3496 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3499 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3500 if (!Unit && !ErrUnit)
3501 return CXError_ASTReadError;
3503 if (NumErrors != Diags->getClient()->getNumErrors()) {
3504 // Make sure to check that 'Unit' is non-NULL.
3505 if (CXXIdx->getDisplayDiagnostics())
3506 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3509 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3510 return CXError_ASTReadError;
3512 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3513 if (CXTranslationUnitImpl *TU = *out_TU) {
3514 TU->ParsingOptions = options;
3515 TU->Arguments.reserve(Args->size());
3516 for (const char *Arg : *Args)
3517 TU->Arguments.push_back(Arg);
3518 return CXError_Success;
3520 return CXError_Failure;
3524 clang_parseTranslationUnit(CXIndex CIdx,
3525 const char *source_filename,
3526 const char *const *command_line_args,
3527 int num_command_line_args,
3528 struct CXUnsavedFile *unsaved_files,
3529 unsigned num_unsaved_files,
3531 CXTranslationUnit TU;
3532 enum CXErrorCode Result = clang_parseTranslationUnit2(
3533 CIdx, source_filename, command_line_args, num_command_line_args,
3534 unsaved_files, num_unsaved_files, options, &TU);
3536 assert((TU && Result == CXError_Success) ||
3537 (!TU && Result != CXError_Success));
3541 enum CXErrorCode clang_parseTranslationUnit2(
3542 CXIndex CIdx, const char *source_filename,
3543 const char *const *command_line_args, int num_command_line_args,
3544 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3545 unsigned options, CXTranslationUnit *out_TU) {
3546 SmallVector<const char *, 4> Args;
3547 Args.push_back("clang");
3548 Args.append(command_line_args, command_line_args + num_command_line_args);
3549 return clang_parseTranslationUnit2FullArgv(
3550 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3551 num_unsaved_files, options, out_TU);
3554 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3555 CXIndex CIdx, const char *source_filename,
3556 const char *const *command_line_args, int num_command_line_args,
3557 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3558 unsigned options, CXTranslationUnit *out_TU) {
3560 *Log << source_filename << ": ";
3561 for (int i = 0; i != num_command_line_args; ++i)
3562 *Log << command_line_args[i] << " ";
3565 if (num_unsaved_files && !unsaved_files)
3566 return CXError_InvalidArguments;
3568 CXErrorCode result = CXError_Failure;
3569 auto ParseTranslationUnitImpl = [=, &result] {
3570 result = clang_parseTranslationUnit_Impl(
3571 CIdx, source_filename, command_line_args, num_command_line_args,
3572 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3575 llvm::CrashRecoveryContext CRC;
3577 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3578 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3579 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3580 fprintf(stderr, " 'command_line_args' : [");
3581 for (int i = 0; i != num_command_line_args; ++i) {
3583 fprintf(stderr, ", ");
3584 fprintf(stderr, "'%s'", command_line_args[i]);
3586 fprintf(stderr, "],\n");
3587 fprintf(stderr, " 'unsaved_files' : [");
3588 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3590 fprintf(stderr, ", ");
3591 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3592 unsaved_files[i].Length);
3594 fprintf(stderr, "],\n");
3595 fprintf(stderr, " 'options' : %d,\n", options);
3596 fprintf(stderr, "}\n");
3598 return CXError_Crashed;
3599 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3600 if (CXTranslationUnit *TU = out_TU)
3601 PrintLibclangResourceUsage(*TU);
3607 CXString clang_Type_getObjCEncoding(CXType CT) {
3608 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3609 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3610 std::string encoding;
3611 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3614 return cxstring::createDup(encoding);
3617 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3618 if (C.kind == CXCursor_MacroDefinition) {
3619 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3620 return MDR->getName();
3621 } else if (C.kind == CXCursor_MacroExpansion) {
3622 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3623 return ME.getName();
3628 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3629 const IdentifierInfo *II = getMacroIdentifier(C);
3633 ASTUnit *ASTU = getCursorASTUnit(C);
3634 Preprocessor &PP = ASTU->getPreprocessor();
3635 if (const MacroInfo *MI = PP.getMacroInfo(II))
3636 return MI->isFunctionLike();
3640 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3641 const IdentifierInfo *II = getMacroIdentifier(C);
3645 ASTUnit *ASTU = getCursorASTUnit(C);
3646 Preprocessor &PP = ASTU->getPreprocessor();
3647 if (const MacroInfo *MI = PP.getMacroInfo(II))
3648 return MI->isBuiltinMacro();
3652 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3653 const Decl *D = getCursorDecl(C);
3654 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3658 return FD->isInlined();
3661 static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3662 if (callExpr->getNumArgs() != 1) {
3666 StringLiteral *S = nullptr;
3667 auto *arg = callExpr->getArg(0);
3668 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3669 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3670 auto *subExpr = I->getSubExprAsWritten();
3672 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3676 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3677 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3678 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3685 struct ExprEvalResult {
3686 CXEvalResultKind EvalType;
3688 unsigned long long unsignedVal;
3695 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3696 EvalType != CXEval_Int) {
3697 delete[] EvalData.stringVal;
3702 void clang_EvalResult_dispose(CXEvalResult E) {
3703 delete static_cast<ExprEvalResult *>(E);
3706 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3708 return CXEval_UnExposed;
3710 return ((ExprEvalResult *)E)->EvalType;
3713 int clang_EvalResult_getAsInt(CXEvalResult E) {
3714 return clang_EvalResult_getAsLongLong(E);
3717 long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3721 ExprEvalResult *Result = (ExprEvalResult*)E;
3722 if (Result->IsUnsignedInt)
3723 return Result->EvalData.unsignedVal;
3724 return Result->EvalData.intVal;
3727 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3728 return ((ExprEvalResult *)E)->IsUnsignedInt;
3731 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3736 ExprEvalResult *Result = (ExprEvalResult*)E;
3737 if (Result->IsUnsignedInt)
3738 return Result->EvalData.unsignedVal;
3739 return Result->EvalData.intVal;
3742 double clang_EvalResult_getAsDouble(CXEvalResult E) {
3746 return ((ExprEvalResult *)E)->EvalData.floatVal;
3749 const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3753 return ((ExprEvalResult *)E)->EvalData.stringVal;
3756 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3757 Expr::EvalResult ER;
3758 ASTContext &ctx = getCursorContext(C);
3762 expr = expr->IgnoreParens();
3763 if (!expr->EvaluateAsRValue(ER, ctx))
3768 auto result = llvm::make_unique<ExprEvalResult>();
3769 result->EvalType = CXEval_UnExposed;
3770 result->IsUnsignedInt = false;
3772 if (ER.Val.isInt()) {
3773 result->EvalType = CXEval_Int;
3775 auto& val = ER.Val.getInt();
3776 if (val.isUnsigned()) {
3777 result->IsUnsignedInt = true;
3778 result->EvalData.unsignedVal = val.getZExtValue();
3780 result->EvalData.intVal = val.getExtValue();
3783 return result.release();
3786 if (ER.Val.isFloat()) {
3787 llvm::SmallVector<char, 100> Buffer;
3788 ER.Val.getFloat().toString(Buffer);
3789 std::string floatStr(Buffer.data(), Buffer.size());
3790 result->EvalType = CXEval_Float;
3792 llvm::APFloat apFloat = ER.Val.getFloat();
3793 apFloat.convert(llvm::APFloat::IEEEdouble(),
3794 llvm::APFloat::rmNearestTiesToEven, &ignored);
3795 result->EvalData.floatVal = apFloat.convertToDouble();
3796 return result.release();
3799 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3800 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3801 auto *subExpr = I->getSubExprAsWritten();
3802 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3803 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3804 const StringLiteral *StrE = nullptr;
3805 const ObjCStringLiteral *ObjCExpr;
3806 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3809 StrE = ObjCExpr->getString();
3810 result->EvalType = CXEval_ObjCStrLiteral;
3812 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3813 result->EvalType = CXEval_StrLiteral;
3816 std::string strRef(StrE->getString().str());
3817 result->EvalData.stringVal = new char[strRef.size() + 1];
3818 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3820 result->EvalData.stringVal[strRef.size()] = '\0';
3821 return result.release();
3823 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3824 expr->getStmtClass() == Stmt::StringLiteralClass) {
3825 const StringLiteral *StrE = nullptr;
3826 const ObjCStringLiteral *ObjCExpr;
3827 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3830 StrE = ObjCExpr->getString();
3831 result->EvalType = CXEval_ObjCStrLiteral;
3833 StrE = cast<StringLiteral>(expr);
3834 result->EvalType = CXEval_StrLiteral;
3837 std::string strRef(StrE->getString().str());
3838 result->EvalData.stringVal = new char[strRef.size() + 1];
3839 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3840 result->EvalData.stringVal[strRef.size()] = '\0';
3841 return result.release();
3844 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3845 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3847 rettype = CC->getType();
3848 if (rettype.getAsString() == "CFStringRef" &&
3849 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3851 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3852 StringLiteral *S = getCFSTR_value(callExpr);
3854 std::string strLiteral(S->getString().str());
3855 result->EvalType = CXEval_CFStr;
3857 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3858 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3860 result->EvalData.stringVal[strLiteral.size()] = '\0';
3861 return result.release();
3865 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3866 callExpr = static_cast<CallExpr *>(expr);
3867 rettype = callExpr->getCallReturnType(ctx);
3869 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3872 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3873 if (callExpr->getNumArgs() == 1 &&
3874 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3876 } else if (rettype.getAsString() == "CFStringRef") {
3878 StringLiteral *S = getCFSTR_value(callExpr);
3880 std::string strLiteral(S->getString().str());
3881 result->EvalType = CXEval_CFStr;
3882 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3883 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3885 result->EvalData.stringVal[strLiteral.size()] = '\0';
3886 return result.release();
3889 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3890 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3891 ValueDecl *V = D->getDecl();
3892 if (V->getKind() == Decl::Function) {
3893 std::string strName = V->getNameAsString();
3894 result->EvalType = CXEval_Other;
3895 result->EvalData.stringVal = new char[strName.size() + 1];
3896 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3897 result->EvalData.stringVal[strName.size()] = '\0';
3898 return result.release();
3905 static const Expr *evaluateDeclExpr(const Decl *D) {
3908 if (auto *Var = dyn_cast<VarDecl>(D))
3909 return Var->getInit();
3910 else if (auto *Field = dyn_cast<FieldDecl>(D))
3911 return Field->getInClassInitializer();
3915 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3916 assert(CS && "invalid compound statement");
3917 for (auto *bodyIterator : CS->body()) {
3918 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3924 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3926 clang_getCursorKind(C) == CXCursor_CompoundStmt
3927 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3928 : evaluateDeclExpr(getCursorDecl(C)))
3929 return const_cast<CXEvalResult>(
3930 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3934 unsigned clang_Cursor_hasAttrs(CXCursor C) {
3935 const Decl *D = getCursorDecl(C);
3940 if (D->hasAttrs()) {
3946 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3947 return CXSaveTranslationUnit_None;
3950 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3951 const char *FileName,
3953 CIndexer *CXXIdx = TU->CIdx;
3954 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3955 setThreadBackgroundPriority();
3957 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3958 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3961 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3964 *Log << TU << ' ' << FileName;
3967 if (isNotUsableTU(TU)) {
3969 return CXSaveError_InvalidTU;
3972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3973 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3974 if (!CXXUnit->hasSema())
3975 return CXSaveError_InvalidTU;
3978 auto SaveTranslationUnitImpl = [=, &result]() {
3979 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3982 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
3983 SaveTranslationUnitImpl();
3985 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3986 PrintLibclangResourceUsage(TU);
3991 // We have an AST that has invalid nodes due to compiler errors.
3992 // Use a crash recovery thread for protection.
3994 llvm::CrashRecoveryContext CRC;
3996 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3997 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3998 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3999 fprintf(stderr, " 'options' : %d,\n", options);
4000 fprintf(stderr, "}\n");
4002 return CXSaveError_Unknown;
4004 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4005 PrintLibclangResourceUsage(TU);
4011 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4013 // If the translation unit has been marked as unsafe to free, just discard
4015 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4016 if (Unit && Unit->isUnsafeToFree())
4019 delete cxtu::getASTUnit(CTUnit);
4020 delete CTUnit->StringPool;
4021 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4022 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4023 delete CTUnit->CommentToXML;
4028 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4030 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4032 if (Unit && Unit->isUnsafeToFree())
4035 Unit->ResetForParse();
4042 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4043 return CXReparse_None;
4047 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4048 ArrayRef<CXUnsavedFile> unsaved_files,
4051 if (isNotUsableTU(TU)) {
4053 return CXError_InvalidArguments;
4056 // Reset the associated diagnostics.
4057 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
4058 TU->Diagnostics = nullptr;
4060 CIndexer *CXXIdx = TU->CIdx;
4061 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4062 setThreadBackgroundPriority();
4064 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4067 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4068 new std::vector<ASTUnit::RemappedFile>());
4070 // Recover resources if we crash before exiting this function.
4071 llvm::CrashRecoveryContextCleanupRegistrar<
4072 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
4074 for (auto &UF : unsaved_files) {
4075 std::unique_ptr<llvm::MemoryBuffer> MB =
4076 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4077 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4080 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4081 *RemappedFiles.get()))
4082 return CXError_Success;
4083 if (isASTReadError(CXXUnit))
4084 return CXError_ASTReadError;
4085 return CXError_Failure;
4088 int clang_reparseTranslationUnit(CXTranslationUnit TU,
4089 unsigned num_unsaved_files,
4090 struct CXUnsavedFile *unsaved_files,
4096 if (num_unsaved_files && !unsaved_files)
4097 return CXError_InvalidArguments;
4100 auto ReparseTranslationUnitImpl = [=, &result]() {
4101 result = clang_reparseTranslationUnit_Impl(
4102 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4105 llvm::CrashRecoveryContext CRC;
4107 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4108 fprintf(stderr, "libclang: crash detected during reparsing\n");
4109 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4110 return CXError_Crashed;
4111 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4112 PrintLibclangResourceUsage(TU);
4118 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4119 if (isNotUsableTU(CTUnit)) {
4121 return cxstring::createEmpty();
4124 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4125 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4128 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4129 if (isNotUsableTU(TU)) {
4131 return clang_getNullCursor();
4134 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4135 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4138 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4139 if (isNotUsableTU(CTUnit)) {
4144 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4145 impl->TranslationUnit = CTUnit;
4149 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4151 return cxstring::createEmpty();
4153 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4154 assert(!isNotUsableTU(CTUnit) &&
4155 "Unexpected unusable translation unit in TargetInfo");
4157 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4158 std::string Triple =
4159 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4160 return cxstring::createDup(Triple);
4163 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4167 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4168 assert(!isNotUsableTU(CTUnit) &&
4169 "Unexpected unusable translation unit in TargetInfo");
4171 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4172 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4175 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4182 //===----------------------------------------------------------------------===//
4183 // CXFile Operations.
4184 //===----------------------------------------------------------------------===//
4186 CXString clang_getFileName(CXFile SFile) {
4188 return cxstring::createNull();
4190 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4191 return cxstring::createRef(FEnt->getName());
4194 time_t clang_getFileTime(CXFile SFile) {
4198 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4199 return FEnt->getModificationTime();
4202 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4203 if (isNotUsableTU(TU)) {
4208 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4210 FileManager &FMgr = CXXUnit->getFileManager();
4211 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4214 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4216 if (isNotUsableTU(TU)) {
4221 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4222 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4223 bool Invalid = true;
4224 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4231 *size = buf->getBufferSize();
4232 return buf->getBufferStart();
4235 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4237 if (isNotUsableTU(TU)) {
4245 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4246 FileEntry *FEnt = static_cast<FileEntry *>(file);
4247 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4248 .isFileMultipleIncludeGuarded(FEnt);
4251 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4252 if (!file || !outID)
4255 FileEntry *FEnt = static_cast<FileEntry *>(file);
4256 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4257 outID->data[0] = ID.getDevice();
4258 outID->data[1] = ID.getFile();
4259 outID->data[2] = FEnt->getModificationTime();
4263 int clang_File_isEqual(CXFile file1, CXFile file2) {
4267 if (!file1 || !file2)
4270 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4271 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4272 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4275 CXString clang_File_tryGetRealPathName(CXFile SFile) {
4277 return cxstring::createNull();
4279 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4280 return cxstring::createRef(FEnt->tryGetRealPathName());
4283 //===----------------------------------------------------------------------===//
4284 // CXCursor Operations.
4285 //===----------------------------------------------------------------------===//
4287 static const Decl *getDeclFromExpr(const Stmt *E) {
4288 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4289 return getDeclFromExpr(CE->getSubExpr());
4291 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4292 return RefExpr->getDecl();
4293 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4294 return ME->getMemberDecl();
4295 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4296 return RE->getDecl();
4297 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4298 if (PRE->isExplicitProperty())
4299 return PRE->getExplicitProperty();
4300 // It could be messaging both getter and setter as in:
4302 // in which case prefer to associate the setter since it is less obvious
4303 // from inspecting the source that the setter is going to get called.
4304 if (PRE->isMessagingSetter())
4305 return PRE->getImplicitPropertySetter();
4306 return PRE->getImplicitPropertyGetter();
4308 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4309 return getDeclFromExpr(POE->getSyntacticForm());
4310 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4311 if (Expr *Src = OVE->getSourceExpr())
4312 return getDeclFromExpr(Src);
4314 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4315 return getDeclFromExpr(CE->getCallee());
4316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4317 if (!CE->isElidable())
4318 return CE->getConstructor();
4319 if (const CXXInheritedCtorInitExpr *CE =
4320 dyn_cast<CXXInheritedCtorInitExpr>(E))
4321 return CE->getConstructor();
4322 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4323 return OME->getMethodDecl();
4325 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4326 return PE->getProtocol();
4327 if (const SubstNonTypeTemplateParmPackExpr *NTTP
4328 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4329 return NTTP->getParameterPack();
4330 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4331 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4332 isa<ParmVarDecl>(SizeOfPack->getPack()))
4333 return SizeOfPack->getPack();
4338 static SourceLocation getLocationFromExpr(const Expr *E) {
4339 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4340 return getLocationFromExpr(CE->getSubExpr());
4342 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4343 return /*FIXME:*/Msg->getLeftLoc();
4344 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4345 return DRE->getLocation();
4346 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4347 return Member->getMemberLoc();
4348 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4349 return Ivar->getLocation();
4350 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4351 return SizeOfPack->getPackLoc();
4352 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4353 return PropRef->getLocation();
4355 return E->getBeginLoc();
4360 unsigned clang_visitChildren(CXCursor parent,
4361 CXCursorVisitor visitor,
4362 CXClientData client_data) {
4363 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4364 /*VisitPreprocessorLast=*/false);
4365 return CursorVis.VisitChildren(parent);
4368 #ifndef __has_feature
4369 #define __has_feature(x) 0
4371 #if __has_feature(blocks)
4372 typedef enum CXChildVisitResult
4373 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4375 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4376 CXClientData client_data) {
4377 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4378 return block(cursor, parent);
4381 // If we are compiled with a compiler that doesn't have native blocks support,
4382 // define and call the block manually, so the
4383 typedef struct _CXChildVisitResult
4388 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4390 } *CXCursorVisitorBlock;
4392 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4393 CXClientData client_data) {
4394 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4395 return block->invoke(block, cursor, parent);
4400 unsigned clang_visitChildrenWithBlock(CXCursor parent,
4401 CXCursorVisitorBlock block) {
4402 return clang_visitChildren(parent, visitWithBlock, block);
4405 static CXString getDeclSpelling(const Decl *D) {
4407 return cxstring::createEmpty();
4409 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4411 if (const ObjCPropertyImplDecl *PropImpl =
4412 dyn_cast<ObjCPropertyImplDecl>(D))
4413 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4414 return cxstring::createDup(Property->getIdentifier()->getName());
4416 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4417 if (Module *Mod = ImportD->getImportedModule())
4418 return cxstring::createDup(Mod->getFullModuleName());
4420 return cxstring::createEmpty();
4423 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4424 return cxstring::createDup(OMD->getSelector().getAsString());
4426 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4427 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4428 // and returns different names. NamedDecl returns the class name and
4429 // ObjCCategoryImplDecl returns the category name.
4430 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4432 if (isa<UsingDirectiveDecl>(D))
4433 return cxstring::createEmpty();
4435 SmallString<1024> S;
4436 llvm::raw_svector_ostream os(S);
4439 return cxstring::createDup(os.str());
4442 CXString clang_getCursorSpelling(CXCursor C) {
4443 if (clang_isTranslationUnit(C.kind))
4444 return clang_getTranslationUnitSpelling(getCursorTU(C));
4446 if (clang_isReference(C.kind)) {
4448 case CXCursor_ObjCSuperClassRef: {
4449 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4450 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4452 case CXCursor_ObjCClassRef: {
4453 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4454 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4456 case CXCursor_ObjCProtocolRef: {
4457 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4458 assert(OID && "getCursorSpelling(): Missing protocol decl");
4459 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4461 case CXCursor_CXXBaseSpecifier: {
4462 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4463 return cxstring::createDup(B->getType().getAsString());
4465 case CXCursor_TypeRef: {
4466 const TypeDecl *Type = getCursorTypeRef(C).first;
4467 assert(Type && "Missing type decl");
4469 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4472 case CXCursor_TemplateRef: {
4473 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4474 assert(Template && "Missing template decl");
4476 return cxstring::createDup(Template->getNameAsString());
4479 case CXCursor_NamespaceRef: {
4480 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4481 assert(NS && "Missing namespace decl");
4483 return cxstring::createDup(NS->getNameAsString());
4486 case CXCursor_MemberRef: {
4487 const FieldDecl *Field = getCursorMemberRef(C).first;
4488 assert(Field && "Missing member decl");
4490 return cxstring::createDup(Field->getNameAsString());
4493 case CXCursor_LabelRef: {
4494 const LabelStmt *Label = getCursorLabelRef(C).first;
4495 assert(Label && "Missing label");
4497 return cxstring::createRef(Label->getName());
4500 case CXCursor_OverloadedDeclRef: {
4501 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4502 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4503 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4504 return cxstring::createDup(ND->getNameAsString());
4505 return cxstring::createEmpty();
4507 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4508 return cxstring::createDup(E->getName().getAsString());
4509 OverloadedTemplateStorage *Ovl
4510 = Storage.get<OverloadedTemplateStorage*>();
4511 if (Ovl->size() == 0)
4512 return cxstring::createEmpty();
4513 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4516 case CXCursor_VariableRef: {
4517 const VarDecl *Var = getCursorVariableRef(C).first;
4518 assert(Var && "Missing variable decl");
4520 return cxstring::createDup(Var->getNameAsString());
4524 return cxstring::createRef("<not implemented>");
4528 if (clang_isExpression(C.kind)) {
4529 const Expr *E = getCursorExpr(C);
4531 if (C.kind == CXCursor_ObjCStringLiteral ||
4532 C.kind == CXCursor_StringLiteral) {
4533 const StringLiteral *SLit;
4534 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4535 SLit = OSL->getString();
4537 SLit = cast<StringLiteral>(E);
4539 SmallString<256> Buf;
4540 llvm::raw_svector_ostream OS(Buf);
4541 SLit->outputString(OS);
4542 return cxstring::createDup(OS.str());
4545 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4547 return getDeclSpelling(D);
4548 return cxstring::createEmpty();
4551 if (clang_isStatement(C.kind)) {
4552 const Stmt *S = getCursorStmt(C);
4553 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4554 return cxstring::createRef(Label->getName());
4556 return cxstring::createEmpty();
4559 if (C.kind == CXCursor_MacroExpansion)
4560 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4563 if (C.kind == CXCursor_MacroDefinition)
4564 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4567 if (C.kind == CXCursor_InclusionDirective)
4568 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4570 if (clang_isDeclaration(C.kind))
4571 return getDeclSpelling(getCursorDecl(C));
4573 if (C.kind == CXCursor_AnnotateAttr) {
4574 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4575 return cxstring::createDup(AA->getAnnotation());
4578 if (C.kind == CXCursor_AsmLabelAttr) {
4579 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4580 return cxstring::createDup(AA->getLabel());
4583 if (C.kind == CXCursor_PackedAttr) {
4584 return cxstring::createRef("packed");
4587 if (C.kind == CXCursor_VisibilityAttr) {
4588 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4589 switch (AA->getVisibility()) {
4590 case VisibilityAttr::VisibilityType::Default:
4591 return cxstring::createRef("default");
4592 case VisibilityAttr::VisibilityType::Hidden:
4593 return cxstring::createRef("hidden");
4594 case VisibilityAttr::VisibilityType::Protected:
4595 return cxstring::createRef("protected");
4597 llvm_unreachable("unknown visibility type");
4600 return cxstring::createEmpty();
4603 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4604 unsigned pieceIndex,
4606 if (clang_Cursor_isNull(C))
4607 return clang_getNullRange();
4609 ASTContext &Ctx = getCursorContext(C);
4611 if (clang_isStatement(C.kind)) {
4612 const Stmt *S = getCursorStmt(C);
4613 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4615 return clang_getNullRange();
4616 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4619 return clang_getNullRange();
4622 if (C.kind == CXCursor_ObjCMessageExpr) {
4623 if (const ObjCMessageExpr *
4624 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4625 if (pieceIndex >= ME->getNumSelectorLocs())
4626 return clang_getNullRange();
4627 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4631 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4632 C.kind == CXCursor_ObjCClassMethodDecl) {
4633 if (const ObjCMethodDecl *
4634 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4635 if (pieceIndex >= MD->getNumSelectorLocs())
4636 return clang_getNullRange();
4637 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4641 if (C.kind == CXCursor_ObjCCategoryDecl ||
4642 C.kind == CXCursor_ObjCCategoryImplDecl) {
4644 return clang_getNullRange();
4645 if (const ObjCCategoryDecl *
4646 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4647 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4648 if (const ObjCCategoryImplDecl *
4649 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4653 if (C.kind == CXCursor_ModuleImportDecl) {
4655 return clang_getNullRange();
4656 if (const ImportDecl *ImportD =
4657 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4658 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4660 return cxloc::translateSourceRange(Ctx,
4661 SourceRange(Locs.front(), Locs.back()));
4663 return clang_getNullRange();
4666 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4667 C.kind == CXCursor_ConversionFunction ||
4668 C.kind == CXCursor_FunctionDecl) {
4670 return clang_getNullRange();
4671 if (const FunctionDecl *FD =
4672 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4673 DeclarationNameInfo FunctionName = FD->getNameInfo();
4674 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4676 return clang_getNullRange();
4679 // FIXME: A CXCursor_InclusionDirective should give the location of the
4680 // filename, but we don't keep track of this.
4682 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4683 // but we don't keep track of this.
4685 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4686 // but we don't keep track of this.
4688 // Default handling, give the location of the cursor.
4691 return clang_getNullRange();
4693 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4694 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4695 return cxloc::translateSourceRange(Ctx, Loc);
4698 CXString clang_Cursor_getMangling(CXCursor C) {
4699 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4700 return cxstring::createEmpty();
4702 // Mangling only works for functions and variables.
4703 const Decl *D = getCursorDecl(C);
4704 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4705 return cxstring::createEmpty();
4707 ASTContext &Ctx = D->getASTContext();
4708 index::CodegenNameGenerator CGNameGen(Ctx);
4709 return cxstring::createDup(CGNameGen.getName(D));
4712 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4713 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4716 const Decl *D = getCursorDecl(C);
4717 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4720 ASTContext &Ctx = D->getASTContext();
4721 index::CodegenNameGenerator CGNameGen(Ctx);
4722 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4723 return cxstring::createSet(Manglings);
4726 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4727 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4730 const Decl *D = getCursorDecl(C);
4731 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4734 ASTContext &Ctx = D->getASTContext();
4735 index::CodegenNameGenerator CGNameGen(Ctx);
4736 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4737 return cxstring::createSet(Manglings);
4740 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4741 if (clang_Cursor_isNull(C))
4743 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4746 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4748 delete static_cast<PrintingPolicy *>(Policy);
4752 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4753 enum CXPrintingPolicyProperty Property) {
4757 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4759 case CXPrintingPolicy_Indentation:
4760 return P->Indentation;
4761 case CXPrintingPolicy_SuppressSpecifiers:
4762 return P->SuppressSpecifiers;
4763 case CXPrintingPolicy_SuppressTagKeyword:
4764 return P->SuppressTagKeyword;
4765 case CXPrintingPolicy_IncludeTagDefinition:
4766 return P->IncludeTagDefinition;
4767 case CXPrintingPolicy_SuppressScope:
4768 return P->SuppressScope;
4769 case CXPrintingPolicy_SuppressUnwrittenScope:
4770 return P->SuppressUnwrittenScope;
4771 case CXPrintingPolicy_SuppressInitializers:
4772 return P->SuppressInitializers;
4773 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4774 return P->ConstantArraySizeAsWritten;
4775 case CXPrintingPolicy_AnonymousTagLocations:
4776 return P->AnonymousTagLocations;
4777 case CXPrintingPolicy_SuppressStrongLifetime:
4778 return P->SuppressStrongLifetime;
4779 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4780 return P->SuppressLifetimeQualifiers;
4781 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4782 return P->SuppressTemplateArgsInCXXConstructors;
4783 case CXPrintingPolicy_Bool:
4785 case CXPrintingPolicy_Restrict:
4787 case CXPrintingPolicy_Alignof:
4789 case CXPrintingPolicy_UnderscoreAlignof:
4790 return P->UnderscoreAlignof;
4791 case CXPrintingPolicy_UseVoidForZeroParams:
4792 return P->UseVoidForZeroParams;
4793 case CXPrintingPolicy_TerseOutput:
4794 return P->TerseOutput;
4795 case CXPrintingPolicy_PolishForDeclaration:
4796 return P->PolishForDeclaration;
4797 case CXPrintingPolicy_Half:
4799 case CXPrintingPolicy_MSWChar:
4801 case CXPrintingPolicy_IncludeNewlines:
4802 return P->IncludeNewlines;
4803 case CXPrintingPolicy_MSVCFormatting:
4804 return P->MSVCFormatting;
4805 case CXPrintingPolicy_ConstantsAsWritten:
4806 return P->ConstantsAsWritten;
4807 case CXPrintingPolicy_SuppressImplicitBase:
4808 return P->SuppressImplicitBase;
4809 case CXPrintingPolicy_FullyQualifiedName:
4810 return P->FullyQualifiedName;
4813 assert(false && "Invalid CXPrintingPolicyProperty");
4817 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4818 enum CXPrintingPolicyProperty Property,
4823 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4825 case CXPrintingPolicy_Indentation:
4826 P->Indentation = Value;
4828 case CXPrintingPolicy_SuppressSpecifiers:
4829 P->SuppressSpecifiers = Value;
4831 case CXPrintingPolicy_SuppressTagKeyword:
4832 P->SuppressTagKeyword = Value;
4834 case CXPrintingPolicy_IncludeTagDefinition:
4835 P->IncludeTagDefinition = Value;
4837 case CXPrintingPolicy_SuppressScope:
4838 P->SuppressScope = Value;
4840 case CXPrintingPolicy_SuppressUnwrittenScope:
4841 P->SuppressUnwrittenScope = Value;
4843 case CXPrintingPolicy_SuppressInitializers:
4844 P->SuppressInitializers = Value;
4846 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4847 P->ConstantArraySizeAsWritten = Value;
4849 case CXPrintingPolicy_AnonymousTagLocations:
4850 P->AnonymousTagLocations = Value;
4852 case CXPrintingPolicy_SuppressStrongLifetime:
4853 P->SuppressStrongLifetime = Value;
4855 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4856 P->SuppressLifetimeQualifiers = Value;
4858 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4859 P->SuppressTemplateArgsInCXXConstructors = Value;
4861 case CXPrintingPolicy_Bool:
4864 case CXPrintingPolicy_Restrict:
4865 P->Restrict = Value;
4867 case CXPrintingPolicy_Alignof:
4870 case CXPrintingPolicy_UnderscoreAlignof:
4871 P->UnderscoreAlignof = Value;
4873 case CXPrintingPolicy_UseVoidForZeroParams:
4874 P->UseVoidForZeroParams = Value;
4876 case CXPrintingPolicy_TerseOutput:
4877 P->TerseOutput = Value;
4879 case CXPrintingPolicy_PolishForDeclaration:
4880 P->PolishForDeclaration = Value;
4882 case CXPrintingPolicy_Half:
4885 case CXPrintingPolicy_MSWChar:
4888 case CXPrintingPolicy_IncludeNewlines:
4889 P->IncludeNewlines = Value;
4891 case CXPrintingPolicy_MSVCFormatting:
4892 P->MSVCFormatting = Value;
4894 case CXPrintingPolicy_ConstantsAsWritten:
4895 P->ConstantsAsWritten = Value;
4897 case CXPrintingPolicy_SuppressImplicitBase:
4898 P->SuppressImplicitBase = Value;
4900 case CXPrintingPolicy_FullyQualifiedName:
4901 P->FullyQualifiedName = Value;
4905 assert(false && "Invalid CXPrintingPolicyProperty");
4908 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4909 if (clang_Cursor_isNull(C))
4910 return cxstring::createEmpty();
4912 if (clang_isDeclaration(C.kind)) {
4913 const Decl *D = getCursorDecl(C);
4915 return cxstring::createEmpty();
4917 SmallString<128> Str;
4918 llvm::raw_svector_ostream OS(Str);
4919 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4920 D->print(OS, UserPolicy ? *UserPolicy
4921 : getCursorContext(C).getPrintingPolicy());
4923 return cxstring::createDup(OS.str());
4926 return cxstring::createEmpty();
4929 CXString clang_getCursorDisplayName(CXCursor C) {
4930 if (!clang_isDeclaration(C.kind))
4931 return clang_getCursorSpelling(C);
4933 const Decl *D = getCursorDecl(C);
4935 return cxstring::createEmpty();
4937 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4938 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4939 D = FunTmpl->getTemplatedDecl();
4941 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4942 SmallString<64> Str;
4943 llvm::raw_svector_ostream OS(Str);
4945 if (Function->getPrimaryTemplate())
4948 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4951 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4954 if (Function->isVariadic()) {
4955 if (Function->getNumParams())
4960 return cxstring::createDup(OS.str());
4963 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4964 SmallString<64> Str;
4965 llvm::raw_svector_ostream OS(Str);
4966 OS << *ClassTemplate;
4968 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4969 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4973 NamedDecl *Param = Params->getParam(I);
4974 if (Param->getIdentifier()) {
4975 OS << Param->getIdentifier()->getName();
4979 // There is no parameter name, which makes this tricky. Try to come up
4980 // with something useful that isn't too long.
4981 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4982 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4983 else if (NonTypeTemplateParmDecl *NTTP
4984 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4985 OS << NTTP->getType().getAsString(Policy);
4987 OS << "template<...> class";
4991 return cxstring::createDup(OS.str());
4994 if (const ClassTemplateSpecializationDecl *ClassSpec
4995 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4996 // If the type was explicitly written, use that.
4997 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4998 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5000 SmallString<128> Str;
5001 llvm::raw_svector_ostream OS(Str);
5003 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5005 return cxstring::createDup(OS.str());
5008 return clang_getCursorSpelling(C);
5011 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5013 case CXCursor_FunctionDecl:
5014 return cxstring::createRef("FunctionDecl");
5015 case CXCursor_TypedefDecl:
5016 return cxstring::createRef("TypedefDecl");
5017 case CXCursor_EnumDecl:
5018 return cxstring::createRef("EnumDecl");
5019 case CXCursor_EnumConstantDecl:
5020 return cxstring::createRef("EnumConstantDecl");
5021 case CXCursor_StructDecl:
5022 return cxstring::createRef("StructDecl");
5023 case CXCursor_UnionDecl:
5024 return cxstring::createRef("UnionDecl");
5025 case CXCursor_ClassDecl:
5026 return cxstring::createRef("ClassDecl");
5027 case CXCursor_FieldDecl:
5028 return cxstring::createRef("FieldDecl");
5029 case CXCursor_VarDecl:
5030 return cxstring::createRef("VarDecl");
5031 case CXCursor_ParmDecl:
5032 return cxstring::createRef("ParmDecl");
5033 case CXCursor_ObjCInterfaceDecl:
5034 return cxstring::createRef("ObjCInterfaceDecl");
5035 case CXCursor_ObjCCategoryDecl:
5036 return cxstring::createRef("ObjCCategoryDecl");
5037 case CXCursor_ObjCProtocolDecl:
5038 return cxstring::createRef("ObjCProtocolDecl");
5039 case CXCursor_ObjCPropertyDecl:
5040 return cxstring::createRef("ObjCPropertyDecl");
5041 case CXCursor_ObjCIvarDecl:
5042 return cxstring::createRef("ObjCIvarDecl");
5043 case CXCursor_ObjCInstanceMethodDecl:
5044 return cxstring::createRef("ObjCInstanceMethodDecl");
5045 case CXCursor_ObjCClassMethodDecl:
5046 return cxstring::createRef("ObjCClassMethodDecl");
5047 case CXCursor_ObjCImplementationDecl:
5048 return cxstring::createRef("ObjCImplementationDecl");
5049 case CXCursor_ObjCCategoryImplDecl:
5050 return cxstring::createRef("ObjCCategoryImplDecl");
5051 case CXCursor_CXXMethod:
5052 return cxstring::createRef("CXXMethod");
5053 case CXCursor_UnexposedDecl:
5054 return cxstring::createRef("UnexposedDecl");
5055 case CXCursor_ObjCSuperClassRef:
5056 return cxstring::createRef("ObjCSuperClassRef");
5057 case CXCursor_ObjCProtocolRef:
5058 return cxstring::createRef("ObjCProtocolRef");
5059 case CXCursor_ObjCClassRef:
5060 return cxstring::createRef("ObjCClassRef");
5061 case CXCursor_TypeRef:
5062 return cxstring::createRef("TypeRef");
5063 case CXCursor_TemplateRef:
5064 return cxstring::createRef("TemplateRef");
5065 case CXCursor_NamespaceRef:
5066 return cxstring::createRef("NamespaceRef");
5067 case CXCursor_MemberRef:
5068 return cxstring::createRef("MemberRef");
5069 case CXCursor_LabelRef:
5070 return cxstring::createRef("LabelRef");
5071 case CXCursor_OverloadedDeclRef:
5072 return cxstring::createRef("OverloadedDeclRef");
5073 case CXCursor_VariableRef:
5074 return cxstring::createRef("VariableRef");
5075 case CXCursor_IntegerLiteral:
5076 return cxstring::createRef("IntegerLiteral");
5077 case CXCursor_FixedPointLiteral:
5078 return cxstring::createRef("FixedPointLiteral");
5079 case CXCursor_FloatingLiteral:
5080 return cxstring::createRef("FloatingLiteral");
5081 case CXCursor_ImaginaryLiteral:
5082 return cxstring::createRef("ImaginaryLiteral");
5083 case CXCursor_StringLiteral:
5084 return cxstring::createRef("StringLiteral");
5085 case CXCursor_CharacterLiteral:
5086 return cxstring::createRef("CharacterLiteral");
5087 case CXCursor_ParenExpr:
5088 return cxstring::createRef("ParenExpr");
5089 case CXCursor_UnaryOperator:
5090 return cxstring::createRef("UnaryOperator");
5091 case CXCursor_ArraySubscriptExpr:
5092 return cxstring::createRef("ArraySubscriptExpr");
5093 case CXCursor_OMPArraySectionExpr:
5094 return cxstring::createRef("OMPArraySectionExpr");
5095 case CXCursor_BinaryOperator:
5096 return cxstring::createRef("BinaryOperator");
5097 case CXCursor_CompoundAssignOperator:
5098 return cxstring::createRef("CompoundAssignOperator");
5099 case CXCursor_ConditionalOperator:
5100 return cxstring::createRef("ConditionalOperator");
5101 case CXCursor_CStyleCastExpr:
5102 return cxstring::createRef("CStyleCastExpr");
5103 case CXCursor_CompoundLiteralExpr:
5104 return cxstring::createRef("CompoundLiteralExpr");
5105 case CXCursor_InitListExpr:
5106 return cxstring::createRef("InitListExpr");
5107 case CXCursor_AddrLabelExpr:
5108 return cxstring::createRef("AddrLabelExpr");
5109 case CXCursor_StmtExpr:
5110 return cxstring::createRef("StmtExpr");
5111 case CXCursor_GenericSelectionExpr:
5112 return cxstring::createRef("GenericSelectionExpr");
5113 case CXCursor_GNUNullExpr:
5114 return cxstring::createRef("GNUNullExpr");
5115 case CXCursor_CXXStaticCastExpr:
5116 return cxstring::createRef("CXXStaticCastExpr");
5117 case CXCursor_CXXDynamicCastExpr:
5118 return cxstring::createRef("CXXDynamicCastExpr");
5119 case CXCursor_CXXReinterpretCastExpr:
5120 return cxstring::createRef("CXXReinterpretCastExpr");
5121 case CXCursor_CXXConstCastExpr:
5122 return cxstring::createRef("CXXConstCastExpr");
5123 case CXCursor_CXXFunctionalCastExpr:
5124 return cxstring::createRef("CXXFunctionalCastExpr");
5125 case CXCursor_CXXTypeidExpr:
5126 return cxstring::createRef("CXXTypeidExpr");
5127 case CXCursor_CXXBoolLiteralExpr:
5128 return cxstring::createRef("CXXBoolLiteralExpr");
5129 case CXCursor_CXXNullPtrLiteralExpr:
5130 return cxstring::createRef("CXXNullPtrLiteralExpr");
5131 case CXCursor_CXXThisExpr:
5132 return cxstring::createRef("CXXThisExpr");
5133 case CXCursor_CXXThrowExpr:
5134 return cxstring::createRef("CXXThrowExpr");
5135 case CXCursor_CXXNewExpr:
5136 return cxstring::createRef("CXXNewExpr");
5137 case CXCursor_CXXDeleteExpr:
5138 return cxstring::createRef("CXXDeleteExpr");
5139 case CXCursor_UnaryExpr:
5140 return cxstring::createRef("UnaryExpr");
5141 case CXCursor_ObjCStringLiteral:
5142 return cxstring::createRef("ObjCStringLiteral");
5143 case CXCursor_ObjCBoolLiteralExpr:
5144 return cxstring::createRef("ObjCBoolLiteralExpr");
5145 case CXCursor_ObjCAvailabilityCheckExpr:
5146 return cxstring::createRef("ObjCAvailabilityCheckExpr");
5147 case CXCursor_ObjCSelfExpr:
5148 return cxstring::createRef("ObjCSelfExpr");
5149 case CXCursor_ObjCEncodeExpr:
5150 return cxstring::createRef("ObjCEncodeExpr");
5151 case CXCursor_ObjCSelectorExpr:
5152 return cxstring::createRef("ObjCSelectorExpr");
5153 case CXCursor_ObjCProtocolExpr:
5154 return cxstring::createRef("ObjCProtocolExpr");
5155 case CXCursor_ObjCBridgedCastExpr:
5156 return cxstring::createRef("ObjCBridgedCastExpr");
5157 case CXCursor_BlockExpr:
5158 return cxstring::createRef("BlockExpr");
5159 case CXCursor_PackExpansionExpr:
5160 return cxstring::createRef("PackExpansionExpr");
5161 case CXCursor_SizeOfPackExpr:
5162 return cxstring::createRef("SizeOfPackExpr");
5163 case CXCursor_LambdaExpr:
5164 return cxstring::createRef("LambdaExpr");
5165 case CXCursor_UnexposedExpr:
5166 return cxstring::createRef("UnexposedExpr");
5167 case CXCursor_DeclRefExpr:
5168 return cxstring::createRef("DeclRefExpr");
5169 case CXCursor_MemberRefExpr:
5170 return cxstring::createRef("MemberRefExpr");
5171 case CXCursor_CallExpr:
5172 return cxstring::createRef("CallExpr");
5173 case CXCursor_ObjCMessageExpr:
5174 return cxstring::createRef("ObjCMessageExpr");
5175 case CXCursor_UnexposedStmt:
5176 return cxstring::createRef("UnexposedStmt");
5177 case CXCursor_DeclStmt:
5178 return cxstring::createRef("DeclStmt");
5179 case CXCursor_LabelStmt:
5180 return cxstring::createRef("LabelStmt");
5181 case CXCursor_CompoundStmt:
5182 return cxstring::createRef("CompoundStmt");
5183 case CXCursor_CaseStmt:
5184 return cxstring::createRef("CaseStmt");
5185 case CXCursor_DefaultStmt:
5186 return cxstring::createRef("DefaultStmt");
5187 case CXCursor_IfStmt:
5188 return cxstring::createRef("IfStmt");
5189 case CXCursor_SwitchStmt:
5190 return cxstring::createRef("SwitchStmt");
5191 case CXCursor_WhileStmt:
5192 return cxstring::createRef("WhileStmt");
5193 case CXCursor_DoStmt:
5194 return cxstring::createRef("DoStmt");
5195 case CXCursor_ForStmt:
5196 return cxstring::createRef("ForStmt");
5197 case CXCursor_GotoStmt:
5198 return cxstring::createRef("GotoStmt");
5199 case CXCursor_IndirectGotoStmt:
5200 return cxstring::createRef("IndirectGotoStmt");
5201 case CXCursor_ContinueStmt:
5202 return cxstring::createRef("ContinueStmt");
5203 case CXCursor_BreakStmt:
5204 return cxstring::createRef("BreakStmt");
5205 case CXCursor_ReturnStmt:
5206 return cxstring::createRef("ReturnStmt");
5207 case CXCursor_GCCAsmStmt:
5208 return cxstring::createRef("GCCAsmStmt");
5209 case CXCursor_MSAsmStmt:
5210 return cxstring::createRef("MSAsmStmt");
5211 case CXCursor_ObjCAtTryStmt:
5212 return cxstring::createRef("ObjCAtTryStmt");
5213 case CXCursor_ObjCAtCatchStmt:
5214 return cxstring::createRef("ObjCAtCatchStmt");
5215 case CXCursor_ObjCAtFinallyStmt:
5216 return cxstring::createRef("ObjCAtFinallyStmt");
5217 case CXCursor_ObjCAtThrowStmt:
5218 return cxstring::createRef("ObjCAtThrowStmt");
5219 case CXCursor_ObjCAtSynchronizedStmt:
5220 return cxstring::createRef("ObjCAtSynchronizedStmt");
5221 case CXCursor_ObjCAutoreleasePoolStmt:
5222 return cxstring::createRef("ObjCAutoreleasePoolStmt");
5223 case CXCursor_ObjCForCollectionStmt:
5224 return cxstring::createRef("ObjCForCollectionStmt");
5225 case CXCursor_CXXCatchStmt:
5226 return cxstring::createRef("CXXCatchStmt");
5227 case CXCursor_CXXTryStmt:
5228 return cxstring::createRef("CXXTryStmt");
5229 case CXCursor_CXXForRangeStmt:
5230 return cxstring::createRef("CXXForRangeStmt");
5231 case CXCursor_SEHTryStmt:
5232 return cxstring::createRef("SEHTryStmt");
5233 case CXCursor_SEHExceptStmt:
5234 return cxstring::createRef("SEHExceptStmt");
5235 case CXCursor_SEHFinallyStmt:
5236 return cxstring::createRef("SEHFinallyStmt");
5237 case CXCursor_SEHLeaveStmt:
5238 return cxstring::createRef("SEHLeaveStmt");
5239 case CXCursor_NullStmt:
5240 return cxstring::createRef("NullStmt");
5241 case CXCursor_InvalidFile:
5242 return cxstring::createRef("InvalidFile");
5243 case CXCursor_InvalidCode:
5244 return cxstring::createRef("InvalidCode");
5245 case CXCursor_NoDeclFound:
5246 return cxstring::createRef("NoDeclFound");
5247 case CXCursor_NotImplemented:
5248 return cxstring::createRef("NotImplemented");
5249 case CXCursor_TranslationUnit:
5250 return cxstring::createRef("TranslationUnit");
5251 case CXCursor_UnexposedAttr:
5252 return cxstring::createRef("UnexposedAttr");
5253 case CXCursor_IBActionAttr:
5254 return cxstring::createRef("attribute(ibaction)");
5255 case CXCursor_IBOutletAttr:
5256 return cxstring::createRef("attribute(iboutlet)");
5257 case CXCursor_IBOutletCollectionAttr:
5258 return cxstring::createRef("attribute(iboutletcollection)");
5259 case CXCursor_CXXFinalAttr:
5260 return cxstring::createRef("attribute(final)");
5261 case CXCursor_CXXOverrideAttr:
5262 return cxstring::createRef("attribute(override)");
5263 case CXCursor_AnnotateAttr:
5264 return cxstring::createRef("attribute(annotate)");
5265 case CXCursor_AsmLabelAttr:
5266 return cxstring::createRef("asm label");
5267 case CXCursor_PackedAttr:
5268 return cxstring::createRef("attribute(packed)");
5269 case CXCursor_PureAttr:
5270 return cxstring::createRef("attribute(pure)");
5271 case CXCursor_ConstAttr:
5272 return cxstring::createRef("attribute(const)");
5273 case CXCursor_NoDuplicateAttr:
5274 return cxstring::createRef("attribute(noduplicate)");
5275 case CXCursor_CUDAConstantAttr:
5276 return cxstring::createRef("attribute(constant)");
5277 case CXCursor_CUDADeviceAttr:
5278 return cxstring::createRef("attribute(device)");
5279 case CXCursor_CUDAGlobalAttr:
5280 return cxstring::createRef("attribute(global)");
5281 case CXCursor_CUDAHostAttr:
5282 return cxstring::createRef("attribute(host)");
5283 case CXCursor_CUDASharedAttr:
5284 return cxstring::createRef("attribute(shared)");
5285 case CXCursor_VisibilityAttr:
5286 return cxstring::createRef("attribute(visibility)");
5287 case CXCursor_DLLExport:
5288 return cxstring::createRef("attribute(dllexport)");
5289 case CXCursor_DLLImport:
5290 return cxstring::createRef("attribute(dllimport)");
5291 case CXCursor_NSReturnsRetained:
5292 return cxstring::createRef("attribute(ns_returns_retained)");
5293 case CXCursor_NSReturnsNotRetained:
5294 return cxstring::createRef("attribute(ns_returns_not_retained)");
5295 case CXCursor_NSReturnsAutoreleased:
5296 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5297 case CXCursor_NSConsumesSelf:
5298 return cxstring::createRef("attribute(ns_consumes_self)");
5299 case CXCursor_NSConsumed:
5300 return cxstring::createRef("attribute(ns_consumed)");
5301 case CXCursor_ObjCException:
5302 return cxstring::createRef("attribute(objc_exception)");
5303 case CXCursor_ObjCNSObject:
5304 return cxstring::createRef("attribute(NSObject)");
5305 case CXCursor_ObjCIndependentClass:
5306 return cxstring::createRef("attribute(objc_independent_class)");
5307 case CXCursor_ObjCPreciseLifetime:
5308 return cxstring::createRef("attribute(objc_precise_lifetime)");
5309 case CXCursor_ObjCReturnsInnerPointer:
5310 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5311 case CXCursor_ObjCRequiresSuper:
5312 return cxstring::createRef("attribute(objc_requires_super)");
5313 case CXCursor_ObjCRootClass:
5314 return cxstring::createRef("attribute(objc_root_class)");
5315 case CXCursor_ObjCSubclassingRestricted:
5316 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5317 case CXCursor_ObjCExplicitProtocolImpl:
5318 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5319 case CXCursor_ObjCDesignatedInitializer:
5320 return cxstring::createRef("attribute(objc_designated_initializer)");
5321 case CXCursor_ObjCRuntimeVisible:
5322 return cxstring::createRef("attribute(objc_runtime_visible)");
5323 case CXCursor_ObjCBoxable:
5324 return cxstring::createRef("attribute(objc_boxable)");
5325 case CXCursor_FlagEnum:
5326 return cxstring::createRef("attribute(flag_enum)");
5327 case CXCursor_PreprocessingDirective:
5328 return cxstring::createRef("preprocessing directive");
5329 case CXCursor_MacroDefinition:
5330 return cxstring::createRef("macro definition");
5331 case CXCursor_MacroExpansion:
5332 return cxstring::createRef("macro expansion");
5333 case CXCursor_InclusionDirective:
5334 return cxstring::createRef("inclusion directive");
5335 case CXCursor_Namespace:
5336 return cxstring::createRef("Namespace");
5337 case CXCursor_LinkageSpec:
5338 return cxstring::createRef("LinkageSpec");
5339 case CXCursor_CXXBaseSpecifier:
5340 return cxstring::createRef("C++ base class specifier");
5341 case CXCursor_Constructor:
5342 return cxstring::createRef("CXXConstructor");
5343 case CXCursor_Destructor:
5344 return cxstring::createRef("CXXDestructor");
5345 case CXCursor_ConversionFunction:
5346 return cxstring::createRef("CXXConversion");
5347 case CXCursor_TemplateTypeParameter:
5348 return cxstring::createRef("TemplateTypeParameter");
5349 case CXCursor_NonTypeTemplateParameter:
5350 return cxstring::createRef("NonTypeTemplateParameter");
5351 case CXCursor_TemplateTemplateParameter:
5352 return cxstring::createRef("TemplateTemplateParameter");
5353 case CXCursor_FunctionTemplate:
5354 return cxstring::createRef("FunctionTemplate");
5355 case CXCursor_ClassTemplate:
5356 return cxstring::createRef("ClassTemplate");
5357 case CXCursor_ClassTemplatePartialSpecialization:
5358 return cxstring::createRef("ClassTemplatePartialSpecialization");
5359 case CXCursor_NamespaceAlias:
5360 return cxstring::createRef("NamespaceAlias");
5361 case CXCursor_UsingDirective:
5362 return cxstring::createRef("UsingDirective");
5363 case CXCursor_UsingDeclaration:
5364 return cxstring::createRef("UsingDeclaration");
5365 case CXCursor_TypeAliasDecl:
5366 return cxstring::createRef("TypeAliasDecl");
5367 case CXCursor_ObjCSynthesizeDecl:
5368 return cxstring::createRef("ObjCSynthesizeDecl");
5369 case CXCursor_ObjCDynamicDecl:
5370 return cxstring::createRef("ObjCDynamicDecl");
5371 case CXCursor_CXXAccessSpecifier:
5372 return cxstring::createRef("CXXAccessSpecifier");
5373 case CXCursor_ModuleImportDecl:
5374 return cxstring::createRef("ModuleImport");
5375 case CXCursor_OMPParallelDirective:
5376 return cxstring::createRef("OMPParallelDirective");
5377 case CXCursor_OMPSimdDirective:
5378 return cxstring::createRef("OMPSimdDirective");
5379 case CXCursor_OMPForDirective:
5380 return cxstring::createRef("OMPForDirective");
5381 case CXCursor_OMPForSimdDirective:
5382 return cxstring::createRef("OMPForSimdDirective");
5383 case CXCursor_OMPSectionsDirective:
5384 return cxstring::createRef("OMPSectionsDirective");
5385 case CXCursor_OMPSectionDirective:
5386 return cxstring::createRef("OMPSectionDirective");
5387 case CXCursor_OMPSingleDirective:
5388 return cxstring::createRef("OMPSingleDirective");
5389 case CXCursor_OMPMasterDirective:
5390 return cxstring::createRef("OMPMasterDirective");
5391 case CXCursor_OMPCriticalDirective:
5392 return cxstring::createRef("OMPCriticalDirective");
5393 case CXCursor_OMPParallelForDirective:
5394 return cxstring::createRef("OMPParallelForDirective");
5395 case CXCursor_OMPParallelForSimdDirective:
5396 return cxstring::createRef("OMPParallelForSimdDirective");
5397 case CXCursor_OMPParallelSectionsDirective:
5398 return cxstring::createRef("OMPParallelSectionsDirective");
5399 case CXCursor_OMPTaskDirective:
5400 return cxstring::createRef("OMPTaskDirective");
5401 case CXCursor_OMPTaskyieldDirective:
5402 return cxstring::createRef("OMPTaskyieldDirective");
5403 case CXCursor_OMPBarrierDirective:
5404 return cxstring::createRef("OMPBarrierDirective");
5405 case CXCursor_OMPTaskwaitDirective:
5406 return cxstring::createRef("OMPTaskwaitDirective");
5407 case CXCursor_OMPTaskgroupDirective:
5408 return cxstring::createRef("OMPTaskgroupDirective");
5409 case CXCursor_OMPFlushDirective:
5410 return cxstring::createRef("OMPFlushDirective");
5411 case CXCursor_OMPOrderedDirective:
5412 return cxstring::createRef("OMPOrderedDirective");
5413 case CXCursor_OMPAtomicDirective:
5414 return cxstring::createRef("OMPAtomicDirective");
5415 case CXCursor_OMPTargetDirective:
5416 return cxstring::createRef("OMPTargetDirective");
5417 case CXCursor_OMPTargetDataDirective:
5418 return cxstring::createRef("OMPTargetDataDirective");
5419 case CXCursor_OMPTargetEnterDataDirective:
5420 return cxstring::createRef("OMPTargetEnterDataDirective");
5421 case CXCursor_OMPTargetExitDataDirective:
5422 return cxstring::createRef("OMPTargetExitDataDirective");
5423 case CXCursor_OMPTargetParallelDirective:
5424 return cxstring::createRef("OMPTargetParallelDirective");
5425 case CXCursor_OMPTargetParallelForDirective:
5426 return cxstring::createRef("OMPTargetParallelForDirective");
5427 case CXCursor_OMPTargetUpdateDirective:
5428 return cxstring::createRef("OMPTargetUpdateDirective");
5429 case CXCursor_OMPTeamsDirective:
5430 return cxstring::createRef("OMPTeamsDirective");
5431 case CXCursor_OMPCancellationPointDirective:
5432 return cxstring::createRef("OMPCancellationPointDirective");
5433 case CXCursor_OMPCancelDirective:
5434 return cxstring::createRef("OMPCancelDirective");
5435 case CXCursor_OMPTaskLoopDirective:
5436 return cxstring::createRef("OMPTaskLoopDirective");
5437 case CXCursor_OMPTaskLoopSimdDirective:
5438 return cxstring::createRef("OMPTaskLoopSimdDirective");
5439 case CXCursor_OMPDistributeDirective:
5440 return cxstring::createRef("OMPDistributeDirective");
5441 case CXCursor_OMPDistributeParallelForDirective:
5442 return cxstring::createRef("OMPDistributeParallelForDirective");
5443 case CXCursor_OMPDistributeParallelForSimdDirective:
5444 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5445 case CXCursor_OMPDistributeSimdDirective:
5446 return cxstring::createRef("OMPDistributeSimdDirective");
5447 case CXCursor_OMPTargetParallelForSimdDirective:
5448 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5449 case CXCursor_OMPTargetSimdDirective:
5450 return cxstring::createRef("OMPTargetSimdDirective");
5451 case CXCursor_OMPTeamsDistributeDirective:
5452 return cxstring::createRef("OMPTeamsDistributeDirective");
5453 case CXCursor_OMPTeamsDistributeSimdDirective:
5454 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5455 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5456 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5457 case CXCursor_OMPTeamsDistributeParallelForDirective:
5458 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5459 case CXCursor_OMPTargetTeamsDirective:
5460 return cxstring::createRef("OMPTargetTeamsDirective");
5461 case CXCursor_OMPTargetTeamsDistributeDirective:
5462 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5463 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5465 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5466 return cxstring::createRef(
5467 "OMPTargetTeamsDistributeParallelForSimdDirective");
5468 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5469 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5470 case CXCursor_OverloadCandidate:
5471 return cxstring::createRef("OverloadCandidate");
5472 case CXCursor_TypeAliasTemplateDecl:
5473 return cxstring::createRef("TypeAliasTemplateDecl");
5474 case CXCursor_StaticAssert:
5475 return cxstring::createRef("StaticAssert");
5476 case CXCursor_FriendDecl:
5477 return cxstring::createRef("FriendDecl");
5480 llvm_unreachable("Unhandled CXCursorKind");
5483 struct GetCursorData {
5484 SourceLocation TokenBeginLoc;
5485 bool PointsAtMacroArgExpansion;
5486 bool VisitedObjCPropertyImplDecl;
5487 SourceLocation VisitedDeclaratorDeclStartLoc;
5488 CXCursor &BestCursor;
5490 GetCursorData(SourceManager &SM,
5491 SourceLocation tokenBegin, CXCursor &outputCursor)
5492 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5493 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5494 VisitedObjCPropertyImplDecl = false;
5498 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5500 CXClientData client_data) {
5501 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5502 CXCursor *BestCursor = &Data->BestCursor;
5504 // If we point inside a macro argument we should provide info of what the
5505 // token is so use the actual cursor, don't replace it with a macro expansion
5507 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5508 return CXChildVisit_Recurse;
5510 if (clang_isDeclaration(cursor.kind)) {
5511 // Avoid having the implicit methods override the property decls.
5512 if (const ObjCMethodDecl *MD
5513 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5514 if (MD->isImplicit())
5515 return CXChildVisit_Break;
5517 } else if (const ObjCInterfaceDecl *ID
5518 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5519 // Check that when we have multiple @class references in the same line,
5520 // that later ones do not override the previous ones.
5523 // source ranges for both start at '@', so 'Bar' will end up overriding
5524 // 'Foo' even though the cursor location was at 'Foo'.
5525 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5526 BestCursor->kind == CXCursor_ObjCClassRef)
5527 if (const ObjCInterfaceDecl *PrevID
5528 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5530 !PrevID->isThisDeclarationADefinition() &&
5531 !ID->isThisDeclarationADefinition())
5532 return CXChildVisit_Break;
5535 } else if (const DeclaratorDecl *DD
5536 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5537 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5538 // Check that when we have multiple declarators in the same line,
5539 // that later ones do not override the previous ones.
5542 // source ranges for both start at 'int', so 'Bar' will end up overriding
5543 // 'Foo' even though the cursor location was at 'Foo'.
5544 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5545 return CXChildVisit_Break;
5546 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5548 } else if (const ObjCPropertyImplDecl *PropImp
5549 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5551 // Check that when we have multiple @synthesize in the same line,
5552 // that later ones do not override the previous ones.
5554 // @synthesize Foo, Bar;
5555 // source ranges for both start at '@', so 'Bar' will end up overriding
5556 // 'Foo' even though the cursor location was at 'Foo'.
5557 if (Data->VisitedObjCPropertyImplDecl)
5558 return CXChildVisit_Break;
5559 Data->VisitedObjCPropertyImplDecl = true;
5563 if (clang_isExpression(cursor.kind) &&
5564 clang_isDeclaration(BestCursor->kind)) {
5565 if (const Decl *D = getCursorDecl(*BestCursor)) {
5566 // Avoid having the cursor of an expression replace the declaration cursor
5567 // when the expression source range overlaps the declaration range.
5568 // This can happen for C++ constructor expressions whose range generally
5569 // include the variable declaration, e.g.:
5570 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5571 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5572 D->getLocation() == Data->TokenBeginLoc)
5573 return CXChildVisit_Break;
5577 // If our current best cursor is the construction of a temporary object,
5578 // don't replace that cursor with a type reference, because we want
5579 // clang_getCursor() to point at the constructor.
5580 if (clang_isExpression(BestCursor->kind) &&
5581 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5582 cursor.kind == CXCursor_TypeRef) {
5583 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5584 // as having the actual point on the type reference.
5585 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5586 return CXChildVisit_Recurse;
5589 // If we already have an Objective-C superclass reference, don't
5590 // update it further.
5591 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5592 return CXChildVisit_Break;
5594 *BestCursor = cursor;
5595 return CXChildVisit_Recurse;
5598 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
5599 if (isNotUsableTU(TU)) {
5601 return clang_getNullCursor();
5604 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5605 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5607 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5608 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5612 unsigned SearchLine, SearchColumn;
5614 unsigned ResultLine, ResultColumn;
5615 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5616 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5617 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5619 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5621 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
5622 &ResultColumn, nullptr);
5623 SearchFileName = clang_getFileName(SearchFile);
5624 ResultFileName = clang_getFileName(ResultFile);
5625 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5626 USR = clang_getCursorUSR(Result);
5627 *Log << llvm::format("(%s:%d:%d) = %s",
5628 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5629 clang_getCString(KindSpelling))
5630 << llvm::format("(%s:%d:%d):%s%s",
5631 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5632 clang_getCString(USR), IsDef);
5633 clang_disposeString(SearchFileName);
5634 clang_disposeString(ResultFileName);
5635 clang_disposeString(KindSpelling);
5636 clang_disposeString(USR);
5638 CXCursor Definition = clang_getCursorDefinition(Result);
5639 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5640 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5641 CXString DefinitionKindSpelling
5642 = clang_getCursorKindSpelling(Definition.kind);
5643 CXFile DefinitionFile;
5644 unsigned DefinitionLine, DefinitionColumn;
5645 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5646 &DefinitionLine, &DefinitionColumn, nullptr);
5647 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5648 *Log << llvm::format(" -> %s(%s:%d:%d)",
5649 clang_getCString(DefinitionKindSpelling),
5650 clang_getCString(DefinitionFileName),
5651 DefinitionLine, DefinitionColumn);
5652 clang_disposeString(DefinitionFileName);
5653 clang_disposeString(DefinitionKindSpelling);
5660 CXCursor clang_getNullCursor(void) {
5661 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5664 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5665 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5666 // can't set consistently. For example, when visiting a DeclStmt we will set
5667 // it but we don't set it on the result of clang_getCursorDefinition for
5668 // a reference of the same declaration.
5669 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5670 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5671 // to provide that kind of info.
5672 if (clang_isDeclaration(X.kind))
5673 X.data[1] = nullptr;
5674 if (clang_isDeclaration(Y.kind))
5675 Y.data[1] = nullptr;
5680 unsigned clang_hashCursor(CXCursor C) {
5682 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5685 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5686 std::make_pair(C.kind, C.data[Index]));
5689 unsigned clang_isInvalid(enum CXCursorKind K) {
5690 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5693 unsigned clang_isDeclaration(enum CXCursorKind K) {
5694 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5695 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5698 unsigned clang_isInvalidDeclaration(CXCursor C) {
5699 if (clang_isDeclaration(C.kind)) {
5700 if (const Decl *D = getCursorDecl(C))
5701 return D->isInvalidDecl();
5707 unsigned clang_isReference(enum CXCursorKind K) {
5708 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5711 unsigned clang_isExpression(enum CXCursorKind K) {
5712 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5715 unsigned clang_isStatement(enum CXCursorKind K) {
5716 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5719 unsigned clang_isAttribute(enum CXCursorKind K) {
5720 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5723 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5724 return K == CXCursor_TranslationUnit;
5727 unsigned clang_isPreprocessing(enum CXCursorKind K) {
5728 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5731 unsigned clang_isUnexposed(enum CXCursorKind K) {
5733 case CXCursor_UnexposedDecl:
5734 case CXCursor_UnexposedExpr:
5735 case CXCursor_UnexposedStmt:
5736 case CXCursor_UnexposedAttr:
5743 CXCursorKind clang_getCursorKind(CXCursor C) {
5747 CXSourceLocation clang_getCursorLocation(CXCursor C) {
5748 if (clang_isReference(C.kind)) {
5750 case CXCursor_ObjCSuperClassRef: {
5751 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5752 = getCursorObjCSuperClassRef(C);
5753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5756 case CXCursor_ObjCProtocolRef: {
5757 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5758 = getCursorObjCProtocolRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5762 case CXCursor_ObjCClassRef: {
5763 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5764 = getCursorObjCClassRef(C);
5765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5768 case CXCursor_TypeRef: {
5769 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5773 case CXCursor_TemplateRef: {
5774 std::pair<const TemplateDecl *, SourceLocation> P =
5775 getCursorTemplateRef(C);
5776 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5779 case CXCursor_NamespaceRef: {
5780 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5781 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5784 case CXCursor_MemberRef: {
5785 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5789 case CXCursor_VariableRef: {
5790 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5794 case CXCursor_CXXBaseSpecifier: {
5795 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5797 return clang_getNullLocation();
5799 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5800 return cxloc::translateSourceLocation(getCursorContext(C),
5801 TSInfo->getTypeLoc().getBeginLoc());
5803 return cxloc::translateSourceLocation(getCursorContext(C),
5804 BaseSpec->getBeginLoc());
5807 case CXCursor_LabelRef: {
5808 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5809 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5812 case CXCursor_OverloadedDeclRef:
5813 return cxloc::translateSourceLocation(getCursorContext(C),
5814 getCursorOverloadedDeclRef(C).second);
5817 // FIXME: Need a way to enumerate all non-reference cases.
5818 llvm_unreachable("Missed a reference kind");
5822 if (clang_isExpression(C.kind))
5823 return cxloc::translateSourceLocation(getCursorContext(C),
5824 getLocationFromExpr(getCursorExpr(C)));
5826 if (clang_isStatement(C.kind))
5827 return cxloc::translateSourceLocation(getCursorContext(C),
5828 getCursorStmt(C)->getBeginLoc());
5830 if (C.kind == CXCursor_PreprocessingDirective) {
5831 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5832 return cxloc::translateSourceLocation(getCursorContext(C), L);
5835 if (C.kind == CXCursor_MacroExpansion) {
5837 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5838 return cxloc::translateSourceLocation(getCursorContext(C), L);
5841 if (C.kind == CXCursor_MacroDefinition) {
5842 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5843 return cxloc::translateSourceLocation(getCursorContext(C), L);
5846 if (C.kind == CXCursor_InclusionDirective) {
5848 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5852 if (clang_isAttribute(C.kind)) {
5854 = cxcursor::getCursorAttr(C)->getLocation();
5855 return cxloc::translateSourceLocation(getCursorContext(C), L);
5858 if (!clang_isDeclaration(C.kind))
5859 return clang_getNullLocation();
5861 const Decl *D = getCursorDecl(C);
5863 return clang_getNullLocation();
5865 SourceLocation Loc = D->getLocation();
5866 // FIXME: Multiple variables declared in a single declaration
5867 // currently lack the information needed to correctly determine their
5868 // ranges when accounting for the type-specifier. We use context
5869 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5870 // and if so, whether it is the first decl.
5871 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5872 if (!cxcursor::isFirstInDeclGroup(C))
5873 Loc = VD->getLocation();
5876 // For ObjC methods, give the start location of the method name.
5877 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5878 Loc = MD->getSelectorStartLoc();
5880 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5885 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5888 // Guard against an invalid SourceLocation, or we may assert in one
5889 // of the following calls.
5890 if (SLoc.isInvalid())
5891 return clang_getNullCursor();
5893 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5895 // Translate the given source location to make it point at the beginning of
5896 // the token under the cursor.
5897 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5898 CXXUnit->getASTContext().getLangOpts());
5900 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5901 if (SLoc.isValid()) {
5902 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5903 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5904 /*VisitPreprocessorLast=*/true,
5905 /*VisitIncludedEntities=*/false,
5906 SourceLocation(SLoc));
5907 CursorVis.visitFileRegion();
5913 static SourceRange getRawCursorExtent(CXCursor C) {
5914 if (clang_isReference(C.kind)) {
5916 case CXCursor_ObjCSuperClassRef:
5917 return getCursorObjCSuperClassRef(C).second;
5919 case CXCursor_ObjCProtocolRef:
5920 return getCursorObjCProtocolRef(C).second;
5922 case CXCursor_ObjCClassRef:
5923 return getCursorObjCClassRef(C).second;
5925 case CXCursor_TypeRef:
5926 return getCursorTypeRef(C).second;
5928 case CXCursor_TemplateRef:
5929 return getCursorTemplateRef(C).second;
5931 case CXCursor_NamespaceRef:
5932 return getCursorNamespaceRef(C).second;
5934 case CXCursor_MemberRef:
5935 return getCursorMemberRef(C).second;
5937 case CXCursor_CXXBaseSpecifier:
5938 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5940 case CXCursor_LabelRef:
5941 return getCursorLabelRef(C).second;
5943 case CXCursor_OverloadedDeclRef:
5944 return getCursorOverloadedDeclRef(C).second;
5946 case CXCursor_VariableRef:
5947 return getCursorVariableRef(C).second;
5950 // FIXME: Need a way to enumerate all non-reference cases.
5951 llvm_unreachable("Missed a reference kind");
5955 if (clang_isExpression(C.kind))
5956 return getCursorExpr(C)->getSourceRange();
5958 if (clang_isStatement(C.kind))
5959 return getCursorStmt(C)->getSourceRange();
5961 if (clang_isAttribute(C.kind))
5962 return getCursorAttr(C)->getRange();
5964 if (C.kind == CXCursor_PreprocessingDirective)
5965 return cxcursor::getCursorPreprocessingDirective(C);
5967 if (C.kind == CXCursor_MacroExpansion) {
5968 ASTUnit *TU = getCursorASTUnit(C);
5969 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5970 return TU->mapRangeFromPreamble(Range);
5973 if (C.kind == CXCursor_MacroDefinition) {
5974 ASTUnit *TU = getCursorASTUnit(C);
5975 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5976 return TU->mapRangeFromPreamble(Range);
5979 if (C.kind == CXCursor_InclusionDirective) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5982 return TU->mapRangeFromPreamble(Range);
5985 if (C.kind == CXCursor_TranslationUnit) {
5986 ASTUnit *TU = getCursorASTUnit(C);
5987 FileID MainID = TU->getSourceManager().getMainFileID();
5988 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5989 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5990 return SourceRange(Start, End);
5993 if (clang_isDeclaration(C.kind)) {
5994 const Decl *D = cxcursor::getCursorDecl(C);
5996 return SourceRange();
5998 SourceRange R = D->getSourceRange();
5999 // FIXME: Multiple variables declared in a single declaration
6000 // currently lack the information needed to correctly determine their
6001 // ranges when accounting for the type-specifier. We use context
6002 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6003 // and if so, whether it is the first decl.
6004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6005 if (!cxcursor::isFirstInDeclGroup(C))
6006 R.setBegin(VD->getLocation());
6010 return SourceRange();
6013 /// Retrieves the "raw" cursor extent, which is then extended to include
6014 /// the decl-specifier-seq for declarations.
6015 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6016 if (clang_isDeclaration(C.kind)) {
6017 const Decl *D = cxcursor::getCursorDecl(C);
6019 return SourceRange();
6021 SourceRange R = D->getSourceRange();
6023 // Adjust the start of the location for declarations preceded by
6024 // declaration specifiers.
6025 SourceLocation StartLoc;
6026 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6027 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
6028 StartLoc = TI->getTypeLoc().getBeginLoc();
6029 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
6030 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
6031 StartLoc = TI->getTypeLoc().getBeginLoc();
6034 if (StartLoc.isValid() && R.getBegin().isValid() &&
6035 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6036 R.setBegin(StartLoc);
6038 // FIXME: Multiple variables declared in a single declaration
6039 // currently lack the information needed to correctly determine their
6040 // ranges when accounting for the type-specifier. We use context
6041 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6042 // and if so, whether it is the first decl.
6043 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6044 if (!cxcursor::isFirstInDeclGroup(C))
6045 R.setBegin(VD->getLocation());
6051 return getRawCursorExtent(C);
6054 CXSourceRange clang_getCursorExtent(CXCursor C) {
6055 SourceRange R = getRawCursorExtent(C);
6057 return clang_getNullRange();
6059 return cxloc::translateSourceRange(getCursorContext(C), R);
6062 CXCursor clang_getCursorReferenced(CXCursor C) {
6063 if (clang_isInvalid(C.kind))
6064 return clang_getNullCursor();
6066 CXTranslationUnit tu = getCursorTU(C);
6067 if (clang_isDeclaration(C.kind)) {
6068 const Decl *D = getCursorDecl(C);
6070 return clang_getNullCursor();
6071 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6072 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
6073 if (const ObjCPropertyImplDecl *PropImpl =
6074 dyn_cast<ObjCPropertyImplDecl>(D))
6075 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6076 return MakeCXCursor(Property, tu);
6081 if (clang_isExpression(C.kind)) {
6082 const Expr *E = getCursorExpr(C);
6083 const Decl *D = getDeclFromExpr(E);
6085 CXCursor declCursor = MakeCXCursor(D, tu);
6086 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6091 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
6092 return MakeCursorOverloadedDeclRef(Ovl, tu);
6094 return clang_getNullCursor();
6097 if (clang_isStatement(C.kind)) {
6098 const Stmt *S = getCursorStmt(C);
6099 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
6100 if (LabelDecl *label = Goto->getLabel())
6101 if (LabelStmt *labelS = label->getStmt())
6102 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6104 return clang_getNullCursor();
6107 if (C.kind == CXCursor_MacroExpansion) {
6108 if (const MacroDefinitionRecord *Def =
6109 getCursorMacroExpansion(C).getDefinition())
6110 return MakeMacroDefinitionCursor(Def, tu);
6113 if (!clang_isReference(C.kind))
6114 return clang_getNullCursor();
6117 case CXCursor_ObjCSuperClassRef:
6118 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6120 case CXCursor_ObjCProtocolRef: {
6121 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6122 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
6123 return MakeCXCursor(Def, tu);
6125 return MakeCXCursor(Prot, tu);
6128 case CXCursor_ObjCClassRef: {
6129 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6130 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6131 return MakeCXCursor(Def, tu);
6133 return MakeCXCursor(Class, tu);
6136 case CXCursor_TypeRef:
6137 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6139 case CXCursor_TemplateRef:
6140 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6142 case CXCursor_NamespaceRef:
6143 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6145 case CXCursor_MemberRef:
6146 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6148 case CXCursor_CXXBaseSpecifier: {
6149 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
6150 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6154 case CXCursor_LabelRef:
6155 // FIXME: We end up faking the "parent" declaration here because we
6156 // don't want to make CXCursor larger.
6157 return MakeCXCursor(getCursorLabelRef(C).first,
6158 cxtu::getASTUnit(tu)->getASTContext()
6159 .getTranslationUnitDecl(),
6162 case CXCursor_OverloadedDeclRef:
6165 case CXCursor_VariableRef:
6166 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6169 // We would prefer to enumerate all non-reference cursor kinds here.
6170 llvm_unreachable("Unhandled reference cursor kind");
6174 CXCursor clang_getCursorDefinition(CXCursor C) {
6175 if (clang_isInvalid(C.kind))
6176 return clang_getNullCursor();
6178 CXTranslationUnit TU = getCursorTU(C);
6180 bool WasReference = false;
6181 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6182 C = clang_getCursorReferenced(C);
6183 WasReference = true;
6186 if (C.kind == CXCursor_MacroExpansion)
6187 return clang_getCursorReferenced(C);
6189 if (!clang_isDeclaration(C.kind))
6190 return clang_getNullCursor();
6192 const Decl *D = getCursorDecl(C);
6194 return clang_getNullCursor();
6196 switch (D->getKind()) {
6197 // Declaration kinds that don't really separate the notions of
6198 // declaration and definition.
6199 case Decl::Namespace:
6201 case Decl::TypeAlias:
6202 case Decl::TypeAliasTemplate:
6203 case Decl::TemplateTypeParm:
6204 case Decl::EnumConstant:
6207 case Decl::MSProperty:
6208 case Decl::IndirectField:
6209 case Decl::ObjCIvar:
6210 case Decl::ObjCAtDefsField:
6211 case Decl::ImplicitParam:
6213 case Decl::NonTypeTemplateParm:
6214 case Decl::TemplateTemplateParm:
6215 case Decl::ObjCCategoryImpl:
6216 case Decl::ObjCImplementation:
6217 case Decl::AccessSpec:
6218 case Decl::LinkageSpec:
6220 case Decl::ObjCPropertyImpl:
6221 case Decl::FileScopeAsm:
6222 case Decl::StaticAssert:
6224 case Decl::Captured:
6225 case Decl::OMPCapturedExpr:
6226 case Decl::Label: // FIXME: Is this right??
6227 case Decl::ClassScopeFunctionSpecialization:
6228 case Decl::CXXDeductionGuide:
6230 case Decl::OMPThreadPrivate:
6231 case Decl::OMPDeclareReduction:
6232 case Decl::OMPRequires:
6233 case Decl::ObjCTypeParam:
6234 case Decl::BuiltinTemplate:
6235 case Decl::PragmaComment:
6236 case Decl::PragmaDetectMismatch:
6237 case Decl::UsingPack:
6240 // Declaration kinds that don't make any sense here, but are
6241 // nonetheless harmless.
6243 case Decl::TranslationUnit:
6244 case Decl::ExternCContext:
6247 // Declaration kinds for which the definition is not resolvable.
6248 case Decl::UnresolvedUsingTypename:
6249 case Decl::UnresolvedUsingValue:
6252 case Decl::UsingDirective:
6253 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6256 case Decl::NamespaceAlias:
6257 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6261 case Decl::CXXRecord:
6262 case Decl::ClassTemplateSpecialization:
6263 case Decl::ClassTemplatePartialSpecialization:
6264 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6265 return MakeCXCursor(Def, TU);
6266 return clang_getNullCursor();
6268 case Decl::Function:
6269 case Decl::CXXMethod:
6270 case Decl::CXXConstructor:
6271 case Decl::CXXDestructor:
6272 case Decl::CXXConversion: {
6273 const FunctionDecl *Def = nullptr;
6274 if (cast<FunctionDecl>(D)->getBody(Def))
6275 return MakeCXCursor(Def, TU);
6276 return clang_getNullCursor();
6280 case Decl::VarTemplateSpecialization:
6281 case Decl::VarTemplatePartialSpecialization:
6282 case Decl::Decomposition: {
6283 // Ask the variable if it has a definition.
6284 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
6285 return MakeCXCursor(Def, TU);
6286 return clang_getNullCursor();
6289 case Decl::FunctionTemplate: {
6290 const FunctionDecl *Def = nullptr;
6291 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6292 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6293 return clang_getNullCursor();
6296 case Decl::ClassTemplate: {
6297 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6299 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6301 return clang_getNullCursor();
6304 case Decl::VarTemplate: {
6306 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6307 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6308 return clang_getNullCursor();
6312 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6313 D->getLocation(), TU);
6315 case Decl::UsingShadow:
6316 case Decl::ConstructorUsingShadow:
6317 return clang_getCursorDefinition(
6318 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6321 case Decl::ObjCMethod: {
6322 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
6323 if (Method->isThisDeclarationADefinition())
6326 // Dig out the method definition in the associated
6327 // @implementation, if we have it.
6328 // FIXME: The ASTs should make finding the definition easier.
6329 if (const ObjCInterfaceDecl *Class
6330 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6331 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6332 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6333 Method->isInstanceMethod()))
6334 if (Def->isThisDeclarationADefinition())
6335 return MakeCXCursor(Def, TU);
6337 return clang_getNullCursor();
6340 case Decl::ObjCCategory:
6341 if (ObjCCategoryImplDecl *Impl
6342 = cast<ObjCCategoryDecl>(D)->getImplementation())
6343 return MakeCXCursor(Impl, TU);
6344 return clang_getNullCursor();
6346 case Decl::ObjCProtocol:
6347 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
6348 return MakeCXCursor(Def, TU);
6349 return clang_getNullCursor();
6351 case Decl::ObjCInterface: {
6352 // There are two notions of a "definition" for an Objective-C
6353 // class: the interface and its implementation. When we resolved a
6354 // reference to an Objective-C class, produce the @interface as
6355 // the definition; when we were provided with the interface,
6356 // produce the @implementation as the definition.
6357 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
6359 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
6360 return MakeCXCursor(Def, TU);
6361 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6362 return MakeCXCursor(Impl, TU);
6363 return clang_getNullCursor();
6366 case Decl::ObjCProperty:
6367 // FIXME: We don't really know where to find the
6368 // ObjCPropertyImplDecls that implement this property.
6369 return clang_getNullCursor();
6371 case Decl::ObjCCompatibleAlias:
6372 if (const ObjCInterfaceDecl *Class
6373 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
6374 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6375 return MakeCXCursor(Def, TU);
6377 return clang_getNullCursor();
6380 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6381 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6382 return clang_getNullCursor();
6384 case Decl::FriendTemplate:
6385 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6386 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6387 return clang_getNullCursor();
6390 return clang_getNullCursor();
6393 unsigned clang_isCursorDefinition(CXCursor C) {
6394 if (!clang_isDeclaration(C.kind))
6397 return clang_getCursorDefinition(C) == C;
6400 CXCursor clang_getCanonicalCursor(CXCursor C) {
6401 if (!clang_isDeclaration(C.kind))
6404 if (const Decl *D = getCursorDecl(C)) {
6405 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
6406 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6407 return MakeCXCursor(CatD, getCursorTU(C));
6409 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6410 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
6411 return MakeCXCursor(IFD, getCursorTU(C));
6413 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6419 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6420 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6423 unsigned clang_getNumOverloadedDecls(CXCursor C) {
6424 if (C.kind != CXCursor_OverloadedDeclRef)
6427 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
6428 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6429 return E->getNumDecls();
6431 if (OverloadedTemplateStorage *S
6432 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6435 const Decl *D = Storage.get<const Decl *>();
6436 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6437 return Using->shadow_size();
6442 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6443 if (cursor.kind != CXCursor_OverloadedDeclRef)
6444 return clang_getNullCursor();
6446 if (index >= clang_getNumOverloadedDecls(cursor))
6447 return clang_getNullCursor();
6449 CXTranslationUnit TU = getCursorTU(cursor);
6450 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
6451 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6452 return MakeCXCursor(E->decls_begin()[index], TU);
6454 if (OverloadedTemplateStorage *S
6455 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6456 return MakeCXCursor(S->begin()[index], TU);
6458 const Decl *D = Storage.get<const Decl *>();
6459 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
6460 // FIXME: This is, unfortunately, linear time.
6461 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6462 std::advance(Pos, index);
6463 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6466 return clang_getNullCursor();
6469 void clang_getDefinitionSpellingAndExtent(CXCursor C,
6470 const char **startBuf,
6471 const char **endBuf,
6472 unsigned *startLine,
6473 unsigned *startColumn,
6475 unsigned *endColumn) {
6476 assert(getCursorDecl(C) && "CXCursor has null decl");
6477 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
6478 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6480 SourceManager &SM = FD->getASTContext().getSourceManager();
6481 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6482 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6483 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6484 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6485 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6486 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6490 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6491 unsigned PieceIndex) {
6492 RefNamePieces Pieces;
6495 case CXCursor_MemberRefExpr:
6496 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
6497 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6498 E->getQualifierLoc().getSourceRange());
6501 case CXCursor_DeclRefExpr:
6502 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6503 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6505 buildPieces(NameFlags, false, E->getNameInfo(),
6506 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6510 case CXCursor_CallExpr:
6511 if (const CXXOperatorCallExpr *OCE =
6512 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
6513 const Expr *Callee = OCE->getCallee();
6514 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
6515 Callee = ICE->getSubExpr();
6517 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
6518 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6519 DRE->getQualifierLoc().getSourceRange());
6527 if (Pieces.empty()) {
6528 if (PieceIndex == 0)
6529 return clang_getCursorExtent(C);
6530 } else if (PieceIndex < Pieces.size()) {
6531 SourceRange R = Pieces[PieceIndex];
6533 return cxloc::translateSourceRange(getCursorContext(C), R);
6536 return clang_getNullRange();
6539 void clang_enableStackTraces(void) {
6540 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6541 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
6544 void clang_executeOnThread(void (*fn)(void*), void *user_data,
6545 unsigned stack_size) {
6546 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6549 //===----------------------------------------------------------------------===//
6550 // Token-based Operations.
6551 //===----------------------------------------------------------------------===//
6554 * int_data[0]: a CXTokenKind
6555 * int_data[1]: starting token location
6556 * int_data[2]: token length
6557 * int_data[3]: reserved
6558 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6561 CXTokenKind clang_getTokenKind(CXToken CXTok) {
6562 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6565 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6566 switch (clang_getTokenKind(CXTok)) {
6567 case CXToken_Identifier:
6568 case CXToken_Keyword:
6569 // We know we have an IdentifierInfo*, so use that.
6570 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
6573 case CXToken_Literal: {
6574 // We have stashed the starting pointer in the ptr_data field. Use it.
6575 const char *Text = static_cast<const char *>(CXTok.ptr_data);
6576 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
6579 case CXToken_Punctuation:
6580 case CXToken_Comment:
6584 if (isNotUsableTU(TU)) {
6586 return cxstring::createEmpty();
6589 // We have to find the starting buffer pointer the hard way, by
6590 // deconstructing the source location.
6591 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6593 return cxstring::createEmpty();
6595 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6596 std::pair<FileID, unsigned> LocInfo
6597 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6598 bool Invalid = false;
6600 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6602 return cxstring::createEmpty();
6604 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
6607 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
6608 if (isNotUsableTU(TU)) {
6610 return clang_getNullLocation();
6613 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6615 return clang_getNullLocation();
6617 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6618 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6621 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
6622 if (isNotUsableTU(TU)) {
6624 return clang_getNullRange();
6627 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6629 return clang_getNullRange();
6631 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6632 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6635 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6636 SmallVectorImpl<CXToken> &CXTokens) {
6637 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6638 std::pair<FileID, unsigned> BeginLocInfo
6639 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
6640 std::pair<FileID, unsigned> EndLocInfo
6641 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
6643 // Cannot tokenize across files.
6644 if (BeginLocInfo.first != EndLocInfo.first)
6648 bool Invalid = false;
6650 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6654 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6655 CXXUnit->getASTContext().getLangOpts(),
6656 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6657 Lex.SetCommentRetentionState(true);
6659 // Lex tokens until we hit the end of the range.
6660 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6662 bool previousWasAt = false;
6664 // Lex the next token
6665 Lex.LexFromRawLexer(Tok);
6666 if (Tok.is(tok::eof))
6669 // Initialize the CXToken.
6673 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6674 CXTok.int_data[2] = Tok.getLength();
6675 CXTok.int_data[3] = 0;
6677 // - Kind-specific fields
6678 if (Tok.isLiteral()) {
6679 CXTok.int_data[0] = CXToken_Literal;
6680 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6681 } else if (Tok.is(tok::raw_identifier)) {
6682 // Lookup the identifier to determine whether we have a keyword.
6684 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6686 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6687 CXTok.int_data[0] = CXToken_Keyword;
6690 CXTok.int_data[0] = Tok.is(tok::identifier)
6691 ? CXToken_Identifier
6694 CXTok.ptr_data = II;
6695 } else if (Tok.is(tok::comment)) {
6696 CXTok.int_data[0] = CXToken_Comment;
6697 CXTok.ptr_data = nullptr;
6699 CXTok.int_data[0] = CXToken_Punctuation;
6700 CXTok.ptr_data = nullptr;
6702 CXTokens.push_back(CXTok);
6703 previousWasAt = Tok.is(tok::at);
6704 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
6707 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6709 *Log << TU << ' ' << Location;
6712 if (isNotUsableTU(TU)) {
6717 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6721 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6722 if (Begin.isInvalid())
6724 SourceManager &SM = CXXUnit->getSourceManager();
6725 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6726 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6728 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6730 SmallVector<CXToken, 32> CXTokens;
6731 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6733 if (CXTokens.empty())
6737 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6739 memmove(Token, CXTokens.data(), sizeof(CXToken));
6743 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6744 CXToken **Tokens, unsigned *NumTokens) {
6746 *Log << TU << ' ' << Range;
6754 if (isNotUsableTU(TU)) {
6759 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6760 if (!CXXUnit || !Tokens || !NumTokens)
6763 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6765 SourceRange R = cxloc::translateCXSourceRange(Range);
6769 SmallVector<CXToken, 32> CXTokens;
6770 getTokens(CXXUnit, R, CXTokens);
6772 if (CXTokens.empty())
6775 *Tokens = static_cast<CXToken *>(
6776 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
6777 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6778 *NumTokens = CXTokens.size();
6781 void clang_disposeTokens(CXTranslationUnit TU,
6782 CXToken *Tokens, unsigned NumTokens) {
6786 //===----------------------------------------------------------------------===//
6787 // Token annotation APIs.
6788 //===----------------------------------------------------------------------===//
6790 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6792 CXClientData client_data);
6793 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6794 CXClientData client_data);
6797 class AnnotateTokensWorker {
6802 unsigned PreprocessingTokIdx;
6803 CursorVisitor AnnotateVis;
6804 SourceManager &SrcMgr;
6805 bool HasContextSensitiveKeywords;
6807 struct PostChildrenAction {
6809 enum Action { Invalid, Ignore, Postpone } action;
6811 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6813 struct PostChildrenInfo {
6815 SourceRange CursorRange;
6816 unsigned BeforeReachingCursorIdx;
6817 unsigned BeforeChildrenTokenIdx;
6818 PostChildrenActions ChildActions;
6820 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
6822 CXToken &getTok(unsigned Idx) {
6823 assert(Idx < NumTokens);
6826 const CXToken &getTok(unsigned Idx) const {
6827 assert(Idx < NumTokens);
6830 bool MoreTokens() const { return TokIdx < NumTokens; }
6831 unsigned NextToken() const { return TokIdx; }
6832 void AdvanceToken() { ++TokIdx; }
6833 SourceLocation GetTokenLoc(unsigned tokI) {
6834 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6836 bool isFunctionMacroToken(unsigned tokI) const {
6837 return getTok(tokI).int_data[3] != 0;
6839 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
6840 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6843 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
6844 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
6848 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
6849 CXTranslationUnit TU, SourceRange RegionOfInterest)
6850 : Tokens(tokens), Cursors(cursors),
6851 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6853 AnnotateTokensVisitor, this,
6854 /*VisitPreprocessorLast=*/true,
6855 /*VisitIncludedEntities=*/false,
6857 /*VisitDeclsOnly=*/false,
6858 AnnotateTokensPostChildrenVisitor),
6859 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6860 HasContextSensitiveKeywords(false) { }
6862 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6863 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6864 bool IsIgnoredChildCursor(CXCursor cursor) const;
6865 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6867 bool postVisitChildren(CXCursor cursor);
6868 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6869 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6871 void AnnotateTokens();
6873 /// Determine whether the annotator saw any cursors that have
6874 /// context-sensitive keywords.
6875 bool hasContextSensitiveKeywords() const {
6876 return HasContextSensitiveKeywords;
6879 ~AnnotateTokensWorker() {
6880 assert(PostChildrenInfos.empty());
6885 void AnnotateTokensWorker::AnnotateTokens() {
6886 // Walk the AST within the region of interest, annotating tokens
6888 AnnotateVis.visitFileRegion();
6891 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6892 if (PostChildrenInfos.empty())
6895 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6896 if (ChildAction.cursor == cursor &&
6897 ChildAction.action == PostChildrenAction::Ignore) {
6905 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6906 if (!clang_isExpression(Cursor.kind))
6909 const Expr *E = getCursorExpr(Cursor);
6910 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6911 const OverloadedOperatorKind Kind = OCE->getOperator();
6912 if (Kind == OO_Call || Kind == OO_Subscript)
6919 AnnotateTokensWorker::PostChildrenActions
6920 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6921 PostChildrenActions actions;
6923 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6924 // visited before the arguments to the operator call. For the Call and
6925 // Subscript operator the range of this DeclRefExpr includes the whole call
6926 // expression, so that all tokens in that range would be mapped to the
6927 // operator function, including the tokens of the arguments. To avoid that,
6928 // ensure to visit this DeclRefExpr as last node.
6929 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6930 const Expr *Callee = OCE->getCallee();
6931 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6932 const Expr *SubExpr = ICE->getSubExpr();
6933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6934 const Decl *parentDecl = getCursorDecl(Cursor);
6935 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6937 // Visit the DeclRefExpr as last.
6938 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6939 actions.push_back({cxChild, PostChildrenAction::Postpone});
6941 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6942 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6943 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6944 actions.push_back({cxChild, PostChildrenAction::Ignore});
6952 static inline void updateCursorAnnotation(CXCursor &Cursor,
6953 const CXCursor &updateC) {
6954 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6959 /// It annotates and advances tokens with a cursor until the comparison
6960 //// between the cursor location and the source range is the same as
6961 /// \arg compResult.
6963 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6964 /// Pass RangeOverlap to annotate tokens inside a range.
6965 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6966 RangeComparisonResult compResult,
6967 SourceRange range) {
6968 while (MoreTokens()) {
6969 const unsigned I = NextToken();
6970 if (isFunctionMacroToken(I))
6971 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6974 SourceLocation TokLoc = GetTokenLoc(I);
6975 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6976 updateCursorAnnotation(Cursors[I], updateC);
6984 /// Special annotation handling for macro argument tokens.
6985 /// \returns true if it advanced beyond all macro tokens, false otherwise.
6986 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
6988 RangeComparisonResult compResult,
6989 SourceRange range) {
6990 assert(MoreTokens());
6991 assert(isFunctionMacroToken(NextToken()) &&
6992 "Should be called only for macro arg tokens");
6994 // This works differently than annotateAndAdvanceTokens; because expanded
6995 // macro arguments can have arbitrary translation-unit source order, we do not
6996 // advance the token index one by one until a token fails the range test.
6997 // We only advance once past all of the macro arg tokens if all of them
6998 // pass the range test. If one of them fails we keep the token index pointing
6999 // at the start of the macro arg tokens so that the failing token will be
7000 // annotated by a subsequent annotation try.
7002 bool atLeastOneCompFail = false;
7004 unsigned I = NextToken();
7005 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7006 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7007 if (TokLoc.isFileID())
7008 continue; // not macro arg token, it's parens or comma.
7009 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7010 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7011 Cursors[I] = updateC;
7013 atLeastOneCompFail = true;
7016 if (atLeastOneCompFail)
7019 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7023 enum CXChildVisitResult
7024 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
7025 SourceRange cursorRange = getRawCursorExtent(cursor);
7026 if (cursorRange.isInvalid())
7027 return CXChildVisit_Recurse;
7029 if (IsIgnoredChildCursor(cursor))
7030 return CXChildVisit_Continue;
7032 if (!HasContextSensitiveKeywords) {
7033 // Objective-C properties can have context-sensitive keywords.
7034 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
7035 if (const ObjCPropertyDecl *Property
7036 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7037 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7039 // Objective-C methods can have context-sensitive keywords.
7040 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7041 cursor.kind == CXCursor_ObjCClassMethodDecl) {
7042 if (const ObjCMethodDecl *Method
7043 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7044 if (Method->getObjCDeclQualifier())
7045 HasContextSensitiveKeywords = true;
7047 for (const auto *P : Method->parameters()) {
7048 if (P->getObjCDeclQualifier()) {
7049 HasContextSensitiveKeywords = true;
7056 // C++ methods can have context-sensitive keywords.
7057 else if (cursor.kind == CXCursor_CXXMethod) {
7058 if (const CXXMethodDecl *Method
7059 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7060 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7061 HasContextSensitiveKeywords = true;
7064 // C++ classes can have context-sensitive keywords.
7065 else if (cursor.kind == CXCursor_StructDecl ||
7066 cursor.kind == CXCursor_ClassDecl ||
7067 cursor.kind == CXCursor_ClassTemplate ||
7068 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
7069 if (const Decl *D = getCursorDecl(cursor))
7070 if (D->hasAttr<FinalAttr>())
7071 HasContextSensitiveKeywords = true;
7075 // Don't override a property annotation with its getter/setter method.
7076 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7077 parent.kind == CXCursor_ObjCPropertyDecl)
7078 return CXChildVisit_Continue;
7080 if (clang_isPreprocessing(cursor.kind)) {
7081 // Items in the preprocessing record are kept separate from items in
7082 // declarations, so we keep a separate token index.
7083 unsigned SavedTokIdx = TokIdx;
7084 TokIdx = PreprocessingTokIdx;
7086 // Skip tokens up until we catch up to the beginning of the preprocessing
7088 while (MoreTokens()) {
7089 const unsigned I = NextToken();
7090 SourceLocation TokLoc = GetTokenLoc(I);
7091 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7102 // Look at all of the tokens within this range.
7103 while (MoreTokens()) {
7104 const unsigned I = NextToken();
7105 SourceLocation TokLoc = GetTokenLoc(I);
7106 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7108 llvm_unreachable("Infeasible");
7112 // For macro expansions, just note where the beginning of the macro
7113 // expansion occurs.
7114 if (cursor.kind == CXCursor_MacroExpansion) {
7115 if (TokLoc == cursorRange.getBegin())
7116 Cursors[I] = cursor;
7120 // We may have already annotated macro names inside macro definitions.
7121 if (Cursors[I].kind != CXCursor_MacroExpansion)
7122 Cursors[I] = cursor;
7129 // Save the preprocessing token index; restore the non-preprocessing
7131 PreprocessingTokIdx = TokIdx;
7132 TokIdx = SavedTokIdx;
7133 return CXChildVisit_Recurse;
7136 if (cursorRange.isInvalid())
7137 return CXChildVisit_Continue;
7139 unsigned BeforeReachingCursorIdx = NextToken();
7140 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
7141 const enum CXCursorKind K = clang_getCursorKind(parent);
7142 const CXCursor updateC =
7143 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7144 // Attributes are annotated out-of-order, skip tokens until we reach it.
7145 clang_isAttribute(cursor.kind))
7146 ? clang_getNullCursor() : parent;
7148 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7150 // Avoid having the cursor of an expression "overwrite" the annotation of the
7151 // variable declaration that it belongs to.
7152 // This can happen for C++ constructor expressions whose range generally
7153 // include the variable declaration, e.g.:
7154 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
7155 if (clang_isExpression(cursorK) && MoreTokens()) {
7156 const Expr *E = getCursorExpr(cursor);
7157 if (const Decl *D = getCursorDecl(cursor)) {
7158 const unsigned I = NextToken();
7159 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7160 E->getBeginLoc() == D->getLocation() &&
7161 E->getBeginLoc() == GetTokenLoc(I)) {
7162 updateCursorAnnotation(Cursors[I], updateC);
7168 // Before recursing into the children keep some state that we are going
7169 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7170 // extra work after the child nodes are visited.
7171 // Note that we don't call VisitChildren here to avoid traversing statements
7172 // code-recursively which can blow the stack.
7174 PostChildrenInfo Info;
7175 Info.Cursor = cursor;
7176 Info.CursorRange = cursorRange;
7177 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
7178 Info.BeforeChildrenTokenIdx = NextToken();
7179 Info.ChildActions = DetermineChildActions(cursor);
7180 PostChildrenInfos.push_back(Info);
7182 return CXChildVisit_Recurse;
7185 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7186 if (PostChildrenInfos.empty())
7188 const PostChildrenInfo &Info = PostChildrenInfos.back();
7189 if (!clang_equalCursors(Info.Cursor, cursor))
7192 HandlePostPonedChildCursors(Info);
7194 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7195 const unsigned AfterChildren = NextToken();
7196 SourceRange cursorRange = Info.CursorRange;
7198 // Scan the tokens that are at the end of the cursor, but are not captured
7199 // but the child cursors.
7200 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7202 // Scan the tokens that are at the beginning of the cursor, but are not
7203 // capture by the child cursors.
7204 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7205 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7208 Cursors[I] = cursor;
7211 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7212 // encountered the attribute cursor.
7213 if (clang_isAttribute(cursor.kind))
7214 TokIdx = Info.BeforeReachingCursorIdx;
7216 PostChildrenInfos.pop_back();
7220 void AnnotateTokensWorker::HandlePostPonedChildCursors(
7221 const PostChildrenInfo &Info) {
7222 for (const auto &ChildAction : Info.ChildActions) {
7223 if (ChildAction.action == PostChildrenAction::Postpone) {
7224 HandlePostPonedChildCursor(ChildAction.cursor,
7225 Info.BeforeChildrenTokenIdx);
7230 void AnnotateTokensWorker::HandlePostPonedChildCursor(
7231 CXCursor Cursor, unsigned StartTokenIndex) {
7232 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7233 unsigned I = StartTokenIndex;
7235 // The bracket tokens of a Call or Subscript operator are mapped to
7236 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7237 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7238 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7239 const CXSourceRange CXRefNameRange =
7240 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7241 if (clang_Range_isNull(CXRefNameRange))
7242 break; // All ranges handled.
7244 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7245 while (I < NumTokens) {
7246 const SourceLocation TokenLocation = GetTokenLoc(I);
7247 if (!TokenLocation.isValid())
7250 // Adapt the end range, because LocationCompare() reports
7251 // RangeOverlap even for the not-inclusive end location.
7252 const SourceLocation fixedEnd =
7253 RefNameRange.getEnd().getLocWithOffset(-1);
7254 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7256 const RangeComparisonResult ComparisonResult =
7257 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7259 if (ComparisonResult == RangeOverlap) {
7260 Cursors[I++] = Cursor;
7261 } else if (ComparisonResult == RangeBefore) {
7262 ++I; // Not relevant token, check next one.
7263 } else if (ComparisonResult == RangeAfter) {
7264 break; // All tokens updated for current range, check next.
7270 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7272 CXClientData client_data) {
7273 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7276 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7277 CXClientData client_data) {
7278 return static_cast<AnnotateTokensWorker*>(client_data)->
7279 postVisitChildren(cursor);
7284 /// Uses the macro expansions in the preprocessing record to find
7285 /// and mark tokens that are macro arguments. This info is used by the
7286 /// AnnotateTokensWorker.
7287 class MarkMacroArgTokensVisitor {
7294 MarkMacroArgTokensVisitor(SourceManager &SM,
7295 CXToken *tokens, unsigned numTokens)
7296 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7298 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7299 if (cursor.kind != CXCursor_MacroExpansion)
7300 return CXChildVisit_Continue;
7302 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
7303 if (macroRange.getBegin() == macroRange.getEnd())
7304 return CXChildVisit_Continue; // it's not a function macro.
7306 for (; CurIdx < NumTokens; ++CurIdx) {
7307 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7308 macroRange.getBegin()))
7312 if (CurIdx == NumTokens)
7313 return CXChildVisit_Break;
7315 for (; CurIdx < NumTokens; ++CurIdx) {
7316 SourceLocation tokLoc = getTokenLoc(CurIdx);
7317 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7320 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7323 if (CurIdx == NumTokens)
7324 return CXChildVisit_Break;
7326 return CXChildVisit_Continue;
7330 CXToken &getTok(unsigned Idx) {
7331 assert(Idx < NumTokens);
7334 const CXToken &getTok(unsigned Idx) const {
7335 assert(Idx < NumTokens);
7339 SourceLocation getTokenLoc(unsigned tokI) {
7340 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7343 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7344 // The third field is reserved and currently not used. Use it here
7345 // to mark macro arg expanded tokens with their expanded locations.
7346 getTok(tokI).int_data[3] = loc.getRawEncoding();
7350 } // end anonymous namespace
7352 static CXChildVisitResult
7353 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7354 CXClientData client_data) {
7355 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7359 /// Used by \c annotatePreprocessorTokens.
7360 /// \returns true if lexing was finished, false otherwise.
7361 static bool lexNext(Lexer &Lex, Token &Tok,
7362 unsigned &NextIdx, unsigned NumTokens) {
7363 if (NextIdx >= NumTokens)
7367 Lex.LexFromRawLexer(Tok);
7368 return Tok.is(tok::eof);
7371 static void annotatePreprocessorTokens(CXTranslationUnit TU,
7372 SourceRange RegionOfInterest,
7375 unsigned NumTokens) {
7376 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7378 Preprocessor &PP = CXXUnit->getPreprocessor();
7379 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7380 std::pair<FileID, unsigned> BeginLocInfo
7381 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
7382 std::pair<FileID, unsigned> EndLocInfo
7383 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
7385 if (BeginLocInfo.first != EndLocInfo.first)
7389 bool Invalid = false;
7390 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7391 if (Buffer.empty() || Invalid)
7394 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7395 CXXUnit->getASTContext().getLangOpts(),
7396 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7398 Lex.SetCommentRetentionState(true);
7400 unsigned NextIdx = 0;
7401 // Lex tokens in raw mode until we hit the end of the range, to avoid
7402 // entering #includes or expanding macros.
7405 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7407 unsigned TokIdx = NextIdx-1;
7408 assert(Tok.getLocation() ==
7409 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
7412 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
7413 // We have found a preprocessing directive. Annotate the tokens
7416 // FIXME: Some simple tests here could identify macro definitions and
7417 // #undefs, to provide specific cursor kinds for those.
7419 SourceLocation BeginLoc = Tok.getLocation();
7420 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7423 MacroInfo *MI = nullptr;
7424 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
7425 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7428 if (Tok.is(tok::raw_identifier)) {
7429 IdentifierInfo &II =
7430 PP.getIdentifierTable().get(Tok.getRawIdentifier());
7431 SourceLocation MappedTokLoc =
7432 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7433 MI = getMacroInfo(II, MappedTokLoc, TU);
7437 bool finished = false;
7439 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7443 // If we are in a macro definition, check if the token was ever a
7444 // macro name and annotate it if that's the case.
7446 SourceLocation SaveLoc = Tok.getLocation();
7447 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
7448 MacroDefinitionRecord *MacroDef =
7449 checkForMacroInMacroDefinition(MI, Tok, TU);
7450 Tok.setLocation(SaveLoc);
7452 Cursors[NextIdx - 1] =
7453 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
7455 } while (!Tok.isAtStartOfLine());
7457 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7458 assert(TokIdx <= LastIdx);
7459 SourceLocation EndLoc =
7460 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7462 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7464 for (; TokIdx <= LastIdx; ++TokIdx)
7465 updateCursorAnnotation(Cursors[TokIdx], Cursor);
7474 // This gets run a separate thread to avoid stack blowout.
7475 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7476 CXToken *Tokens, unsigned NumTokens,
7477 CXCursor *Cursors) {
7478 CIndexer *CXXIdx = TU->CIdx;
7479 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7480 setThreadBackgroundPriority();
7482 // Determine the region of interest, which contains all of the tokens.
7483 SourceRange RegionOfInterest;
7484 RegionOfInterest.setBegin(
7485 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7486 RegionOfInterest.setEnd(
7487 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7488 Tokens[NumTokens-1])));
7490 // Relex the tokens within the source range to look for preprocessing
7492 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
7494 // If begin location points inside a macro argument, set it to the expansion
7495 // location so we can have the full context when annotating semantically.
7497 SourceManager &SM = CXXUnit->getSourceManager();
7498 SourceLocation Loc =
7499 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7500 if (Loc.isMacroID())
7501 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7504 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7505 // Search and mark tokens that are macro argument expansions.
7506 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7508 CursorVisitor MacroArgMarker(TU,
7509 MarkMacroArgTokensVisitorDelegate, &Visitor,
7510 /*VisitPreprocessorLast=*/true,
7511 /*VisitIncludedEntities=*/false,
7513 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7516 // Annotate all of the source locations in the region of interest that map to
7517 // a specific cursor.
7518 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
7520 // FIXME: We use a ridiculous stack size here because the data-recursion
7521 // algorithm uses a large stack frame than the non-data recursive version,
7522 // and AnnotationTokensWorker currently transforms the data-recursion
7523 // algorithm back into a traditional recursion by explicitly calling
7524 // VisitChildren(). We will need to remove this explicit recursive call.
7527 // If we ran into any entities that involve context-sensitive keywords,
7528 // take another pass through the tokens to mark them as such.
7529 if (W.hasContextSensitiveKeywords()) {
7530 for (unsigned I = 0; I != NumTokens; ++I) {
7531 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7534 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7535 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7536 if (const ObjCPropertyDecl *Property
7537 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7538 if (Property->getPropertyAttributesAsWritten() != 0 &&
7539 llvm::StringSwitch<bool>(II->getName())
7540 .Case("readonly", true)
7541 .Case("assign", true)
7542 .Case("unsafe_unretained", true)
7543 .Case("readwrite", true)
7544 .Case("retain", true)
7546 .Case("nonatomic", true)
7547 .Case("atomic", true)
7548 .Case("getter", true)
7549 .Case("setter", true)
7550 .Case("strong", true)
7552 .Case("class", true)
7554 Tokens[I].int_data[0] = CXToken_Keyword;
7559 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7560 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7561 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7562 if (llvm::StringSwitch<bool>(II->getName())
7565 .Case("inout", true)
7566 .Case("oneway", true)
7567 .Case("bycopy", true)
7568 .Case("byref", true)
7570 Tokens[I].int_data[0] = CXToken_Keyword;
7574 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7575 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7576 Tokens[I].int_data[0] = CXToken_Keyword;
7583 void clang_annotateTokens(CXTranslationUnit TU,
7584 CXToken *Tokens, unsigned NumTokens,
7585 CXCursor *Cursors) {
7586 if (isNotUsableTU(TU)) {
7590 if (NumTokens == 0 || !Tokens || !Cursors) {
7591 LOG_FUNC_SECTION { *Log << "<null input>"; }
7597 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7598 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7599 *Log << clang_getRange(bloc, eloc);
7602 // Any token we don't specifically annotate will have a NULL cursor.
7603 CXCursor C = clang_getNullCursor();
7604 for (unsigned I = 0; I != NumTokens; ++I)
7607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7613 auto AnnotateTokensImpl = [=]() {
7614 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7616 llvm::CrashRecoveryContext CRC;
7617 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
7618 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7622 //===----------------------------------------------------------------------===//
7623 // Operations for querying linkage of a cursor.
7624 //===----------------------------------------------------------------------===//
7626 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7627 if (!clang_isDeclaration(cursor.kind))
7628 return CXLinkage_Invalid;
7630 const Decl *D = cxcursor::getCursorDecl(cursor);
7631 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7632 switch (ND->getLinkageInternal()) {
7634 case VisibleNoLinkage: return CXLinkage_NoLinkage;
7635 case ModuleInternalLinkage:
7636 case InternalLinkage: return CXLinkage_Internal;
7637 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7639 case ExternalLinkage: return CXLinkage_External;
7642 return CXLinkage_Invalid;
7645 //===----------------------------------------------------------------------===//
7646 // Operations for querying visibility of a cursor.
7647 //===----------------------------------------------------------------------===//
7649 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7650 if (!clang_isDeclaration(cursor.kind))
7651 return CXVisibility_Invalid;
7653 const Decl *D = cxcursor::getCursorDecl(cursor);
7654 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7655 switch (ND->getVisibility()) {
7656 case HiddenVisibility: return CXVisibility_Hidden;
7657 case ProtectedVisibility: return CXVisibility_Protected;
7658 case DefaultVisibility: return CXVisibility_Default;
7661 return CXVisibility_Invalid;
7664 //===----------------------------------------------------------------------===//
7665 // Operations for querying language of a cursor.
7666 //===----------------------------------------------------------------------===//
7668 static CXLanguageKind getDeclLanguage(const Decl *D) {
7670 return CXLanguage_C;
7672 switch (D->getKind()) {
7675 case Decl::ImplicitParam:
7676 case Decl::ObjCAtDefsField:
7677 case Decl::ObjCCategory:
7678 case Decl::ObjCCategoryImpl:
7679 case Decl::ObjCCompatibleAlias:
7680 case Decl::ObjCImplementation:
7681 case Decl::ObjCInterface:
7682 case Decl::ObjCIvar:
7683 case Decl::ObjCMethod:
7684 case Decl::ObjCProperty:
7685 case Decl::ObjCPropertyImpl:
7686 case Decl::ObjCProtocol:
7687 case Decl::ObjCTypeParam:
7688 return CXLanguage_ObjC;
7689 case Decl::CXXConstructor:
7690 case Decl::CXXConversion:
7691 case Decl::CXXDestructor:
7692 case Decl::CXXMethod:
7693 case Decl::CXXRecord:
7694 case Decl::ClassTemplate:
7695 case Decl::ClassTemplatePartialSpecialization:
7696 case Decl::ClassTemplateSpecialization:
7698 case Decl::FriendTemplate:
7699 case Decl::FunctionTemplate:
7700 case Decl::LinkageSpec:
7701 case Decl::Namespace:
7702 case Decl::NamespaceAlias:
7703 case Decl::NonTypeTemplateParm:
7704 case Decl::StaticAssert:
7705 case Decl::TemplateTemplateParm:
7706 case Decl::TemplateTypeParm:
7707 case Decl::UnresolvedUsingTypename:
7708 case Decl::UnresolvedUsingValue:
7710 case Decl::UsingDirective:
7711 case Decl::UsingShadow:
7712 return CXLanguage_CPlusPlus;
7715 return CXLanguage_C;
7718 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7719 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
7720 return CXAvailability_NotAvailable;
7722 switch (D->getAvailability()) {
7724 case AR_NotYetIntroduced:
7725 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7726 return getCursorAvailabilityForDecl(
7727 cast<Decl>(EnumConst->getDeclContext()));
7728 return CXAvailability_Available;
7731 return CXAvailability_Deprecated;
7733 case AR_Unavailable:
7734 return CXAvailability_NotAvailable;
7737 llvm_unreachable("Unknown availability kind!");
7740 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7741 if (clang_isDeclaration(cursor.kind))
7742 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7743 return getCursorAvailabilityForDecl(D);
7745 return CXAvailability_Available;
7748 static CXVersion convertVersion(VersionTuple In) {
7749 CXVersion Out = { -1, -1, -1 };
7753 Out.Major = In.getMajor();
7755 Optional<unsigned> Minor = In.getMinor();
7756 if (Minor.hasValue())
7761 Optional<unsigned> Subminor = In.getSubminor();
7762 if (Subminor.hasValue())
7763 Out.Subminor = *Subminor;
7768 static void getCursorPlatformAvailabilityForDecl(
7769 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7770 int *always_unavailable, CXString *unavailable_message,
7771 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
7772 bool HadAvailAttr = false;
7773 for (auto A : D->attrs()) {
7774 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
7775 HadAvailAttr = true;
7776 if (always_deprecated)
7777 *always_deprecated = 1;
7778 if (deprecated_message) {
7779 clang_disposeString(*deprecated_message);
7780 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
7785 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
7786 HadAvailAttr = true;
7787 if (always_unavailable)
7788 *always_unavailable = 1;
7789 if (unavailable_message) {
7790 clang_disposeString(*unavailable_message);
7791 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7796 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
7797 AvailabilityAttrs.push_back(Avail);
7798 HadAvailAttr = true;
7803 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7804 return getCursorPlatformAvailabilityForDecl(
7805 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7806 deprecated_message, always_unavailable, unavailable_message,
7809 if (AvailabilityAttrs.empty())
7812 llvm::sort(AvailabilityAttrs,
7813 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7814 return LHS->getPlatform()->getName() <
7815 RHS->getPlatform()->getName();
7817 ASTContext &Ctx = D->getASTContext();
7818 auto It = std::unique(
7819 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7820 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7821 if (LHS->getPlatform() != RHS->getPlatform())
7824 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7825 LHS->getDeprecated() == RHS->getDeprecated() &&
7826 LHS->getObsoleted() == RHS->getObsoleted() &&
7827 LHS->getMessage() == RHS->getMessage() &&
7828 LHS->getReplacement() == RHS->getReplacement())
7831 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7832 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7833 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7836 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7837 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7839 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7840 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7841 if (LHS->getMessage().empty())
7842 LHS->setMessage(Ctx, RHS->getMessage());
7843 if (LHS->getReplacement().empty())
7844 LHS->setReplacement(Ctx, RHS->getReplacement());
7847 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7848 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7849 if (LHS->getMessage().empty())
7850 LHS->setMessage(Ctx, RHS->getMessage());
7851 if (LHS->getReplacement().empty())
7852 LHS->setReplacement(Ctx, RHS->getReplacement());
7857 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
7860 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
7861 CXString *deprecated_message,
7862 int *always_unavailable,
7863 CXString *unavailable_message,
7864 CXPlatformAvailability *availability,
7865 int availability_size) {
7866 if (always_deprecated)
7867 *always_deprecated = 0;
7868 if (deprecated_message)
7869 *deprecated_message = cxstring::createEmpty();
7870 if (always_unavailable)
7871 *always_unavailable = 0;
7872 if (unavailable_message)
7873 *unavailable_message = cxstring::createEmpty();
7875 if (!clang_isDeclaration(cursor.kind))
7878 const Decl *D = cxcursor::getCursorDecl(cursor);
7882 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7883 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7884 always_unavailable, unavailable_message,
7886 for (const auto &Avail :
7887 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7888 .take_front(availability_size))) {
7889 availability[Avail.index()].Platform =
7890 cxstring::createDup(Avail.value()->getPlatform()->getName());
7891 availability[Avail.index()].Introduced =
7892 convertVersion(Avail.value()->getIntroduced());
7893 availability[Avail.index()].Deprecated =
7894 convertVersion(Avail.value()->getDeprecated());
7895 availability[Avail.index()].Obsoleted =
7896 convertVersion(Avail.value()->getObsoleted());
7897 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7898 availability[Avail.index()].Message =
7899 cxstring::createDup(Avail.value()->getMessage());
7902 return AvailabilityAttrs.size();
7905 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7906 clang_disposeString(availability->Platform);
7907 clang_disposeString(availability->Message);
7910 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7911 if (clang_isDeclaration(cursor.kind))
7912 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7914 return CXLanguage_Invalid;
7917 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7918 const Decl *D = cxcursor::getCursorDecl(cursor);
7919 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7920 switch (VD->getTLSKind()) {
7921 case VarDecl::TLS_None:
7923 case VarDecl::TLS_Dynamic:
7924 return CXTLS_Dynamic;
7925 case VarDecl::TLS_Static:
7926 return CXTLS_Static;
7933 /// If the given cursor is the "templated" declaration
7934 /// describing a class or function template, return the class or
7935 /// function template.
7936 static const Decl *maybeGetTemplateCursor(const Decl *D) {
7940 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7941 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7944 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7945 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7952 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7953 StorageClass sc = SC_None;
7954 const Decl *D = getCursorDecl(C);
7956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7957 sc = FD->getStorageClass();
7958 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7959 sc = VD->getStorageClass();
7961 return CX_SC_Invalid;
7964 return CX_SC_Invalid;
7970 return CX_SC_Extern;
7972 return CX_SC_Static;
7973 case SC_PrivateExtern:
7974 return CX_SC_PrivateExtern;
7978 return CX_SC_Register;
7980 llvm_unreachable("Unhandled storage class!");
7983 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7984 if (clang_isDeclaration(cursor.kind)) {
7985 if (const Decl *D = getCursorDecl(cursor)) {
7986 const DeclContext *DC = D->getDeclContext();
7988 return clang_getNullCursor();
7990 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7991 getCursorTU(cursor));
7995 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
7996 if (const Decl *D = getCursorDecl(cursor))
7997 return MakeCXCursor(D, getCursorTU(cursor));
8000 return clang_getNullCursor();
8003 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8004 if (clang_isDeclaration(cursor.kind)) {
8005 if (const Decl *D = getCursorDecl(cursor)) {
8006 const DeclContext *DC = D->getLexicalDeclContext();
8008 return clang_getNullCursor();
8010 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8011 getCursorTU(cursor));
8015 // FIXME: Note that we can't easily compute the lexical context of a
8016 // statement or expression, so we return nothing.
8017 return clang_getNullCursor();
8020 CXFile clang_getIncludedFile(CXCursor cursor) {
8021 if (cursor.kind != CXCursor_InclusionDirective)
8024 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
8025 return const_cast<FileEntry *>(ID->getFile());
8028 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8029 if (C.kind != CXCursor_ObjCPropertyDecl)
8030 return CXObjCPropertyAttr_noattr;
8032 unsigned Result = CXObjCPropertyAttr_noattr;
8033 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8034 ObjCPropertyDecl::PropertyAttributeKind Attr =
8035 PD->getPropertyAttributesAsWritten();
8037 #define SET_CXOBJCPROP_ATTR(A) \
8038 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8039 Result |= CXObjCPropertyAttr_##A
8040 SET_CXOBJCPROP_ATTR(readonly);
8041 SET_CXOBJCPROP_ATTR(getter);
8042 SET_CXOBJCPROP_ATTR(assign);
8043 SET_CXOBJCPROP_ATTR(readwrite);
8044 SET_CXOBJCPROP_ATTR(retain);
8045 SET_CXOBJCPROP_ATTR(copy);
8046 SET_CXOBJCPROP_ATTR(nonatomic);
8047 SET_CXOBJCPROP_ATTR(setter);
8048 SET_CXOBJCPROP_ATTR(atomic);
8049 SET_CXOBJCPROP_ATTR(weak);
8050 SET_CXOBJCPROP_ATTR(strong);
8051 SET_CXOBJCPROP_ATTR(unsafe_unretained);
8052 SET_CXOBJCPROP_ATTR(class);
8053 #undef SET_CXOBJCPROP_ATTR
8058 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8059 if (C.kind != CXCursor_ObjCPropertyDecl)
8060 return cxstring::createNull();
8062 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8063 Selector sel = PD->getGetterName();
8065 return cxstring::createNull();
8067 return cxstring::createDup(sel.getAsString());
8070 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8071 if (C.kind != CXCursor_ObjCPropertyDecl)
8072 return cxstring::createNull();
8074 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8075 Selector sel = PD->getSetterName();
8077 return cxstring::createNull();
8079 return cxstring::createDup(sel.getAsString());
8082 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8083 if (!clang_isDeclaration(C.kind))
8084 return CXObjCDeclQualifier_None;
8086 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8087 const Decl *D = getCursorDecl(C);
8088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8089 QT = MD->getObjCDeclQualifier();
8090 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8091 QT = PD->getObjCDeclQualifier();
8092 if (QT == Decl::OBJC_TQ_None)
8093 return CXObjCDeclQualifier_None;
8095 unsigned Result = CXObjCDeclQualifier_None;
8096 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8097 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8098 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8099 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8100 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8101 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8106 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8107 if (!clang_isDeclaration(C.kind))
8110 const Decl *D = getCursorDecl(C);
8111 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8112 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8113 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8114 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8119 unsigned clang_Cursor_isVariadic(CXCursor C) {
8120 if (!clang_isDeclaration(C.kind))
8123 const Decl *D = getCursorDecl(C);
8124 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8125 return FD->isVariadic();
8126 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8127 return MD->isVariadic();
8132 unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8133 CXString *language, CXString *definedIn,
8134 unsigned *isGenerated) {
8135 if (!clang_isDeclaration(C.kind))
8138 const Decl *D = getCursorDecl(C);
8140 if (auto *attr = D->getExternalSourceSymbolAttr()) {
8142 *language = cxstring::createDup(attr->getLanguage());
8144 *definedIn = cxstring::createDup(attr->getDefinedIn());
8146 *isGenerated = attr->getGeneratedDeclaration();
8152 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8153 if (!clang_isDeclaration(C.kind))
8154 return clang_getNullRange();
8156 const Decl *D = getCursorDecl(C);
8157 ASTContext &Context = getCursorContext(C);
8158 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8160 return clang_getNullRange();
8162 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8165 CXString clang_Cursor_getRawCommentText(CXCursor C) {
8166 if (!clang_isDeclaration(C.kind))
8167 return cxstring::createNull();
8169 const Decl *D = getCursorDecl(C);
8170 ASTContext &Context = getCursorContext(C);
8171 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8172 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8175 // Don't duplicate the string because RawText points directly into source
8177 return cxstring::createRef(RawText);
8180 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8181 if (!clang_isDeclaration(C.kind))
8182 return cxstring::createNull();
8184 const Decl *D = getCursorDecl(C);
8185 const ASTContext &Context = getCursorContext(C);
8186 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8189 StringRef BriefText = RC->getBriefText(Context);
8191 // Don't duplicate the string because RawComment ensures that this memory
8192 // will not go away.
8193 return cxstring::createRef(BriefText);
8196 return cxstring::createNull();
8199 CXModule clang_Cursor_getModule(CXCursor C) {
8200 if (C.kind == CXCursor_ModuleImportDecl) {
8201 if (const ImportDecl *ImportD =
8202 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
8203 return ImportD->getImportedModule();
8209 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8210 if (isNotUsableTU(TU)) {
8216 FileEntry *FE = static_cast<FileEntry *>(File);
8218 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8219 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8220 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8222 return Header.getModule();
8225 CXFile clang_Module_getASTFile(CXModule CXMod) {
8228 Module *Mod = static_cast<Module*>(CXMod);
8229 return const_cast<FileEntry *>(Mod->getASTFile());
8232 CXModule clang_Module_getParent(CXModule CXMod) {
8235 Module *Mod = static_cast<Module*>(CXMod);
8239 CXString clang_Module_getName(CXModule CXMod) {
8241 return cxstring::createEmpty();
8242 Module *Mod = static_cast<Module*>(CXMod);
8243 return cxstring::createDup(Mod->Name);
8246 CXString clang_Module_getFullName(CXModule CXMod) {
8248 return cxstring::createEmpty();
8249 Module *Mod = static_cast<Module*>(CXMod);
8250 return cxstring::createDup(Mod->getFullModuleName());
8253 int clang_Module_isSystem(CXModule CXMod) {
8256 Module *Mod = static_cast<Module*>(CXMod);
8257 return Mod->IsSystem;
8260 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8262 if (isNotUsableTU(TU)) {
8268 Module *Mod = static_cast<Module*>(CXMod);
8269 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8270 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8271 return TopHeaders.size();
8274 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8275 CXModule CXMod, unsigned Index) {
8276 if (isNotUsableTU(TU)) {
8282 Module *Mod = static_cast<Module*>(CXMod);
8283 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8285 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8286 if (Index < TopHeaders.size())
8287 return const_cast<FileEntry *>(TopHeaders[Index]);
8292 //===----------------------------------------------------------------------===//
8293 // C++ AST instrospection.
8294 //===----------------------------------------------------------------------===//
8296 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8297 if (!clang_isDeclaration(C.kind))
8300 const Decl *D = cxcursor::getCursorDecl(C);
8301 const CXXConstructorDecl *Constructor =
8302 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8303 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8306 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8307 if (!clang_isDeclaration(C.kind))
8310 const Decl *D = cxcursor::getCursorDecl(C);
8311 const CXXConstructorDecl *Constructor =
8312 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8313 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8316 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8317 if (!clang_isDeclaration(C.kind))
8320 const Decl *D = cxcursor::getCursorDecl(C);
8321 const CXXConstructorDecl *Constructor =
8322 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8323 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8326 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8327 if (!clang_isDeclaration(C.kind))
8330 const Decl *D = cxcursor::getCursorDecl(C);
8331 const CXXConstructorDecl *Constructor =
8332 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8333 // Passing 'false' excludes constructors marked 'explicit'.
8334 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8337 unsigned clang_CXXField_isMutable(CXCursor C) {
8338 if (!clang_isDeclaration(C.kind))
8341 if (const auto D = cxcursor::getCursorDecl(C))
8342 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8343 return FD->isMutable() ? 1 : 0;
8347 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8348 if (!clang_isDeclaration(C.kind))
8351 const Decl *D = cxcursor::getCursorDecl(C);
8352 const CXXMethodDecl *Method =
8353 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8354 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8357 unsigned clang_CXXMethod_isConst(CXCursor C) {
8358 if (!clang_isDeclaration(C.kind))
8361 const Decl *D = cxcursor::getCursorDecl(C);
8362 const CXXMethodDecl *Method =
8363 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8364 return (Method && Method->getTypeQualifiers().hasConst()) ? 1 : 0;
8367 unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8368 if (!clang_isDeclaration(C.kind))
8371 const Decl *D = cxcursor::getCursorDecl(C);
8372 const CXXMethodDecl *Method =
8373 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8374 return (Method && Method->isDefaulted()) ? 1 : 0;
8377 unsigned clang_CXXMethod_isStatic(CXCursor C) {
8378 if (!clang_isDeclaration(C.kind))
8381 const Decl *D = cxcursor::getCursorDecl(C);
8382 const CXXMethodDecl *Method =
8383 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8384 return (Method && Method->isStatic()) ? 1 : 0;
8387 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8388 if (!clang_isDeclaration(C.kind))
8391 const Decl *D = cxcursor::getCursorDecl(C);
8392 const CXXMethodDecl *Method =
8393 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8394 return (Method && Method->isVirtual()) ? 1 : 0;
8397 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8398 if (!clang_isDeclaration(C.kind))
8401 const auto *D = cxcursor::getCursorDecl(C);
8402 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8404 RD = RD->getDefinition();
8405 return (RD && RD->isAbstract()) ? 1 : 0;
8408 unsigned clang_EnumDecl_isScoped(CXCursor C) {
8409 if (!clang_isDeclaration(C.kind))
8412 const Decl *D = cxcursor::getCursorDecl(C);
8413 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8414 return (Enum && Enum->isScoped()) ? 1 : 0;
8417 //===----------------------------------------------------------------------===//
8418 // Attribute introspection.
8419 //===----------------------------------------------------------------------===//
8421 CXType clang_getIBOutletCollectionType(CXCursor C) {
8422 if (C.kind != CXCursor_IBOutletCollectionAttr)
8423 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8425 const IBOutletCollectionAttr *A =
8426 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8428 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8431 //===----------------------------------------------------------------------===//
8432 // Inspecting memory usage.
8433 //===----------------------------------------------------------------------===//
8435 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8437 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8438 enum CXTUResourceUsageKind k,
8439 unsigned long amount) {
8440 CXTUResourceUsageEntry entry = { k, amount };
8441 entries.push_back(entry);
8444 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8445 const char *str = "";
8447 case CXTUResourceUsage_AST:
8448 str = "ASTContext: expressions, declarations, and types";
8450 case CXTUResourceUsage_Identifiers:
8451 str = "ASTContext: identifiers";
8453 case CXTUResourceUsage_Selectors:
8454 str = "ASTContext: selectors";
8456 case CXTUResourceUsage_GlobalCompletionResults:
8457 str = "Code completion: cached global results";
8459 case CXTUResourceUsage_SourceManagerContentCache:
8460 str = "SourceManager: content cache allocator";
8462 case CXTUResourceUsage_AST_SideTables:
8463 str = "ASTContext: side tables";
8465 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8466 str = "SourceManager: malloc'ed memory buffers";
8468 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8469 str = "SourceManager: mmap'ed memory buffers";
8471 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8472 str = "ExternalASTSource: malloc'ed memory buffers";
8474 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8475 str = "ExternalASTSource: mmap'ed memory buffers";
8477 case CXTUResourceUsage_Preprocessor:
8478 str = "Preprocessor: malloc'ed memory";
8480 case CXTUResourceUsage_PreprocessingRecord:
8481 str = "Preprocessor: PreprocessingRecord";
8483 case CXTUResourceUsage_SourceManager_DataStructures:
8484 str = "SourceManager: data structures and tables";
8486 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8487 str = "Preprocessor: header search tables";
8493 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
8494 if (isNotUsableTU(TU)) {
8496 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
8500 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8501 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
8502 ASTContext &astContext = astUnit->getASTContext();
8504 // How much memory is used by AST nodes and types?
8505 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8506 (unsigned long) astContext.getASTAllocatedMemory());
8508 // How much memory is used by identifiers?
8509 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8510 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8512 // How much memory is used for selectors?
8513 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8514 (unsigned long) astContext.Selectors.getTotalMemory());
8516 // How much memory is used by ASTContext's side tables?
8517 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8518 (unsigned long) astContext.getSideTableAllocatedMemory());
8520 // How much memory is used for caching global code completion results?
8521 unsigned long completionBytes = 0;
8522 if (GlobalCodeCompletionAllocator *completionAllocator =
8523 astUnit->getCachedCompletionAllocator().get()) {
8524 completionBytes = completionAllocator->getTotalMemory();
8526 createCXTUResourceUsageEntry(*entries,
8527 CXTUResourceUsage_GlobalCompletionResults,
8530 // How much memory is being used by SourceManager's content cache?
8531 createCXTUResourceUsageEntry(*entries,
8532 CXTUResourceUsage_SourceManagerContentCache,
8533 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8535 // How much memory is being used by the MemoryBuffer's in SourceManager?
8536 const SourceManager::MemoryBufferSizes &srcBufs =
8537 astUnit->getSourceManager().getMemoryBufferSizes();
8539 createCXTUResourceUsageEntry(*entries,
8540 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8541 (unsigned long) srcBufs.malloc_bytes);
8542 createCXTUResourceUsageEntry(*entries,
8543 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8544 (unsigned long) srcBufs.mmap_bytes);
8545 createCXTUResourceUsageEntry(*entries,
8546 CXTUResourceUsage_SourceManager_DataStructures,
8547 (unsigned long) astContext.getSourceManager()
8548 .getDataStructureSizes());
8550 // How much memory is being used by the ExternalASTSource?
8551 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8552 const ExternalASTSource::MemoryBufferSizes &sizes =
8553 esrc->getMemoryBufferSizes();
8555 createCXTUResourceUsageEntry(*entries,
8556 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8557 (unsigned long) sizes.malloc_bytes);
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8560 (unsigned long) sizes.mmap_bytes);
8563 // How much memory is being used by the Preprocessor?
8564 Preprocessor &pp = astUnit->getPreprocessor();
8565 createCXTUResourceUsageEntry(*entries,
8566 CXTUResourceUsage_Preprocessor,
8567 pp.getTotalMemory());
8569 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8570 createCXTUResourceUsageEntry(*entries,
8571 CXTUResourceUsage_PreprocessingRecord,
8572 pRec->getTotalMemory());
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_Preprocessor_HeaderSearch,
8577 pp.getHeaderSearchInfo().getTotalMemory());
8579 CXTUResourceUsage usage = { (void*) entries.get(),
8580 (unsigned) entries->size(),
8581 !entries->empty() ? &(*entries)[0] : nullptr };
8582 (void)entries.release();
8586 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8588 delete (MemUsageEntries*) usage.data;
8591 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8592 CXSourceRangeList *skipped = new CXSourceRangeList;
8594 skipped->ranges = nullptr;
8596 if (isNotUsableTU(TU)) {
8604 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8605 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8609 ASTContext &Ctx = astUnit->getASTContext();
8610 SourceManager &sm = Ctx.getSourceManager();
8611 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8612 FileID wantedFileID = sm.translateFile(fileEntry);
8613 bool isMainFile = wantedFileID == sm.getMainFileID();
8615 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8616 std::vector<SourceRange> wantedRanges;
8617 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8619 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8620 wantedRanges.push_back(*i);
8621 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8622 wantedRanges.push_back(*i);
8625 skipped->count = wantedRanges.size();
8626 skipped->ranges = new CXSourceRange[skipped->count];
8627 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8628 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8633 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8634 CXSourceRangeList *skipped = new CXSourceRangeList;
8636 skipped->ranges = nullptr;
8638 if (isNotUsableTU(TU)) {
8643 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8644 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8648 ASTContext &Ctx = astUnit->getASTContext();
8650 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8652 skipped->count = SkippedRanges.size();
8653 skipped->ranges = new CXSourceRange[skipped->count];
8654 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8655 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8660 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8662 delete[] ranges->ranges;
8667 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8668 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8669 for (unsigned I = 0; I != Usage.numEntries; ++I)
8670 fprintf(stderr, " %s: %lu\n",
8671 clang_getTUResourceUsageName(Usage.entries[I].kind),
8672 Usage.entries[I].amount);
8674 clang_disposeCXTUResourceUsage(Usage);
8677 //===----------------------------------------------------------------------===//
8678 // Misc. utility functions.
8679 //===----------------------------------------------------------------------===//
8681 /// Default to using our desired 8 MB stack size on "safety" threads.
8682 static unsigned SafetyStackThreadSize = DesiredStackSize;
8686 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
8689 Size = GetSafetyThreadStackSize();
8690 if (Size && !getenv("LIBCLANG_NOTHREADS"))
8691 return CRC.RunSafelyOnThread(Fn, Size);
8692 return CRC.RunSafely(Fn);
8695 unsigned GetSafetyThreadStackSize() {
8696 return SafetyStackThreadSize;
8699 void SetSafetyThreadStackSize(unsigned Value) {
8700 SafetyStackThreadSize = Value;
8705 void clang::setThreadBackgroundPriority() {
8706 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8709 #ifdef USE_DARWIN_THREADS
8710 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8714 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8718 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8719 DEnd = Unit->stored_diag_end();
8721 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
8722 CXString Msg = clang_formatDiagnostic(&Diag,
8723 clang_defaultDiagnosticDisplayOptions());
8724 fprintf(stderr, "%s\n", clang_getCString(Msg));
8725 clang_disposeString(Msg);
8728 // On Windows, force a flush, since there may be multiple copies of
8729 // stderr and stdout in the file system, all with different buffers
8730 // but writing to the same device.
8735 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8736 SourceLocation MacroDefLoc,
8737 CXTranslationUnit TU){
8738 if (MacroDefLoc.isInvalid() || !TU)
8740 if (!II.hadMacroDefinition())
8743 ASTUnit *Unit = cxtu::getASTUnit(TU);
8744 Preprocessor &PP = Unit->getPreprocessor();
8745 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
8747 for (MacroDirective::DefInfo
8748 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8749 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8750 return Def.getMacroInfo();
8757 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
8758 CXTranslationUnit TU) {
8759 if (!MacroDef || !TU)
8761 const IdentifierInfo *II = MacroDef->getName();
8765 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8768 MacroDefinitionRecord *
8769 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8770 CXTranslationUnit TU) {
8773 if (Tok.isNot(tok::raw_identifier))
8776 if (MI->getNumTokens() == 0)
8778 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8779 MI->getDefinitionEndLoc());
8780 ASTUnit *Unit = cxtu::getASTUnit(TU);
8782 // Check that the token is inside the definition and not its argument list.
8783 SourceManager &SM = Unit->getSourceManager();
8784 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
8786 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
8789 Preprocessor &PP = Unit->getPreprocessor();
8790 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8794 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
8795 if (!II.hadMacroDefinition())
8798 // Check that the identifier is not one of the macro arguments.
8799 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
8802 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
8806 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
8809 MacroDefinitionRecord *
8810 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8811 CXTranslationUnit TU) {
8812 if (Loc.isInvalid() || !MI || !TU)
8815 if (MI->getNumTokens() == 0)
8817 ASTUnit *Unit = cxtu::getASTUnit(TU);
8818 Preprocessor &PP = Unit->getPreprocessor();
8819 if (!PP.getPreprocessingRecord())
8821 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8823 if (PP.getRawToken(Loc, Tok))
8826 return checkForMacroInMacroDefinition(MI, Tok, TU);
8829 CXString clang_getClangVersion() {
8830 return cxstring::createDup(getClangFullVersion());
8833 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8835 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
8836 LogOS << '<' << Unit->getMainFileName() << '>';
8837 if (Unit->isMainFileAST())
8838 LogOS << " (" << Unit->getASTFileName() << ')';
8842 LogOS << "<NULL TU>";
8847 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8848 *this << FE->getName();
8852 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8853 CXString cursorName = clang_getCursorDisplayName(cursor);
8854 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8855 clang_disposeString(cursorName);
8859 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8861 unsigned Line, Column;
8862 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
8863 CXString FileName = clang_getFileName(File);
8864 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8865 clang_disposeString(FileName);
8869 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8870 CXSourceLocation BLoc = clang_getRangeStart(range);
8871 CXSourceLocation ELoc = clang_getRangeEnd(range);
8874 unsigned BLine, BColumn;
8875 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
8878 unsigned ELine, EColumn;
8879 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
8881 CXString BFileName = clang_getFileName(BFile);
8882 if (BFile == EFile) {
8883 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8884 BLine, BColumn, ELine, EColumn);
8886 CXString EFileName = clang_getFileName(EFile);
8887 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8889 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8891 clang_disposeString(EFileName);
8893 clang_disposeString(BFileName);
8897 Logger &cxindex::Logger::operator<<(CXString Str) {
8898 *this << clang_getCString(Str);
8902 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8907 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8909 cxindex::Logger::~Logger() {
8910 llvm::sys::ScopedLock L(*LoggingMutex);
8912 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8914 raw_ostream &OS = llvm::errs();
8915 OS << "[libclang:" << Name << ':';
8917 #ifdef USE_DARWIN_THREADS
8918 // TODO: Portability.
8919 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8923 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8924 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
8928 llvm::sys::PrintStackTrace(OS);
8929 OS << "--------------------------------------------------\n";
8933 #ifdef CLANG_TOOL_EXTRA_BUILD
8934 // This anchor is used to force the linker to link the clang-tidy plugin.
8935 extern volatile int ClangTidyPluginAnchorSource;
8936 static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8937 ClangTidyPluginAnchorSource;
8939 // This anchor is used to force the linker to link the clang-include-fixer
8941 extern volatile int ClangIncludeFixerPluginAnchorSource;
8942 static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8943 ClangIncludeFixerPluginAnchorSource;