1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the main API hooks in the Clang-C Source Indexing
13 //===----------------------------------------------------------------------===//
16 #include "CIndexDiagnostic.h"
19 #include "CXSourceLocation.h"
21 #include "CXTranslationUnit.h"
23 #include "CursorVisitor.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Basic/DiagnosticCategories.h"
29 #include "clang/Basic/DiagnosticIDs.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/ASTUnit.h"
33 #include "clang/Frontend/CompilerInstance.h"
34 #include "clang/Frontend/FrontendDiagnostic.h"
35 #include "clang/Index/CommentToXML.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Serialization/SerializationDiagnostic.h"
41 #include "llvm/ADT/Optional.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/StringSwitch.h"
44 #include "llvm/Config/llvm-config.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/Mangler.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/CrashRecoveryContext.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Mutex.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/Threading.h"
58 #include "llvm/Support/Timer.h"
59 #include "llvm/Support/raw_ostream.h"
61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
62 #define USE_DARWIN_THREADS
65 #ifdef USE_DARWIN_THREADS
69 using namespace clang;
70 using namespace clang::cxcursor;
71 using namespace clang::cxtu;
72 using namespace clang::cxindex;
74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
78 CXTranslationUnit D = new CXTranslationUnitImpl();
81 D->StringPool = new cxstring::CXStringPool();
82 D->Diagnostics = nullptr;
83 D->OverridenCursorsPool = createOverridenCXCursorsPool();
84 D->CommentToXML = nullptr;
88 bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
100 cxtu::CXTUOwner::~CXTUOwner() {
102 clang_disposeTranslationUnit(TU);
105 /// \brief Compare two source ranges to determine their relative position in
106 /// the translation unit.
107 static RangeComparisonResult RangeCompare(SourceManager &SM,
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
121 /// \brief Determine if a source location falls within, before, or after a
122 /// a given source range.
123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
136 /// \brief Translate a Clang source range into a CIndex source range.
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
149 EndLoc = SM.getExpansionRange(EndLoc).second;
150 if (R.isTokenRange() && EndLoc.isValid()) {
151 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
153 EndLoc = EndLoc.getLocWithOffset(Length);
156 CXSourceRange Result = {
158 R.getBegin().getRawEncoding(),
159 EndLoc.getRawEncoding()
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 static SourceRange getRawCursorExtent(CXCursor C);
169 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
172 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
173 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
176 /// \brief Visit the given cursor and, if requested by the visitor,
179 /// \param Cursor the cursor to visit.
181 /// \param CheckedRegionOfInterest if true, then the caller already checked
182 /// that this cursor is within the region of interest.
184 /// \returns true if the visitation should be aborted, false if it
186 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
187 if (clang_isInvalid(Cursor.kind))
190 if (clang_isDeclaration(Cursor.kind)) {
191 const Decl *D = getCursorDecl(Cursor);
193 assert(0 && "Invalid declaration cursor");
194 return true; // abort.
197 // Ignore implicit declarations, unless it's an objc method because
198 // currently we should report implicit methods for properties when indexing.
199 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 // If we have a range of interest, and this cursor doesn't intersect with it,
205 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
206 SourceRange Range = getRawCursorExtent(Cursor);
207 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 switch (Visitor(Cursor, Parent, ClientData)) {
212 case CXChildVisit_Break:
215 case CXChildVisit_Continue:
218 case CXChildVisit_Recurse: {
219 bool ret = VisitChildren(Cursor);
220 if (PostChildrenVisitor)
221 if (PostChildrenVisitor(Cursor, ClientData))
227 llvm_unreachable("Invalid CXChildVisitResult!");
230 static bool visitPreprocessedEntitiesInRange(SourceRange R,
231 PreprocessingRecord &PPRec,
232 CursorVisitor &Visitor) {
233 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
236 if (!Visitor.shouldVisitIncludedEntities()) {
237 // If the begin/end of the range lie in the same FileID, do the optimization
238 // where we skip preprocessed entities that do not come from the same FileID.
239 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
240 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
245 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
249 bool CursorVisitor::visitFileRegion() {
250 if (RegionOfInterest.isInvalid())
253 ASTUnit *Unit = cxtu::getASTUnit(TU);
254 SourceManager &SM = Unit->getSourceManager();
256 std::pair<FileID, unsigned>
257 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
258 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
260 if (End.first != Begin.first) {
261 // If the end does not reside in the same file, try to recover by
262 // picking the end of the file of begin location.
263 End.first = Begin.first;
264 End.second = SM.getFileIDSize(Begin.first);
267 assert(Begin.first == End.first);
268 if (Begin.second > End.second)
271 FileID File = Begin.first;
272 unsigned Offset = Begin.second;
273 unsigned Length = End.second - Begin.second;
275 if (!VisitDeclsOnly && !VisitPreprocessorLast)
276 if (visitPreprocessedEntitiesInRegion())
277 return true; // visitation break.
279 if (visitDeclsFromFileRegion(File, Offset, Length))
280 return true; // visitation break.
282 if (!VisitDeclsOnly && VisitPreprocessorLast)
283 return visitPreprocessedEntitiesInRegion();
288 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 for (DeclContext *DeclDC = D->getLexicalDeclContext();
293 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
301 unsigned Offset, unsigned Length) {
302 ASTUnit *Unit = cxtu::getASTUnit(TU);
303 SourceManager &SM = Unit->getSourceManager();
304 SourceRange Range = RegionOfInterest;
306 SmallVector<Decl *, 16> Decls;
307 Unit->findFileRegionDecls(File, Offset, Length, Decls);
309 // If we didn't find any file level decls for the file, try looking at the
310 // file that it was included from.
311 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
312 bool Invalid = false;
313 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 SourceLocation Outer;
318 if (SLEntry.isFile())
319 Outer = SLEntry.getFile().getIncludeLoc();
321 Outer = SLEntry.getExpansion().getExpansionLocStart();
322 if (Outer.isInvalid())
325 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
327 Unit->findFileRegionDecls(File, Offset, Length, Decls);
330 assert(!Decls.empty());
332 bool VisitedAtLeastOnce = false;
333 DeclContext *CurDC = nullptr;
334 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
335 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
337 if (D->getSourceRange().isInvalid())
340 if (isInLexicalContext(D, CurDC))
343 CurDC = dyn_cast<DeclContext>(D);
345 if (TagDecl *TD = dyn_cast<TagDecl>(D))
346 if (!TD->isFreeStanding())
349 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
350 if (CompRes == RangeBefore)
352 if (CompRes == RangeAfter)
355 assert(CompRes == RangeOverlap);
356 VisitedAtLeastOnce = true;
358 if (isa<ObjCContainerDecl>(D)) {
359 FileDI_current = &DIt;
362 FileDI_current = nullptr;
365 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
366 return true; // visitation break.
369 if (VisitedAtLeastOnce)
372 // No Decls overlapped with the range. Move up the lexical context until there
373 // is a context that contains the range or we reach the translation unit
375 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
376 : (*(DIt-1))->getLexicalDeclContext();
378 while (DC && !DC->isTranslationUnit()) {
379 Decl *D = cast<Decl>(DC);
380 SourceRange CurDeclRange = D->getSourceRange();
381 if (CurDeclRange.isInvalid())
384 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
385 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
386 return true; // visitation break.
389 DC = D->getLexicalDeclContext();
395 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
396 if (!AU->getPreprocessor().getPreprocessingRecord())
399 PreprocessingRecord &PPRec
400 = *AU->getPreprocessor().getPreprocessingRecord();
401 SourceManager &SM = AU->getSourceManager();
403 if (RegionOfInterest.isValid()) {
404 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
405 SourceLocation B = MappedRange.getBegin();
406 SourceLocation E = MappedRange.getEnd();
408 if (AU->isInPreambleFileID(B)) {
409 if (SM.isLoadedSourceLocation(E))
410 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
413 // Beginning of range lies in the preamble but it also extends beyond
414 // it into the main file. Split the range into 2 parts, one covering
415 // the preamble and another covering the main file. This allows subsequent
416 // calls to visitPreprocessedEntitiesInRange to accept a source range that
417 // lies in the same FileID, allowing it to skip preprocessed entities that
418 // do not come from the same FileID.
420 visitPreprocessedEntitiesInRange(
421 SourceRange(B, AU->getEndOfPreambleFileID()),
423 if (breaked) return true;
424 return visitPreprocessedEntitiesInRange(
425 SourceRange(AU->getStartOfMainFileID(), E),
429 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
436 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
439 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
442 template<typename InputIterator>
443 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
445 PreprocessingRecord &PPRec,
447 for (; First != Last; ++First) {
448 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
451 PreprocessedEntity *PPE = *First;
455 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
456 if (Visit(MakeMacroExpansionCursor(ME, TU)))
462 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
463 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
469 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
470 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 /// \brief Visit the children of the given cursor.
482 /// \returns true if the visitation should be aborted, false if it
484 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
485 if (clang_isReference(Cursor.kind) &&
486 Cursor.kind != CXCursor_CXXBaseSpecifier) {
487 // By definition, references have no children.
491 // Set the Parent field to Cursor, then back to its old value once we're
493 SetParentRAII SetParent(Parent, StmtParent, Cursor);
495 if (clang_isDeclaration(Cursor.kind)) {
496 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
500 return VisitAttributes(D) || Visit(D);
503 if (clang_isStatement(Cursor.kind)) {
504 if (const Stmt *S = getCursorStmt(Cursor))
510 if (clang_isExpression(Cursor.kind)) {
511 if (const Expr *E = getCursorExpr(Cursor))
517 if (clang_isTranslationUnit(Cursor.kind)) {
518 CXTranslationUnit TU = getCursorTU(Cursor);
519 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
521 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
522 for (unsigned I = 0; I != 2; ++I) {
524 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525 RegionOfInterest.isInvalid()) {
526 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527 TLEnd = CXXUnit->top_level_end();
529 if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
555 const IBOutletCollectionAttr *A =
556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
577 // Nothing to visit at the moment.
581 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
592 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
598 switch (CompareRegionOfInterest(Range)) {
600 // This declaration comes before the region of interest; skip it.
604 // This declaration comes after the region of interest; we're done.
608 // This declaration overlaps the region of interest; visit it.
615 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623 for ( ; I != E; ++I) {
625 if (D->getLexicalDeclContext() != DC)
627 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
629 // Ignore synthesized ivars here, otherwise if we have something like:
630 // @synthesize prop = _prop;
631 // and '_prop' is not declared, we will encounter a '_prop' ivar before
632 // encountering the 'prop' synthesize declaration and we will think that
633 // we passed the region-of-interest.
634 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
635 if (ivarD->getSynthesize())
639 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
640 // declarations is a mismatch with the compiler semantics.
641 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
642 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
643 if (!ID->isThisDeclarationADefinition())
644 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
646 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
647 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
648 if (!PD->isThisDeclarationADefinition())
649 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
652 const Optional<bool> &V = shouldVisitCursor(Cursor);
657 if (Visit(Cursor, true))
663 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
664 llvm_unreachable("Translation units are visited directly by Visit()");
667 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
668 if (VisitTemplateParameters(D->getTemplateParameters()))
671 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
674 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
675 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
676 return Visit(TSInfo->getTypeLoc());
681 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
682 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
683 return Visit(TSInfo->getTypeLoc());
688 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
689 return VisitDeclContext(D);
692 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
693 ClassTemplateSpecializationDecl *D) {
694 bool ShouldVisitBody = false;
695 switch (D->getSpecializationKind()) {
697 case TSK_ImplicitInstantiation:
701 case TSK_ExplicitInstantiationDeclaration:
702 case TSK_ExplicitInstantiationDefinition:
705 case TSK_ExplicitSpecialization:
706 ShouldVisitBody = true;
710 // Visit the template arguments used in the specialization.
711 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
712 TypeLoc TL = SpecType->getTypeLoc();
713 if (TemplateSpecializationTypeLoc TSTLoc =
714 TL.getAs<TemplateSpecializationTypeLoc>()) {
715 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
716 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
721 if (ShouldVisitBody && VisitCXXRecordDecl(D))
727 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
728 ClassTemplatePartialSpecializationDecl *D) {
729 // FIXME: Visit the "outer" template parameter lists on the TagDecl
730 // before visiting these template parameters.
731 if (VisitTemplateParameters(D->getTemplateParameters()))
734 // Visit the partial specialization arguments.
735 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
736 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
737 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
738 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
741 return VisitCXXRecordDecl(D);
744 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
745 // Visit the default argument.
746 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
747 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
748 if (Visit(DefArg->getTypeLoc()))
754 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
755 if (Expr *Init = D->getInitExpr())
756 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
760 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
761 unsigned NumParamList = DD->getNumTemplateParameterLists();
762 for (unsigned i = 0; i < NumParamList; i++) {
763 TemplateParameterList* Params = DD->getTemplateParameterList(i);
764 if (VisitTemplateParameters(Params))
768 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
769 if (Visit(TSInfo->getTypeLoc()))
772 // Visit the nested-name-specifier, if present.
773 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
774 if (VisitNestedNameSpecifierLoc(QualifierLoc))
780 /// \brief Compare two base or member initializers based on their source order.
781 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
782 CXXCtorInitializer *const *Y) {
783 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
786 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
787 unsigned NumParamList = ND->getNumTemplateParameterLists();
788 for (unsigned i = 0; i < NumParamList; i++) {
789 TemplateParameterList* Params = ND->getTemplateParameterList(i);
790 if (VisitTemplateParameters(Params))
794 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
795 // Visit the function declaration's syntactic components in the order
796 // written. This requires a bit of work.
797 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
798 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
800 // If we have a function declared directly (without the use of a typedef),
801 // visit just the return type. Otherwise, just visit the function's type
803 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
807 // Visit the nested-name-specifier, if present.
808 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
809 if (VisitNestedNameSpecifierLoc(QualifierLoc))
812 // Visit the declaration name.
813 if (!isa<CXXDestructorDecl>(ND))
814 if (VisitDeclarationNameInfo(ND->getNameInfo()))
817 // FIXME: Visit explicitly-specified template arguments!
819 // Visit the function parameters, if we have a function type.
820 if (FTL && VisitFunctionTypeLoc(FTL, true))
823 // FIXME: Attributes?
826 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
827 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
828 // Find the initializers that were written in the source.
829 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
830 for (auto *I : Constructor->inits()) {
834 WrittenInits.push_back(I);
837 // Sort the initializers in source order
838 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
839 &CompareCXXCtorInitializers);
841 // Visit the initializers in source order
842 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
843 CXXCtorInitializer *Init = WrittenInits[I];
844 if (Init->isAnyMemberInitializer()) {
845 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
846 Init->getMemberLocation(), TU)))
848 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
849 if (Visit(TInfo->getTypeLoc()))
853 // Visit the initializer value.
854 if (Expr *Initializer = Init->getInit())
855 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
860 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
867 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
868 if (VisitDeclaratorDecl(D))
871 if (Expr *BitWidth = D->getBitWidth())
872 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
877 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
878 if (VisitDeclaratorDecl(D))
881 if (Expr *Init = D->getInit())
882 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
887 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
888 if (VisitDeclaratorDecl(D))
891 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
892 if (Expr *DefArg = D->getDefaultArgument())
893 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
898 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
899 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
900 // before visiting these template parameters.
901 if (VisitTemplateParameters(D->getTemplateParameters()))
904 return VisitFunctionDecl(D->getTemplatedDecl());
907 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
908 // FIXME: Visit the "outer" template parameter lists on the TagDecl
909 // before visiting these template parameters.
910 if (VisitTemplateParameters(D->getTemplateParameters()))
913 return VisitCXXRecordDecl(D->getTemplatedDecl());
916 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
917 if (VisitTemplateParameters(D->getTemplateParameters()))
920 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
921 VisitTemplateArgumentLoc(D->getDefaultArgument()))
927 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
928 // Visit the bound, if it's explicit.
929 if (D->hasExplicitBound()) {
930 if (auto TInfo = D->getTypeSourceInfo()) {
931 if (Visit(TInfo->getTypeLoc()))
939 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
940 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
941 if (Visit(TSInfo->getTypeLoc()))
944 for (const auto *P : ND->params()) {
945 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
949 if (ND->isThisDeclarationADefinition() &&
950 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
956 template <typename DeclIt>
957 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
958 SourceManager &SM, SourceLocation EndLoc,
959 SmallVectorImpl<Decl *> &Decls) {
960 DeclIt next = *DI_current;
961 while (++next != DE_current) {
962 Decl *D_next = *next;
965 SourceLocation L = D_next->getLocStart();
968 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
970 Decls.push_back(D_next);
977 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
978 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
979 // an @implementation can lexically contain Decls that are not properly
980 // nested in the AST. When we identify such cases, we need to retrofit
981 // this nesting here.
982 if (!DI_current && !FileDI_current)
983 return VisitDeclContext(D);
985 // Scan the Decls that immediately come after the container
986 // in the current DeclContext. If any fall within the
987 // container's lexical region, stash them into a vector
988 // for later processing.
989 SmallVector<Decl *, 24> DeclsInContainer;
990 SourceLocation EndLoc = D->getSourceRange().getEnd();
991 SourceManager &SM = AU->getSourceManager();
992 if (EndLoc.isValid()) {
994 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
997 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1003 if (DeclsInContainer.empty())
1004 return VisitDeclContext(D);
1006 // Get all the Decls in the DeclContext, and sort them with the
1007 // additional ones we've collected. Then visit them.
1008 for (auto *SubDecl : D->decls()) {
1009 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1010 SubDecl->getLocStart().isInvalid())
1012 DeclsInContainer.push_back(SubDecl);
1015 // Now sort the Decls so that they appear in lexical order.
1016 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1017 [&SM](Decl *A, Decl *B) {
1018 SourceLocation L_A = A->getLocStart();
1019 SourceLocation L_B = B->getLocStart();
1020 assert(L_A.isValid() && L_B.isValid());
1021 return SM.isBeforeInTranslationUnit(L_A, L_B);
1024 // Now visit the decls.
1025 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1026 E = DeclsInContainer.end(); I != E; ++I) {
1027 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1028 const Optional<bool> &V = shouldVisitCursor(Cursor);
1033 if (Visit(Cursor, true))
1039 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1040 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1044 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1047 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1048 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1049 E = ND->protocol_end(); I != E; ++I, ++PL)
1050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1053 return VisitObjCContainerDecl(ND);
1056 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1057 if (!PID->isThisDeclarationADefinition())
1058 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1060 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1061 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1062 E = PID->protocol_end(); I != E; ++I, ++PL)
1063 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1066 return VisitObjCContainerDecl(PID);
1069 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1070 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1073 // FIXME: This implements a workaround with @property declarations also being
1074 // installed in the DeclContext for the @interface. Eventually this code
1075 // should be removed.
1076 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1077 if (!CDecl || !CDecl->IsClassExtension())
1080 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1084 IdentifierInfo *PropertyId = PD->getIdentifier();
1085 ObjCPropertyDecl *prevDecl =
1086 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1091 // Visit synthesized methods since they will be skipped when visiting
1093 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1094 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1095 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1099 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1100 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1106 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1110 for (auto *typeParam : *typeParamList) {
1111 // Visit the type parameter.
1112 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1119 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1120 if (!D->isThisDeclarationADefinition()) {
1121 // Forward declaration is treated like a reference.
1122 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1125 // Objective-C type parameters.
1126 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1129 // Issue callbacks for super class.
1130 if (D->getSuperClass() &&
1131 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1132 D->getSuperClassLoc(),
1136 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1137 if (Visit(SuperClassTInfo->getTypeLoc()))
1140 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1141 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1142 E = D->protocol_end(); I != E; ++I, ++PL)
1143 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1146 return VisitObjCContainerDecl(D);
1149 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1150 return VisitObjCContainerDecl(D);
1153 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1154 // 'ID' could be null when dealing with invalid code.
1155 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1156 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1159 return VisitObjCImplDecl(D);
1162 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1164 // Issue callbacks for super class.
1165 // FIXME: No source location information!
1166 if (D->getSuperClass() &&
1167 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1168 D->getSuperClassLoc(),
1173 return VisitObjCImplDecl(D);
1176 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1177 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1178 if (PD->isIvarNameSpecified())
1179 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1184 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1185 return VisitDeclContext(D);
1188 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1189 // Visit nested-name-specifier.
1190 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1191 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1195 D->getTargetNameLoc(), TU));
1198 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1199 // Visit nested-name-specifier.
1200 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1201 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1205 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1208 return VisitDeclarationNameInfo(D->getNameInfo());
1211 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1212 // Visit nested-name-specifier.
1213 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1214 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1218 D->getIdentLocation(), TU));
1221 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1222 // Visit nested-name-specifier.
1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1228 return VisitDeclarationNameInfo(D->getNameInfo());
1231 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1232 UnresolvedUsingTypenameDecl *D) {
1233 // Visit nested-name-specifier.
1234 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1235 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1241 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1242 switch (Name.getName().getNameKind()) {
1243 case clang::DeclarationName::Identifier:
1244 case clang::DeclarationName::CXXLiteralOperatorName:
1245 case clang::DeclarationName::CXXOperatorName:
1246 case clang::DeclarationName::CXXUsingDirective:
1249 case clang::DeclarationName::CXXConstructorName:
1250 case clang::DeclarationName::CXXDestructorName:
1251 case clang::DeclarationName::CXXConversionFunctionName:
1252 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1253 return Visit(TSInfo->getTypeLoc());
1256 case clang::DeclarationName::ObjCZeroArgSelector:
1257 case clang::DeclarationName::ObjCOneArgSelector:
1258 case clang::DeclarationName::ObjCMultiArgSelector:
1259 // FIXME: Per-identifier location info?
1263 llvm_unreachable("Invalid DeclarationName::Kind!");
1266 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1267 SourceRange Range) {
1268 // FIXME: This whole routine is a hack to work around the lack of proper
1269 // source information in nested-name-specifiers (PR5791). Since we do have
1270 // a beginning source location, we can visit the first component of the
1271 // nested-name-specifier, if it's a single-token component.
1275 // Get the first component in the nested-name-specifier.
1276 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1279 switch (NNS->getKind()) {
1280 case NestedNameSpecifier::Namespace:
1281 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1284 case NestedNameSpecifier::NamespaceAlias:
1285 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1286 Range.getBegin(), TU));
1288 case NestedNameSpecifier::TypeSpec: {
1289 // If the type has a form where we know that the beginning of the source
1290 // range matches up with a reference cursor. Visit the appropriate reference
1292 const Type *T = NNS->getAsType();
1293 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1294 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1295 if (const TagType *Tag = dyn_cast<TagType>(T))
1296 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1297 if (const TemplateSpecializationType *TST
1298 = dyn_cast<TemplateSpecializationType>(T))
1299 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1303 case NestedNameSpecifier::TypeSpecWithTemplate:
1304 case NestedNameSpecifier::Global:
1305 case NestedNameSpecifier::Identifier:
1306 case NestedNameSpecifier::Super:
1314 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1315 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1316 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1317 Qualifiers.push_back(Qualifier);
1319 while (!Qualifiers.empty()) {
1320 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1321 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1322 switch (NNS->getKind()) {
1323 case NestedNameSpecifier::Namespace:
1324 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1325 Q.getLocalBeginLoc(),
1331 case NestedNameSpecifier::NamespaceAlias:
1332 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1333 Q.getLocalBeginLoc(),
1339 case NestedNameSpecifier::TypeSpec:
1340 case NestedNameSpecifier::TypeSpecWithTemplate:
1341 if (Visit(Q.getTypeLoc()))
1346 case NestedNameSpecifier::Global:
1347 case NestedNameSpecifier::Identifier:
1348 case NestedNameSpecifier::Super:
1356 bool CursorVisitor::VisitTemplateParameters(
1357 const TemplateParameterList *Params) {
1361 for (TemplateParameterList::const_iterator P = Params->begin(),
1362 PEnd = Params->end();
1364 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1371 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1372 switch (Name.getKind()) {
1373 case TemplateName::Template:
1374 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1376 case TemplateName::OverloadedTemplate:
1377 // Visit the overloaded template set.
1378 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1383 case TemplateName::DependentTemplate:
1384 // FIXME: Visit nested-name-specifier.
1387 case TemplateName::QualifiedTemplate:
1388 // FIXME: Visit nested-name-specifier.
1389 return Visit(MakeCursorTemplateRef(
1390 Name.getAsQualifiedTemplateName()->getDecl(),
1393 case TemplateName::SubstTemplateTemplateParm:
1394 return Visit(MakeCursorTemplateRef(
1395 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1398 case TemplateName::SubstTemplateTemplateParmPack:
1399 return Visit(MakeCursorTemplateRef(
1400 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1404 llvm_unreachable("Invalid TemplateName::Kind!");
1407 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1408 switch (TAL.getArgument().getKind()) {
1409 case TemplateArgument::Null:
1410 case TemplateArgument::Integral:
1411 case TemplateArgument::Pack:
1414 case TemplateArgument::Type:
1415 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1416 return Visit(TSInfo->getTypeLoc());
1419 case TemplateArgument::Declaration:
1420 if (Expr *E = TAL.getSourceDeclExpression())
1421 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1424 case TemplateArgument::NullPtr:
1425 if (Expr *E = TAL.getSourceNullPtrExpression())
1426 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1429 case TemplateArgument::Expression:
1430 if (Expr *E = TAL.getSourceExpression())
1431 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1434 case TemplateArgument::Template:
1435 case TemplateArgument::TemplateExpansion:
1436 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1439 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1440 TAL.getTemplateNameLoc());
1443 llvm_unreachable("Invalid TemplateArgument::Kind!");
1446 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1447 return VisitDeclContext(D);
1450 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1451 return Visit(TL.getUnqualifiedLoc());
1454 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1455 ASTContext &Context = AU->getASTContext();
1457 // Some builtin types (such as Objective-C's "id", "sel", and
1458 // "Class") have associated declarations. Create cursors for those.
1460 switch (TL.getTypePtr()->getKind()) {
1462 case BuiltinType::Void:
1463 case BuiltinType::NullPtr:
1464 case BuiltinType::Dependent:
1465 case BuiltinType::OCLImage1d:
1466 case BuiltinType::OCLImage1dArray:
1467 case BuiltinType::OCLImage1dBuffer:
1468 case BuiltinType::OCLImage2d:
1469 case BuiltinType::OCLImage2dArray:
1470 case BuiltinType::OCLImage2dDepth:
1471 case BuiltinType::OCLImage2dArrayDepth:
1472 case BuiltinType::OCLImage2dMSAA:
1473 case BuiltinType::OCLImage2dArrayMSAA:
1474 case BuiltinType::OCLImage2dMSAADepth:
1475 case BuiltinType::OCLImage2dArrayMSAADepth:
1476 case BuiltinType::OCLImage3d:
1477 case BuiltinType::OCLSampler:
1478 case BuiltinType::OCLEvent:
1479 case BuiltinType::OCLClkEvent:
1480 case BuiltinType::OCLQueue:
1481 case BuiltinType::OCLNDRange:
1482 case BuiltinType::OCLReserveID:
1483 #define BUILTIN_TYPE(Id, SingletonId)
1484 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1485 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1486 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1487 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1488 #include "clang/AST/BuiltinTypes.def"
1491 case BuiltinType::ObjCId:
1492 VisitType = Context.getObjCIdType();
1495 case BuiltinType::ObjCClass:
1496 VisitType = Context.getObjCClassType();
1499 case BuiltinType::ObjCSel:
1500 VisitType = Context.getObjCSelType();
1504 if (!VisitType.isNull()) {
1505 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1506 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1513 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1514 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1517 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1518 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1521 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1522 if (TL.isDefinition())
1523 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1525 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1528 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1529 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1532 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1533 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1536 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1537 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1540 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1541 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1545 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1546 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1554 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1555 return Visit(TL.getPointeeLoc());
1558 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1559 return Visit(TL.getInnerLoc());
1562 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1563 return Visit(TL.getPointeeLoc());
1566 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1567 return Visit(TL.getPointeeLoc());
1570 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1571 return Visit(TL.getPointeeLoc());
1574 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1575 return Visit(TL.getPointeeLoc());
1578 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1579 return Visit(TL.getPointeeLoc());
1582 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1583 return Visit(TL.getModifiedLoc());
1586 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1587 bool SkipResultType) {
1588 if (!SkipResultType && Visit(TL.getReturnLoc()))
1591 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1592 if (Decl *D = TL.getParam(I))
1593 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1599 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1600 if (Visit(TL.getElementLoc()))
1603 if (Expr *Size = TL.getSizeExpr())
1604 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1609 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1610 return Visit(TL.getOriginalLoc());
1613 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1614 return Visit(TL.getOriginalLoc());
1617 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1618 TemplateSpecializationTypeLoc TL) {
1619 // Visit the template name.
1620 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1621 TL.getTemplateNameLoc()))
1624 // Visit the template arguments.
1625 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1626 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1632 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1633 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1636 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1637 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1638 return Visit(TSInfo->getTypeLoc());
1643 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1644 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1645 return Visit(TSInfo->getTypeLoc());
1650 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1651 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1654 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1655 DependentTemplateSpecializationTypeLoc TL) {
1656 // Visit the nested-name-specifier, if there is one.
1657 if (TL.getQualifierLoc() &&
1658 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1661 // Visit the template arguments.
1662 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1663 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1669 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1670 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1673 return Visit(TL.getNamedTypeLoc());
1676 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1677 return Visit(TL.getPatternLoc());
1680 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1681 if (Expr *E = TL.getUnderlyingExpr())
1682 return Visit(MakeCXCursor(E, StmtParent, TU));
1687 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1688 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1691 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1692 return Visit(TL.getValueLoc());
1695 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1696 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1697 return Visit##PARENT##Loc(TL); \
1700 DEFAULT_TYPELOC_IMPL(Complex, Type)
1701 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1702 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1703 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1704 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1705 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1706 DEFAULT_TYPELOC_IMPL(Vector, Type)
1707 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1708 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1709 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1710 DEFAULT_TYPELOC_IMPL(Record, TagType)
1711 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1712 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1713 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1714 DEFAULT_TYPELOC_IMPL(Auto, Type)
1716 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1717 // Visit the nested-name-specifier, if present.
1718 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1719 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1722 if (D->isCompleteDefinition()) {
1723 for (const auto &I : D->bases()) {
1724 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1729 return VisitTagDecl(D);
1732 bool CursorVisitor::VisitAttributes(Decl *D) {
1733 for (const auto *I : D->attrs())
1734 if (Visit(MakeCXCursor(I, D, TU)))
1740 //===----------------------------------------------------------------------===//
1741 // Data-recursive visitor methods.
1742 //===----------------------------------------------------------------------===//
1745 #define DEF_JOB(NAME, DATA, KIND)\
1746 class NAME : public VisitorJob {\
1748 NAME(const DATA *d, CXCursor parent) : \
1749 VisitorJob(parent, VisitorJob::KIND, d) {} \
1750 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1751 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1754 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1755 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1756 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1757 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1758 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1759 ExplicitTemplateArgsVisitKind)
1760 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1761 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1762 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1765 class DeclVisit : public VisitorJob {
1767 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1768 VisitorJob(parent, VisitorJob::DeclVisitKind,
1769 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1770 static bool classof(const VisitorJob *VJ) {
1771 return VJ->getKind() == DeclVisitKind;
1773 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1774 bool isFirst() const { return data[1] != nullptr; }
1776 class TypeLocVisit : public VisitorJob {
1778 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1779 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1780 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1782 static bool classof(const VisitorJob *VJ) {
1783 return VJ->getKind() == TypeLocVisitKind;
1786 TypeLoc get() const {
1787 QualType T = QualType::getFromOpaquePtr(data[0]);
1788 return TypeLoc(T, const_cast<void *>(data[1]));
1792 class LabelRefVisit : public VisitorJob {
1794 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1795 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1796 labelLoc.getPtrEncoding()) {}
1798 static bool classof(const VisitorJob *VJ) {
1799 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1801 const LabelDecl *get() const {
1802 return static_cast<const LabelDecl *>(data[0]);
1804 SourceLocation getLoc() const {
1805 return SourceLocation::getFromPtrEncoding(data[1]); }
1808 class NestedNameSpecifierLocVisit : public VisitorJob {
1810 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1811 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1812 Qualifier.getNestedNameSpecifier(),
1813 Qualifier.getOpaqueData()) { }
1815 static bool classof(const VisitorJob *VJ) {
1816 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1819 NestedNameSpecifierLoc get() const {
1820 return NestedNameSpecifierLoc(
1821 const_cast<NestedNameSpecifier *>(
1822 static_cast<const NestedNameSpecifier *>(data[0])),
1823 const_cast<void *>(data[1]));
1827 class DeclarationNameInfoVisit : public VisitorJob {
1829 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1830 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1831 static bool classof(const VisitorJob *VJ) {
1832 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1834 DeclarationNameInfo get() const {
1835 const Stmt *S = static_cast<const Stmt *>(data[0]);
1836 switch (S->getStmtClass()) {
1838 llvm_unreachable("Unhandled Stmt");
1839 case clang::Stmt::MSDependentExistsStmtClass:
1840 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1841 case Stmt::CXXDependentScopeMemberExprClass:
1842 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1843 case Stmt::DependentScopeDeclRefExprClass:
1844 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1845 case Stmt::OMPCriticalDirectiveClass:
1846 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1850 class MemberRefVisit : public VisitorJob {
1852 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1853 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1854 L.getPtrEncoding()) {}
1855 static bool classof(const VisitorJob *VJ) {
1856 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1858 const FieldDecl *get() const {
1859 return static_cast<const FieldDecl *>(data[0]);
1861 SourceLocation getLoc() const {
1862 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1865 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1866 friend class OMPClauseEnqueue;
1867 VisitorWorkList &WL;
1870 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1871 : WL(wl), Parent(parent) {}
1873 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1874 void VisitBlockExpr(const BlockExpr *B);
1875 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1876 void VisitCompoundStmt(const CompoundStmt *S);
1877 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1878 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1879 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1880 void VisitCXXNewExpr(const CXXNewExpr *E);
1881 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1882 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1883 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1884 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1885 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1886 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1887 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1888 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1889 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1890 void VisitDeclRefExpr(const DeclRefExpr *D);
1891 void VisitDeclStmt(const DeclStmt *S);
1892 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1893 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1894 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1895 void VisitForStmt(const ForStmt *FS);
1896 void VisitGotoStmt(const GotoStmt *GS);
1897 void VisitIfStmt(const IfStmt *If);
1898 void VisitInitListExpr(const InitListExpr *IE);
1899 void VisitMemberExpr(const MemberExpr *M);
1900 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1901 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1902 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1903 void VisitOverloadExpr(const OverloadExpr *E);
1904 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1905 void VisitStmt(const Stmt *S);
1906 void VisitSwitchStmt(const SwitchStmt *S);
1907 void VisitWhileStmt(const WhileStmt *W);
1908 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1909 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1910 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1911 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1912 void VisitVAArgExpr(const VAArgExpr *E);
1913 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1914 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1915 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1916 void VisitLambdaExpr(const LambdaExpr *E);
1917 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1918 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1919 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1920 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1921 void VisitOMPForDirective(const OMPForDirective *D);
1922 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1923 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1924 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1925 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1926 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1927 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1928 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1929 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1930 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1931 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1932 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1933 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1934 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1935 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1937 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1938 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1939 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1940 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1941 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1942 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1943 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1944 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1945 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
1948 void AddDeclarationNameInfo(const Stmt *S);
1949 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1950 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1951 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1952 void AddStmt(const Stmt *S);
1953 void AddDecl(const Decl *D, bool isFirst = true);
1954 void AddTypeLoc(TypeSourceInfo *TI);
1955 void EnqueueChildren(const Stmt *S);
1956 void EnqueueChildren(const OMPClause *S);
1958 } // end anonyous namespace
1960 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1961 // 'S' should always be non-null, since it comes from the
1962 // statement we are visiting.
1963 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1967 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1969 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1972 void EnqueueVisitor::AddStmt(const Stmt *S) {
1974 WL.push_back(StmtVisit(S, Parent));
1976 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1978 WL.push_back(DeclVisit(D, Parent, isFirst));
1980 void EnqueueVisitor::
1981 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1983 WL.push_back(ExplicitTemplateArgsVisit(A, Parent));
1985 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
1987 WL.push_back(MemberRefVisit(D, L, Parent));
1989 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1991 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1993 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
1994 unsigned size = WL.size();
1995 for (const Stmt *SubStmt : S->children()) {
1998 if (size == WL.size())
2000 // Now reverse the entries we just added. This will match the DFS
2001 // ordering performed by the worklist.
2002 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2006 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2007 EnqueueVisitor *Visitor;
2008 /// \brief Process clauses with list of variables.
2009 template <typename T>
2010 void VisitOMPClauseList(T *Node);
2012 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2013 #define OPENMP_CLAUSE(Name, Class) \
2014 void Visit##Class(const Class *C);
2015 #include "clang/Basic/OpenMPKinds.def"
2018 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2019 Visitor->AddStmt(C->getCondition());
2022 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2023 Visitor->AddStmt(C->getCondition());
2026 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2027 Visitor->AddStmt(C->getNumThreads());
2030 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2031 Visitor->AddStmt(C->getSafelen());
2034 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2035 Visitor->AddStmt(C->getSimdlen());
2038 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2039 Visitor->AddStmt(C->getNumForLoops());
2042 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2044 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2046 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2047 Visitor->AddStmt(C->getChunkSize());
2048 Visitor->AddStmt(C->getHelperChunkSize());
2051 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2052 Visitor->AddStmt(C->getNumForLoops());
2055 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2057 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2059 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2061 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2063 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2065 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2067 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2069 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2071 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2073 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2075 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2076 Visitor->AddStmt(C->getDevice());
2079 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2080 Visitor->AddStmt(C->getNumTeams());
2083 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2084 Visitor->AddStmt(C->getThreadLimit());
2087 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2088 Visitor->AddStmt(C->getPriority());
2091 template<typename T>
2092 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2093 for (const auto *I : Node->varlists()) {
2094 Visitor->AddStmt(I);
2098 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2099 VisitOMPClauseList(C);
2100 for (const auto *E : C->private_copies()) {
2101 Visitor->AddStmt(E);
2104 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2105 const OMPFirstprivateClause *C) {
2106 VisitOMPClauseList(C);
2108 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2109 const OMPLastprivateClause *C) {
2110 VisitOMPClauseList(C);
2111 for (auto *E : C->private_copies()) {
2112 Visitor->AddStmt(E);
2114 for (auto *E : C->source_exprs()) {
2115 Visitor->AddStmt(E);
2117 for (auto *E : C->destination_exprs()) {
2118 Visitor->AddStmt(E);
2120 for (auto *E : C->assignment_ops()) {
2121 Visitor->AddStmt(E);
2124 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2125 VisitOMPClauseList(C);
2127 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2128 VisitOMPClauseList(C);
2129 for (auto *E : C->privates()) {
2130 Visitor->AddStmt(E);
2132 for (auto *E : C->lhs_exprs()) {
2133 Visitor->AddStmt(E);
2135 for (auto *E : C->rhs_exprs()) {
2136 Visitor->AddStmt(E);
2138 for (auto *E : C->reduction_ops()) {
2139 Visitor->AddStmt(E);
2142 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2143 VisitOMPClauseList(C);
2144 for (const auto *E : C->privates()) {
2145 Visitor->AddStmt(E);
2147 for (const auto *E : C->inits()) {
2148 Visitor->AddStmt(E);
2150 for (const auto *E : C->updates()) {
2151 Visitor->AddStmt(E);
2153 for (const auto *E : C->finals()) {
2154 Visitor->AddStmt(E);
2156 Visitor->AddStmt(C->getStep());
2157 Visitor->AddStmt(C->getCalcStep());
2159 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2160 VisitOMPClauseList(C);
2161 Visitor->AddStmt(C->getAlignment());
2163 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2164 VisitOMPClauseList(C);
2165 for (auto *E : C->source_exprs()) {
2166 Visitor->AddStmt(E);
2168 for (auto *E : C->destination_exprs()) {
2169 Visitor->AddStmt(E);
2171 for (auto *E : C->assignment_ops()) {
2172 Visitor->AddStmt(E);
2176 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2177 VisitOMPClauseList(C);
2178 for (auto *E : C->source_exprs()) {
2179 Visitor->AddStmt(E);
2181 for (auto *E : C->destination_exprs()) {
2182 Visitor->AddStmt(E);
2184 for (auto *E : C->assignment_ops()) {
2185 Visitor->AddStmt(E);
2188 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2189 VisitOMPClauseList(C);
2191 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2192 VisitOMPClauseList(C);
2194 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2195 VisitOMPClauseList(C);
2199 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2200 unsigned size = WL.size();
2201 OMPClauseEnqueue Visitor(this);
2203 if (size == WL.size())
2205 // Now reverse the entries we just added. This will match the DFS
2206 // ordering performed by the worklist.
2207 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2210 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2211 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2213 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2214 AddDecl(B->getBlockDecl());
2216 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2218 AddTypeLoc(E->getTypeSourceInfo());
2220 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2221 for (auto &I : llvm::reverse(S->body()))
2224 void EnqueueVisitor::
2225 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2226 AddStmt(S->getSubStmt());
2227 AddDeclarationNameInfo(S);
2228 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2229 AddNestedNameSpecifierLoc(QualifierLoc);
2232 void EnqueueVisitor::
2233 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2234 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2235 AddDeclarationNameInfo(E);
2236 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2237 AddNestedNameSpecifierLoc(QualifierLoc);
2238 if (!E->isImplicitAccess())
2239 AddStmt(E->getBase());
2241 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2242 // Enqueue the initializer , if any.
2243 AddStmt(E->getInitializer());
2244 // Enqueue the array size, if any.
2245 AddStmt(E->getArraySize());
2246 // Enqueue the allocated type.
2247 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2248 // Enqueue the placement arguments.
2249 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2250 AddStmt(E->getPlacementArg(I-1));
2252 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2253 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2254 AddStmt(CE->getArg(I-1));
2255 AddStmt(CE->getCallee());
2256 AddStmt(CE->getArg(0));
2258 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2259 const CXXPseudoDestructorExpr *E) {
2260 // Visit the name of the type being destroyed.
2261 AddTypeLoc(E->getDestroyedTypeInfo());
2262 // Visit the scope type that looks disturbingly like the nested-name-specifier
2264 AddTypeLoc(E->getScopeTypeInfo());
2265 // Visit the nested-name-specifier.
2266 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2267 AddNestedNameSpecifierLoc(QualifierLoc);
2268 // Visit base expression.
2269 AddStmt(E->getBase());
2271 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2272 const CXXScalarValueInitExpr *E) {
2273 AddTypeLoc(E->getTypeSourceInfo());
2275 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2276 const CXXTemporaryObjectExpr *E) {
2278 AddTypeLoc(E->getTypeSourceInfo());
2280 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2282 if (E->isTypeOperand())
2283 AddTypeLoc(E->getTypeOperandSourceInfo());
2286 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2287 const CXXUnresolvedConstructExpr *E) {
2289 AddTypeLoc(E->getTypeSourceInfo());
2291 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2293 if (E->isTypeOperand())
2294 AddTypeLoc(E->getTypeOperandSourceInfo());
2297 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2299 AddDecl(S->getExceptionDecl());
2302 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2303 AddStmt(S->getBody());
2304 AddStmt(S->getRangeInit());
2305 AddDecl(S->getLoopVariable());
2308 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2309 if (DR->hasExplicitTemplateArgs()) {
2310 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
2312 WL.push_back(DeclRefExprParts(DR, Parent));
2314 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2315 const DependentScopeDeclRefExpr *E) {
2316 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2317 AddDeclarationNameInfo(E);
2318 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2320 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2321 unsigned size = WL.size();
2322 bool isFirst = true;
2323 for (const auto *D : S->decls()) {
2324 AddDecl(D, isFirst);
2327 if (size == WL.size())
2329 // Now reverse the entries we just added. This will match the DFS
2330 // ordering performed by the worklist.
2331 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2334 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2335 AddStmt(E->getInit());
2336 for (DesignatedInitExpr::const_reverse_designators_iterator
2337 D = E->designators_rbegin(), DEnd = E->designators_rend();
2339 if (D->isFieldDesignator()) {
2340 if (FieldDecl *Field = D->getField())
2341 AddMemberRef(Field, D->getFieldLoc());
2344 if (D->isArrayDesignator()) {
2345 AddStmt(E->getArrayIndex(*D));
2348 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2349 AddStmt(E->getArrayRangeEnd(*D));
2350 AddStmt(E->getArrayRangeStart(*D));
2353 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2355 AddTypeLoc(E->getTypeInfoAsWritten());
2357 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2358 AddStmt(FS->getBody());
2359 AddStmt(FS->getInc());
2360 AddStmt(FS->getCond());
2361 AddDecl(FS->getConditionVariable());
2362 AddStmt(FS->getInit());
2364 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2365 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2367 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2368 AddStmt(If->getElse());
2369 AddStmt(If->getThen());
2370 AddStmt(If->getCond());
2371 AddDecl(If->getConditionVariable());
2373 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2374 // We care about the syntactic form of the initializer list, only.
2375 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2377 EnqueueChildren(IE);
2379 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2380 WL.push_back(MemberExprParts(M, Parent));
2382 // If the base of the member access expression is an implicit 'this', don't
2384 // FIXME: If we ever want to show these implicit accesses, this will be
2385 // unfortunate. However, clang_getCursor() relies on this behavior.
2386 if (M->isImplicitAccess())
2389 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2390 // real field that that we are interested in.
2391 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2392 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2393 if (FD->isAnonymousStructOrUnion()) {
2394 AddStmt(SubME->getBase());
2400 AddStmt(M->getBase());
2402 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2403 AddTypeLoc(E->getEncodedTypeSourceInfo());
2405 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2407 AddTypeLoc(M->getClassReceiverTypeInfo());
2409 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2410 // Visit the components of the offsetof expression.
2411 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2412 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2413 const OffsetOfNode &Node = E->getComponent(I-1);
2414 switch (Node.getKind()) {
2415 case OffsetOfNode::Array:
2416 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2418 case OffsetOfNode::Field:
2419 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2421 case OffsetOfNode::Identifier:
2422 case OffsetOfNode::Base:
2426 // Visit the type into which we're computing the offset.
2427 AddTypeLoc(E->getTypeSourceInfo());
2429 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2430 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2431 WL.push_back(OverloadExprParts(E, Parent));
2433 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2434 const UnaryExprOrTypeTraitExpr *E) {
2436 if (E->isArgumentType())
2437 AddTypeLoc(E->getArgumentTypeInfo());
2439 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2442 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2443 AddStmt(S->getBody());
2444 AddStmt(S->getCond());
2445 AddDecl(S->getConditionVariable());
2448 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2449 AddStmt(W->getBody());
2450 AddStmt(W->getCond());
2451 AddDecl(W->getConditionVariable());
2454 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2455 for (unsigned I = E->getNumArgs(); I > 0; --I)
2456 AddTypeLoc(E->getArg(I-1));
2459 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2460 AddTypeLoc(E->getQueriedTypeSourceInfo());
2463 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2467 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2468 VisitOverloadExpr(U);
2469 if (!U->isImplicitAccess())
2470 AddStmt(U->getBase());
2472 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2473 AddStmt(E->getSubExpr());
2474 AddTypeLoc(E->getWrittenTypeInfo());
2476 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2477 WL.push_back(SizeOfPackExprParts(E, Parent));
2479 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2480 // If the opaque value has a source expression, just transparently
2481 // visit that. This is useful for (e.g.) pseudo-object expressions.
2482 if (Expr *SourceExpr = E->getSourceExpr())
2483 return Visit(SourceExpr);
2485 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2486 AddStmt(E->getBody());
2487 WL.push_back(LambdaExprParts(E, Parent));
2489 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2490 // Treat the expression like its syntactic form.
2491 Visit(E->getSyntacticForm());
2494 void EnqueueVisitor::VisitOMPExecutableDirective(
2495 const OMPExecutableDirective *D) {
2497 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2498 E = D->clauses().end();
2500 EnqueueChildren(*I);
2503 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2504 VisitOMPExecutableDirective(D);
2507 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2508 VisitOMPExecutableDirective(D);
2511 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2512 VisitOMPLoopDirective(D);
2515 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2516 VisitOMPLoopDirective(D);
2519 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2520 VisitOMPLoopDirective(D);
2523 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2524 VisitOMPExecutableDirective(D);
2527 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2528 VisitOMPExecutableDirective(D);
2531 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2532 VisitOMPExecutableDirective(D);
2535 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2536 VisitOMPExecutableDirective(D);
2539 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2540 VisitOMPExecutableDirective(D);
2541 AddDeclarationNameInfo(D);
2545 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2546 VisitOMPLoopDirective(D);
2549 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2550 const OMPParallelForSimdDirective *D) {
2551 VisitOMPLoopDirective(D);
2554 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2555 const OMPParallelSectionsDirective *D) {
2556 VisitOMPExecutableDirective(D);
2559 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2560 VisitOMPExecutableDirective(D);
2564 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2565 VisitOMPExecutableDirective(D);
2568 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2569 VisitOMPExecutableDirective(D);
2572 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2573 VisitOMPExecutableDirective(D);
2576 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2577 const OMPTaskgroupDirective *D) {
2578 VisitOMPExecutableDirective(D);
2581 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2582 VisitOMPExecutableDirective(D);
2585 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2586 VisitOMPExecutableDirective(D);
2589 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2590 VisitOMPExecutableDirective(D);
2593 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2594 VisitOMPExecutableDirective(D);
2597 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2598 OMPTargetDataDirective *D) {
2599 VisitOMPExecutableDirective(D);
2602 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2603 VisitOMPExecutableDirective(D);
2606 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2607 const OMPCancellationPointDirective *D) {
2608 VisitOMPExecutableDirective(D);
2611 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2612 VisitOMPExecutableDirective(D);
2615 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2616 VisitOMPLoopDirective(D);
2619 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2620 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2623 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2624 if (RegionOfInterest.isValid()) {
2625 SourceRange Range = getRawCursorExtent(C);
2626 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2632 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2633 while (!WL.empty()) {
2634 // Dequeue the worklist item.
2635 VisitorJob LI = WL.pop_back_val();
2637 // Set the Parent field, then back to its old value once we're done.
2638 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2640 switch (LI.getKind()) {
2641 case VisitorJob::DeclVisitKind: {
2642 const Decl *D = cast<DeclVisit>(&LI)->get();
2646 // For now, perform default visitation for Decls.
2647 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2648 cast<DeclVisit>(&LI)->isFirst())))
2653 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2654 const ASTTemplateArgumentListInfo *ArgList =
2655 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2656 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2657 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2658 Arg != ArgEnd; ++Arg) {
2659 if (VisitTemplateArgumentLoc(*Arg))
2664 case VisitorJob::TypeLocVisitKind: {
2665 // Perform default visitation for TypeLocs.
2666 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2670 case VisitorJob::LabelRefVisitKind: {
2671 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2672 if (LabelStmt *stmt = LS->getStmt()) {
2673 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2681 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2682 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2683 if (VisitNestedNameSpecifierLoc(V->get()))
2688 case VisitorJob::DeclarationNameInfoVisitKind: {
2689 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2694 case VisitorJob::MemberRefVisitKind: {
2695 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2696 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2700 case VisitorJob::StmtVisitKind: {
2701 const Stmt *S = cast<StmtVisit>(&LI)->get();
2705 // Update the current cursor.
2706 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2707 if (!IsInRegionOfInterest(Cursor))
2709 switch (Visitor(Cursor, Parent, ClientData)) {
2710 case CXChildVisit_Break: return true;
2711 case CXChildVisit_Continue: break;
2712 case CXChildVisit_Recurse:
2713 if (PostChildrenVisitor)
2714 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2715 EnqueueWorkList(WL, S);
2720 case VisitorJob::MemberExprPartsKind: {
2721 // Handle the other pieces in the MemberExpr besides the base.
2722 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2724 // Visit the nested-name-specifier
2725 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2726 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2729 // Visit the declaration name.
2730 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2733 // Visit the explicitly-specified template arguments, if any.
2734 if (M->hasExplicitTemplateArgs()) {
2735 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2736 *ArgEnd = Arg + M->getNumTemplateArgs();
2737 Arg != ArgEnd; ++Arg) {
2738 if (VisitTemplateArgumentLoc(*Arg))
2744 case VisitorJob::DeclRefExprPartsKind: {
2745 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2746 // Visit nested-name-specifier, if present.
2747 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2748 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2750 // Visit declaration name.
2751 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2755 case VisitorJob::OverloadExprPartsKind: {
2756 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2757 // Visit the nested-name-specifier.
2758 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2759 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2761 // Visit the declaration name.
2762 if (VisitDeclarationNameInfo(O->getNameInfo()))
2764 // Visit the overloaded declaration reference.
2765 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2769 case VisitorJob::SizeOfPackExprPartsKind: {
2770 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2771 NamedDecl *Pack = E->getPack();
2772 if (isa<TemplateTypeParmDecl>(Pack)) {
2773 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2774 E->getPackLoc(), TU)))
2780 if (isa<TemplateTemplateParmDecl>(Pack)) {
2781 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2782 E->getPackLoc(), TU)))
2788 // Non-type template parameter packs and function parameter packs are
2789 // treated like DeclRefExpr cursors.
2793 case VisitorJob::LambdaExprPartsKind: {
2795 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2796 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2797 CEnd = E->explicit_capture_end();
2799 // FIXME: Lambda init-captures.
2800 if (!C->capturesVariable())
2803 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2809 // Visit parameters and return type, if present.
2810 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2811 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2812 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2813 // Visit the whole type.
2816 } else if (FunctionProtoTypeLoc Proto =
2817 TL.getAs<FunctionProtoTypeLoc>()) {
2818 if (E->hasExplicitParameters()) {
2819 // Visit parameters.
2820 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2821 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2824 // Visit result type.
2825 if (Visit(Proto.getReturnLoc()))
2833 case VisitorJob::PostChildrenVisitKind:
2834 if (PostChildrenVisitor(Parent, ClientData))
2842 bool CursorVisitor::Visit(const Stmt *S) {
2843 VisitorWorkList *WL = nullptr;
2844 if (!WorkListFreeList.empty()) {
2845 WL = WorkListFreeList.back();
2847 WorkListFreeList.pop_back();
2850 WL = new VisitorWorkList();
2851 WorkListCache.push_back(WL);
2853 EnqueueWorkList(*WL, S);
2854 bool result = RunVisitorWorkList(*WL);
2855 WorkListFreeList.push_back(WL);
2860 typedef SmallVector<SourceRange, 4> RefNamePieces;
2862 buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2863 const DeclarationNameInfo &NI, SourceRange QLoc,
2864 const ASTTemplateArgumentListInfo *TemplateArgs = nullptr) {
2865 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2866 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2867 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2869 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2871 RefNamePieces Pieces;
2873 if (WantQualifier && QLoc.isValid())
2874 Pieces.push_back(QLoc);
2876 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2877 Pieces.push_back(NI.getLoc());
2879 if (WantTemplateArgs && TemplateArgs)
2880 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2881 TemplateArgs->RAngleLoc));
2883 if (Kind == DeclarationName::CXXOperatorName) {
2884 Pieces.push_back(SourceLocation::getFromRawEncoding(
2885 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2886 Pieces.push_back(SourceLocation::getFromRawEncoding(
2887 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2890 if (WantSinglePiece) {
2891 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2893 Pieces.push_back(R);
2900 //===----------------------------------------------------------------------===//
2902 //===----------------------------------------------------------------------===//
2904 static void fatal_error_handler(void *user_data, const std::string& reason,
2905 bool gen_crash_diag) {
2906 // Write the result out to stderr avoiding errs() because raw_ostreams can
2907 // call report_fatal_error.
2908 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2913 struct RegisterFatalErrorHandler {
2914 RegisterFatalErrorHandler() {
2915 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
2920 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
2923 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2924 int displayDiagnostics) {
2925 // We use crash recovery to make some of our APIs more reliable, implicitly
2927 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
2928 llvm::CrashRecoveryContext::Enable();
2930 // Look through the managed static to trigger construction of the managed
2931 // static which registers our fatal error handler. This ensures it is only
2933 (void)*RegisterFatalErrorHandlerOnce;
2935 // Initialize targets for clang module support.
2936 llvm::InitializeAllTargets();
2937 llvm::InitializeAllTargetMCs();
2938 llvm::InitializeAllAsmPrinters();
2939 llvm::InitializeAllAsmParsers();
2941 CIndexer *CIdxr = new CIndexer();
2943 if (excludeDeclarationsFromPCH)
2944 CIdxr->setOnlyLocalDecls();
2945 if (displayDiagnostics)
2946 CIdxr->setDisplayDiagnostics();
2948 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2949 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2950 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2951 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2952 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2953 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2958 void clang_disposeIndex(CXIndex CIdx) {
2960 delete static_cast<CIndexer *>(CIdx);
2963 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2965 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2968 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2970 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2974 void clang_toggleCrashRecovery(unsigned isEnabled) {
2976 llvm::CrashRecoveryContext::Enable();
2978 llvm::CrashRecoveryContext::Disable();
2981 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2982 const char *ast_filename) {
2983 CXTranslationUnit TU;
2984 enum CXErrorCode Result =
2985 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
2987 assert((TU && Result == CXError_Success) ||
2988 (!TU && Result != CXError_Success));
2992 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
2993 const char *ast_filename,
2994 CXTranslationUnit *out_TU) {
2998 if (!CIdx || !ast_filename || !out_TU)
2999 return CXError_InvalidArguments;
3002 *Log << ast_filename;
3005 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3006 FileSystemOptions FileSystemOpts;
3008 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3009 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3010 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3011 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
3012 FileSystemOpts, /*UseDebugInfo=*/false,
3013 CXXIdx->getOnlyLocalDecls(), None,
3014 /*CaptureDiagnostics=*/true,
3015 /*AllowPCHWithCompilerErrors=*/true,
3016 /*UserFilesAreVolatile=*/true);
3017 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
3018 return *out_TU ? CXError_Success : CXError_Failure;
3021 unsigned clang_defaultEditingTranslationUnitOptions() {
3022 return CXTranslationUnit_PrecompiledPreamble |
3023 CXTranslationUnit_CacheCompletionResults;
3027 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3028 const char *source_filename,
3029 int num_command_line_args,
3030 const char * const *command_line_args,
3031 unsigned num_unsaved_files,
3032 struct CXUnsavedFile *unsaved_files) {
3033 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3034 return clang_parseTranslationUnit(CIdx, source_filename,
3035 command_line_args, num_command_line_args,
3036 unsaved_files, num_unsaved_files,
3041 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3042 const char *const *command_line_args,
3043 int num_command_line_args,
3044 ArrayRef<CXUnsavedFile> unsaved_files,
3045 unsigned options, CXTranslationUnit *out_TU) {
3046 // Set up the initial return values.
3051 if (!CIdx || !out_TU)
3052 return CXError_InvalidArguments;
3054 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3056 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3057 setThreadBackgroundPriority();
3059 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3060 // FIXME: Add a flag for modules.
3061 TranslationUnitKind TUKind
3062 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3063 bool CacheCodeCompletionResults
3064 = options & CXTranslationUnit_CacheCompletionResults;
3065 bool IncludeBriefCommentsInCodeCompletion
3066 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3067 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3068 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3070 // Configure the diagnostics.
3071 IntrusiveRefCntPtr<DiagnosticsEngine>
3072 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3074 // Recover resources if we crash before exiting this function.
3075 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3076 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3077 DiagCleanup(Diags.get());
3079 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3080 new std::vector<ASTUnit::RemappedFile>());
3082 // Recover resources if we crash before exiting this function.
3083 llvm::CrashRecoveryContextCleanupRegistrar<
3084 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3086 for (auto &UF : unsaved_files) {
3087 std::unique_ptr<llvm::MemoryBuffer> MB =
3088 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3089 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3092 std::unique_ptr<std::vector<const char *>> Args(
3093 new std::vector<const char *>());
3095 // Recover resources if we crash before exiting this method.
3096 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3097 ArgsCleanup(Args.get());
3099 // Since the Clang C library is primarily used by batch tools dealing with
3100 // (often very broken) source code, where spell-checking can have a
3101 // significant negative impact on performance (particularly when
3102 // precompiled headers are involved), we disable it by default.
3103 // Only do this if we haven't found a spell-checking-related argument.
3104 bool FoundSpellCheckingArgument = false;
3105 for (int I = 0; I != num_command_line_args; ++I) {
3106 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3107 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3108 FoundSpellCheckingArgument = true;
3112 Args->insert(Args->end(), command_line_args,
3113 command_line_args + num_command_line_args);
3115 if (!FoundSpellCheckingArgument)
3116 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3118 // The 'source_filename' argument is optional. If the caller does not
3119 // specify it then it is assumed that the source file is specified
3120 // in the actual argument list.
3121 // Put the source file after command_line_args otherwise if '-x' flag is
3122 // present it will be unused.
3123 if (source_filename)
3124 Args->push_back(source_filename);
3126 // Do we need the detailed preprocessing record?
3127 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3128 Args->push_back("-Xclang");
3129 Args->push_back("-detailed-preprocessing-record");
3132 unsigned NumErrors = Diags->getClient()->getNumErrors();
3133 std::unique_ptr<ASTUnit> ErrUnit;
3134 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3135 Args->data(), Args->data() + Args->size(),
3136 CXXIdx->getPCHContainerOperations(), Diags,
3137 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3138 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3139 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreamble, TUKind,
3140 CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3141 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3142 /*UserFilesAreVolatile=*/true, ForSerialization,
3143 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3146 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3147 if (!Unit && !ErrUnit)
3148 return CXError_ASTReadError;
3150 if (NumErrors != Diags->getClient()->getNumErrors()) {
3151 // Make sure to check that 'Unit' is non-NULL.
3152 if (CXXIdx->getDisplayDiagnostics())
3153 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3156 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3157 return CXError_ASTReadError;
3159 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3160 return *out_TU ? CXError_Success : CXError_Failure;
3164 clang_parseTranslationUnit(CXIndex CIdx,
3165 const char *source_filename,
3166 const char *const *command_line_args,
3167 int num_command_line_args,
3168 struct CXUnsavedFile *unsaved_files,
3169 unsigned num_unsaved_files,
3171 CXTranslationUnit TU;
3172 enum CXErrorCode Result = clang_parseTranslationUnit2(
3173 CIdx, source_filename, command_line_args, num_command_line_args,
3174 unsaved_files, num_unsaved_files, options, &TU);
3176 assert((TU && Result == CXError_Success) ||
3177 (!TU && Result != CXError_Success));
3181 enum CXErrorCode clang_parseTranslationUnit2(
3182 CXIndex CIdx, const char *source_filename,
3183 const char *const *command_line_args, int num_command_line_args,
3184 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3185 unsigned options, CXTranslationUnit *out_TU) {
3186 SmallVector<const char *, 4> Args;
3187 Args.push_back("clang");
3188 Args.append(command_line_args, command_line_args + num_command_line_args);
3189 return clang_parseTranslationUnit2FullArgv(
3190 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3191 num_unsaved_files, options, out_TU);
3194 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3195 CXIndex CIdx, const char *source_filename,
3196 const char *const *command_line_args, int num_command_line_args,
3197 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3198 unsigned options, CXTranslationUnit *out_TU) {
3200 *Log << source_filename << ": ";
3201 for (int i = 0; i != num_command_line_args; ++i)
3202 *Log << command_line_args[i] << " ";
3205 if (num_unsaved_files && !unsaved_files)
3206 return CXError_InvalidArguments;
3208 CXErrorCode result = CXError_Failure;
3209 auto ParseTranslationUnitImpl = [=, &result] {
3210 result = clang_parseTranslationUnit_Impl(
3211 CIdx, source_filename, command_line_args, num_command_line_args,
3212 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3214 llvm::CrashRecoveryContext CRC;
3216 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3217 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3218 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3219 fprintf(stderr, " 'command_line_args' : [");
3220 for (int i = 0; i != num_command_line_args; ++i) {
3222 fprintf(stderr, ", ");
3223 fprintf(stderr, "'%s'", command_line_args[i]);
3225 fprintf(stderr, "],\n");
3226 fprintf(stderr, " 'unsaved_files' : [");
3227 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3229 fprintf(stderr, ", ");
3230 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3231 unsaved_files[i].Length);
3233 fprintf(stderr, "],\n");
3234 fprintf(stderr, " 'options' : %d,\n", options);
3235 fprintf(stderr, "}\n");
3237 return CXError_Crashed;
3238 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3239 if (CXTranslationUnit *TU = out_TU)
3240 PrintLibclangResourceUsage(*TU);
3246 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3247 return CXSaveTranslationUnit_None;
3250 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3251 const char *FileName,
3253 CIndexer *CXXIdx = TU->CIdx;
3254 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3255 setThreadBackgroundPriority();
3257 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3258 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3261 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3264 *Log << TU << ' ' << FileName;
3267 if (isNotUsableTU(TU)) {
3269 return CXSaveError_InvalidTU;
3272 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3273 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3274 if (!CXXUnit->hasSema())
3275 return CXSaveError_InvalidTU;
3278 auto SaveTranslationUnitImpl = [=, &result]() {
3279 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3282 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3283 getenv("LIBCLANG_NOTHREADS")) {
3284 SaveTranslationUnitImpl();
3286 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3287 PrintLibclangResourceUsage(TU);
3292 // We have an AST that has invalid nodes due to compiler errors.
3293 // Use a crash recovery thread for protection.
3295 llvm::CrashRecoveryContext CRC;
3297 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3298 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3299 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3300 fprintf(stderr, " 'options' : %d,\n", options);
3301 fprintf(stderr, "}\n");
3303 return CXSaveError_Unknown;
3305 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3306 PrintLibclangResourceUsage(TU);
3312 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3314 // If the translation unit has been marked as unsafe to free, just discard
3316 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3317 if (Unit && Unit->isUnsafeToFree())
3320 delete cxtu::getASTUnit(CTUnit);
3321 delete CTUnit->StringPool;
3322 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3323 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3324 delete CTUnit->CommentToXML;
3329 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3330 return CXReparse_None;
3334 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3335 ArrayRef<CXUnsavedFile> unsaved_files,
3338 if (isNotUsableTU(TU)) {
3340 return CXError_InvalidArguments;
3343 // Reset the associated diagnostics.
3344 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3345 TU->Diagnostics = nullptr;
3347 CIndexer *CXXIdx = TU->CIdx;
3348 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3349 setThreadBackgroundPriority();
3351 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3352 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3354 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3355 new std::vector<ASTUnit::RemappedFile>());
3357 // Recover resources if we crash before exiting this function.
3358 llvm::CrashRecoveryContextCleanupRegistrar<
3359 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3361 for (auto &UF : unsaved_files) {
3362 std::unique_ptr<llvm::MemoryBuffer> MB =
3363 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3364 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3367 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3368 *RemappedFiles.get()))
3369 return CXError_Success;
3370 if (isASTReadError(CXXUnit))
3371 return CXError_ASTReadError;
3372 return CXError_Failure;
3375 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3376 unsigned num_unsaved_files,
3377 struct CXUnsavedFile *unsaved_files,
3383 if (num_unsaved_files && !unsaved_files)
3384 return CXError_InvalidArguments;
3387 auto ReparseTranslationUnitImpl = [=, &result]() {
3388 result = clang_reparseTranslationUnit_Impl(
3389 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3392 if (getenv("LIBCLANG_NOTHREADS")) {
3393 ReparseTranslationUnitImpl();
3397 llvm::CrashRecoveryContext CRC;
3399 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3400 fprintf(stderr, "libclang: crash detected during reparsing\n");
3401 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3402 return CXError_Crashed;
3403 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3404 PrintLibclangResourceUsage(TU);
3410 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3411 if (isNotUsableTU(CTUnit)) {
3413 return cxstring::createEmpty();
3416 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3417 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3420 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3421 if (isNotUsableTU(TU)) {
3423 return clang_getNullCursor();
3426 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3427 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3430 } // end: extern "C"
3432 //===----------------------------------------------------------------------===//
3433 // CXFile Operations.
3434 //===----------------------------------------------------------------------===//
3437 CXString clang_getFileName(CXFile SFile) {
3439 return cxstring::createNull();
3441 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3442 return cxstring::createRef(FEnt->getName());
3445 time_t clang_getFileTime(CXFile SFile) {
3449 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3450 return FEnt->getModificationTime();
3453 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3454 if (isNotUsableTU(TU)) {
3459 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3461 FileManager &FMgr = CXXUnit->getFileManager();
3462 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3465 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3467 if (isNotUsableTU(TU)) {
3475 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3476 FileEntry *FEnt = static_cast<FileEntry *>(file);
3477 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3478 .isFileMultipleIncludeGuarded(FEnt);
3481 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3482 if (!file || !outID)
3485 FileEntry *FEnt = static_cast<FileEntry *>(file);
3486 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3487 outID->data[0] = ID.getDevice();
3488 outID->data[1] = ID.getFile();
3489 outID->data[2] = FEnt->getModificationTime();
3493 int clang_File_isEqual(CXFile file1, CXFile file2) {
3497 if (!file1 || !file2)
3500 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3501 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3502 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3505 } // end: extern "C"
3507 //===----------------------------------------------------------------------===//
3508 // CXCursor Operations.
3509 //===----------------------------------------------------------------------===//
3511 static const Decl *getDeclFromExpr(const Stmt *E) {
3512 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3513 return getDeclFromExpr(CE->getSubExpr());
3515 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3516 return RefExpr->getDecl();
3517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3518 return ME->getMemberDecl();
3519 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3520 return RE->getDecl();
3521 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3522 if (PRE->isExplicitProperty())
3523 return PRE->getExplicitProperty();
3524 // It could be messaging both getter and setter as in:
3526 // in which case prefer to associate the setter since it is less obvious
3527 // from inspecting the source that the setter is going to get called.
3528 if (PRE->isMessagingSetter())
3529 return PRE->getImplicitPropertySetter();
3530 return PRE->getImplicitPropertyGetter();
3532 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3533 return getDeclFromExpr(POE->getSyntacticForm());
3534 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3535 if (Expr *Src = OVE->getSourceExpr())
3536 return getDeclFromExpr(Src);
3538 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3539 return getDeclFromExpr(CE->getCallee());
3540 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3541 if (!CE->isElidable())
3542 return CE->getConstructor();
3543 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3544 return OME->getMethodDecl();
3546 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3547 return PE->getProtocol();
3548 if (const SubstNonTypeTemplateParmPackExpr *NTTP
3549 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3550 return NTTP->getParameterPack();
3551 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3552 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3553 isa<ParmVarDecl>(SizeOfPack->getPack()))
3554 return SizeOfPack->getPack();
3559 static SourceLocation getLocationFromExpr(const Expr *E) {
3560 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3561 return getLocationFromExpr(CE->getSubExpr());
3563 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3564 return /*FIXME:*/Msg->getLeftLoc();
3565 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3566 return DRE->getLocation();
3567 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3568 return Member->getMemberLoc();
3569 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3570 return Ivar->getLocation();
3571 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3572 return SizeOfPack->getPackLoc();
3573 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3574 return PropRef->getLocation();
3576 return E->getLocStart();
3579 static std::string getMangledStructor(std::unique_ptr<MangleContext> &M,
3580 std::unique_ptr<llvm::DataLayout> &DL,
3581 const NamedDecl *ND,
3582 unsigned StructorType) {
3583 std::string FrontendBuf;
3584 llvm::raw_string_ostream FOS(FrontendBuf);
3586 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND))
3587 M->mangleCXXCtor(CD, static_cast<CXXCtorType>(StructorType), FOS);
3588 else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND))
3589 M->mangleCXXDtor(DD, static_cast<CXXDtorType>(StructorType), FOS);
3591 std::string BackendBuf;
3592 llvm::raw_string_ostream BOS(BackendBuf);
3594 llvm::Mangler::getNameWithPrefix(BOS, llvm::Twine(FOS.str()), *DL);
3601 unsigned clang_visitChildren(CXCursor parent,
3602 CXCursorVisitor visitor,
3603 CXClientData client_data) {
3604 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3605 /*VisitPreprocessorLast=*/false);
3606 return CursorVis.VisitChildren(parent);
3609 #ifndef __has_feature
3610 #define __has_feature(x) 0
3612 #if __has_feature(blocks)
3613 typedef enum CXChildVisitResult
3614 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3616 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3617 CXClientData client_data) {
3618 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3619 return block(cursor, parent);
3622 // If we are compiled with a compiler that doesn't have native blocks support,
3623 // define and call the block manually, so the
3624 typedef struct _CXChildVisitResult
3629 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3631 } *CXCursorVisitorBlock;
3633 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3634 CXClientData client_data) {
3635 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3636 return block->invoke(block, cursor, parent);
3641 unsigned clang_visitChildrenWithBlock(CXCursor parent,
3642 CXCursorVisitorBlock block) {
3643 return clang_visitChildren(parent, visitWithBlock, block);
3646 static CXString getDeclSpelling(const Decl *D) {
3648 return cxstring::createEmpty();
3650 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3652 if (const ObjCPropertyImplDecl *PropImpl =
3653 dyn_cast<ObjCPropertyImplDecl>(D))
3654 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3655 return cxstring::createDup(Property->getIdentifier()->getName());
3657 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3658 if (Module *Mod = ImportD->getImportedModule())
3659 return cxstring::createDup(Mod->getFullModuleName());
3661 return cxstring::createEmpty();
3664 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3665 return cxstring::createDup(OMD->getSelector().getAsString());
3667 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3668 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3669 // and returns different names. NamedDecl returns the class name and
3670 // ObjCCategoryImplDecl returns the category name.
3671 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
3673 if (isa<UsingDirectiveDecl>(D))
3674 return cxstring::createEmpty();
3676 SmallString<1024> S;
3677 llvm::raw_svector_ostream os(S);
3680 return cxstring::createDup(os.str());
3683 CXString clang_getCursorSpelling(CXCursor C) {
3684 if (clang_isTranslationUnit(C.kind))
3685 return clang_getTranslationUnitSpelling(getCursorTU(C));
3687 if (clang_isReference(C.kind)) {
3689 case CXCursor_ObjCSuperClassRef: {
3690 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3691 return cxstring::createRef(Super->getIdentifier()->getNameStart());
3693 case CXCursor_ObjCClassRef: {
3694 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3695 return cxstring::createRef(Class->getIdentifier()->getNameStart());
3697 case CXCursor_ObjCProtocolRef: {
3698 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3699 assert(OID && "getCursorSpelling(): Missing protocol decl");
3700 return cxstring::createRef(OID->getIdentifier()->getNameStart());
3702 case CXCursor_CXXBaseSpecifier: {
3703 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3704 return cxstring::createDup(B->getType().getAsString());
3706 case CXCursor_TypeRef: {
3707 const TypeDecl *Type = getCursorTypeRef(C).first;
3708 assert(Type && "Missing type decl");
3710 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
3713 case CXCursor_TemplateRef: {
3714 const TemplateDecl *Template = getCursorTemplateRef(C).first;
3715 assert(Template && "Missing template decl");
3717 return cxstring::createDup(Template->getNameAsString());
3720 case CXCursor_NamespaceRef: {
3721 const NamedDecl *NS = getCursorNamespaceRef(C).first;
3722 assert(NS && "Missing namespace decl");
3724 return cxstring::createDup(NS->getNameAsString());
3727 case CXCursor_MemberRef: {
3728 const FieldDecl *Field = getCursorMemberRef(C).first;
3729 assert(Field && "Missing member decl");
3731 return cxstring::createDup(Field->getNameAsString());
3734 case CXCursor_LabelRef: {
3735 const LabelStmt *Label = getCursorLabelRef(C).first;
3736 assert(Label && "Missing label");
3738 return cxstring::createRef(Label->getName());
3741 case CXCursor_OverloadedDeclRef: {
3742 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3743 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3744 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3745 return cxstring::createDup(ND->getNameAsString());
3746 return cxstring::createEmpty();
3748 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3749 return cxstring::createDup(E->getName().getAsString());
3750 OverloadedTemplateStorage *Ovl
3751 = Storage.get<OverloadedTemplateStorage*>();
3752 if (Ovl->size() == 0)
3753 return cxstring::createEmpty();
3754 return cxstring::createDup((*Ovl->begin())->getNameAsString());
3757 case CXCursor_VariableRef: {
3758 const VarDecl *Var = getCursorVariableRef(C).first;
3759 assert(Var && "Missing variable decl");
3761 return cxstring::createDup(Var->getNameAsString());
3765 return cxstring::createRef("<not implemented>");
3769 if (clang_isExpression(C.kind)) {
3770 const Expr *E = getCursorExpr(C);
3772 if (C.kind == CXCursor_ObjCStringLiteral ||
3773 C.kind == CXCursor_StringLiteral) {
3774 const StringLiteral *SLit;
3775 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
3776 SLit = OSL->getString();
3778 SLit = cast<StringLiteral>(E);
3780 SmallString<256> Buf;
3781 llvm::raw_svector_ostream OS(Buf);
3782 SLit->outputString(OS);
3783 return cxstring::createDup(OS.str());
3786 const Decl *D = getDeclFromExpr(getCursorExpr(C));
3788 return getDeclSpelling(D);
3789 return cxstring::createEmpty();
3792 if (clang_isStatement(C.kind)) {
3793 const Stmt *S = getCursorStmt(C);
3794 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3795 return cxstring::createRef(Label->getName());
3797 return cxstring::createEmpty();
3800 if (C.kind == CXCursor_MacroExpansion)
3801 return cxstring::createRef(getCursorMacroExpansion(C).getName()
3804 if (C.kind == CXCursor_MacroDefinition)
3805 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
3808 if (C.kind == CXCursor_InclusionDirective)
3809 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
3811 if (clang_isDeclaration(C.kind))
3812 return getDeclSpelling(getCursorDecl(C));
3814 if (C.kind == CXCursor_AnnotateAttr) {
3815 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3816 return cxstring::createDup(AA->getAnnotation());
3819 if (C.kind == CXCursor_AsmLabelAttr) {
3820 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3821 return cxstring::createDup(AA->getLabel());
3824 if (C.kind == CXCursor_PackedAttr) {
3825 return cxstring::createRef("packed");
3828 if (C.kind == CXCursor_VisibilityAttr) {
3829 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
3830 switch (AA->getVisibility()) {
3831 case VisibilityAttr::VisibilityType::Default:
3832 return cxstring::createRef("default");
3833 case VisibilityAttr::VisibilityType::Hidden:
3834 return cxstring::createRef("hidden");
3835 case VisibilityAttr::VisibilityType::Protected:
3836 return cxstring::createRef("protected");
3838 llvm_unreachable("unknown visibility type");
3841 return cxstring::createEmpty();
3844 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3845 unsigned pieceIndex,
3847 if (clang_Cursor_isNull(C))
3848 return clang_getNullRange();
3850 ASTContext &Ctx = getCursorContext(C);
3852 if (clang_isStatement(C.kind)) {
3853 const Stmt *S = getCursorStmt(C);
3854 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3856 return clang_getNullRange();
3857 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3860 return clang_getNullRange();
3863 if (C.kind == CXCursor_ObjCMessageExpr) {
3864 if (const ObjCMessageExpr *
3865 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3866 if (pieceIndex >= ME->getNumSelectorLocs())
3867 return clang_getNullRange();
3868 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3872 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3873 C.kind == CXCursor_ObjCClassMethodDecl) {
3874 if (const ObjCMethodDecl *
3875 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3876 if (pieceIndex >= MD->getNumSelectorLocs())
3877 return clang_getNullRange();
3878 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3882 if (C.kind == CXCursor_ObjCCategoryDecl ||
3883 C.kind == CXCursor_ObjCCategoryImplDecl) {
3885 return clang_getNullRange();
3886 if (const ObjCCategoryDecl *
3887 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3888 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3889 if (const ObjCCategoryImplDecl *
3890 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3891 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3894 if (C.kind == CXCursor_ModuleImportDecl) {
3896 return clang_getNullRange();
3897 if (const ImportDecl *ImportD =
3898 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3899 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3901 return cxloc::translateSourceRange(Ctx,
3902 SourceRange(Locs.front(), Locs.back()));
3904 return clang_getNullRange();
3907 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
3908 C.kind == CXCursor_ConversionFunction) {
3910 return clang_getNullRange();
3911 if (const FunctionDecl *FD =
3912 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
3913 DeclarationNameInfo FunctionName = FD->getNameInfo();
3914 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
3916 return clang_getNullRange();
3919 // FIXME: A CXCursor_InclusionDirective should give the location of the
3920 // filename, but we don't keep track of this.
3922 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3923 // but we don't keep track of this.
3925 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3926 // but we don't keep track of this.
3928 // Default handling, give the location of the cursor.
3931 return clang_getNullRange();
3933 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3934 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3935 return cxloc::translateSourceRange(Ctx, Loc);
3938 CXString clang_Cursor_getMangling(CXCursor C) {
3939 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
3940 return cxstring::createEmpty();
3942 // Mangling only works for functions and variables.
3943 const Decl *D = getCursorDecl(C);
3944 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
3945 return cxstring::createEmpty();
3947 // First apply frontend mangling.
3948 const NamedDecl *ND = cast<NamedDecl>(D);
3949 ASTContext &Ctx = ND->getASTContext();
3950 std::unique_ptr<MangleContext> MC(Ctx.createMangleContext());
3952 std::string FrontendBuf;
3953 llvm::raw_string_ostream FrontendBufOS(FrontendBuf);
3954 if (MC->shouldMangleDeclName(ND)) {
3955 MC->mangleName(ND, FrontendBufOS);
3957 ND->printName(FrontendBufOS);
3960 // Now apply backend mangling.
3961 std::unique_ptr<llvm::DataLayout> DL(
3962 new llvm::DataLayout(Ctx.getTargetInfo().getDataLayoutString()));
3964 std::string FinalBuf;
3965 llvm::raw_string_ostream FinalBufOS(FinalBuf);
3966 llvm::Mangler::getNameWithPrefix(FinalBufOS, llvm::Twine(FrontendBufOS.str()),
3969 return cxstring::createDup(FinalBufOS.str());
3972 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
3973 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
3976 const Decl *D = getCursorDecl(C);
3977 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
3980 const NamedDecl *ND = cast<NamedDecl>(D);
3982 ASTContext &Ctx = ND->getASTContext();
3983 std::unique_ptr<MangleContext> M(Ctx.createMangleContext());
3984 std::unique_ptr<llvm::DataLayout> DL(
3985 new llvm::DataLayout(Ctx.getTargetInfo().getDataLayoutString()));
3987 std::vector<std::string> Manglings;
3989 auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
3990 auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
3991 /*IsCSSMethod=*/true);
3992 auto CC = MD->getType()->getAs<FunctionProtoType>()->getCallConv();
3993 return CC == DefaultCC;
3996 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) {
3997 Manglings.emplace_back(getMangledStructor(M, DL, CD, Ctor_Base));
3999 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily())
4000 if (!CD->getParent()->isAbstract())
4001 Manglings.emplace_back(getMangledStructor(M, DL, CD, Ctor_Complete));
4003 if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4004 if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
4005 if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
4006 Manglings.emplace_back(getMangledStructor(M, DL, CD,
4007 Ctor_DefaultClosure));
4008 } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) {
4009 Manglings.emplace_back(getMangledStructor(M, DL, DD, Dtor_Base));
4010 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) {
4011 Manglings.emplace_back(getMangledStructor(M, DL, DD, Dtor_Complete));
4013 if (!DD->isVirtual())
4014 Manglings.emplace_back(getMangledStructor(M, DL, DD, Dtor_Deleting));
4018 return cxstring::createSet(Manglings);
4021 CXString clang_getCursorDisplayName(CXCursor C) {
4022 if (!clang_isDeclaration(C.kind))
4023 return clang_getCursorSpelling(C);
4025 const Decl *D = getCursorDecl(C);
4027 return cxstring::createEmpty();
4029 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4030 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4031 D = FunTmpl->getTemplatedDecl();
4033 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4034 SmallString<64> Str;
4035 llvm::raw_svector_ostream OS(Str);
4037 if (Function->getPrimaryTemplate())
4040 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4043 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4046 if (Function->isVariadic()) {
4047 if (Function->getNumParams())
4052 return cxstring::createDup(OS.str());
4055 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4056 SmallString<64> Str;
4057 llvm::raw_svector_ostream OS(Str);
4058 OS << *ClassTemplate;
4060 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4061 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4065 NamedDecl *Param = Params->getParam(I);
4066 if (Param->getIdentifier()) {
4067 OS << Param->getIdentifier()->getName();
4071 // There is no parameter name, which makes this tricky. Try to come up
4072 // with something useful that isn't too long.
4073 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4074 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4075 else if (NonTypeTemplateParmDecl *NTTP
4076 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4077 OS << NTTP->getType().getAsString(Policy);
4079 OS << "template<...> class";
4083 return cxstring::createDup(OS.str());
4086 if (const ClassTemplateSpecializationDecl *ClassSpec
4087 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4088 // If the type was explicitly written, use that.
4089 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4090 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
4092 SmallString<128> Str;
4093 llvm::raw_svector_ostream OS(Str);
4095 TemplateSpecializationType::PrintTemplateArgumentList(OS,
4096 ClassSpec->getTemplateArgs().data(),
4097 ClassSpec->getTemplateArgs().size(),
4099 return cxstring::createDup(OS.str());
4102 return clang_getCursorSpelling(C);
4105 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4107 case CXCursor_FunctionDecl:
4108 return cxstring::createRef("FunctionDecl");
4109 case CXCursor_TypedefDecl:
4110 return cxstring::createRef("TypedefDecl");
4111 case CXCursor_EnumDecl:
4112 return cxstring::createRef("EnumDecl");
4113 case CXCursor_EnumConstantDecl:
4114 return cxstring::createRef("EnumConstantDecl");
4115 case CXCursor_StructDecl:
4116 return cxstring::createRef("StructDecl");
4117 case CXCursor_UnionDecl:
4118 return cxstring::createRef("UnionDecl");
4119 case CXCursor_ClassDecl:
4120 return cxstring::createRef("ClassDecl");
4121 case CXCursor_FieldDecl:
4122 return cxstring::createRef("FieldDecl");
4123 case CXCursor_VarDecl:
4124 return cxstring::createRef("VarDecl");
4125 case CXCursor_ParmDecl:
4126 return cxstring::createRef("ParmDecl");
4127 case CXCursor_ObjCInterfaceDecl:
4128 return cxstring::createRef("ObjCInterfaceDecl");
4129 case CXCursor_ObjCCategoryDecl:
4130 return cxstring::createRef("ObjCCategoryDecl");
4131 case CXCursor_ObjCProtocolDecl:
4132 return cxstring::createRef("ObjCProtocolDecl");
4133 case CXCursor_ObjCPropertyDecl:
4134 return cxstring::createRef("ObjCPropertyDecl");
4135 case CXCursor_ObjCIvarDecl:
4136 return cxstring::createRef("ObjCIvarDecl");
4137 case CXCursor_ObjCInstanceMethodDecl:
4138 return cxstring::createRef("ObjCInstanceMethodDecl");
4139 case CXCursor_ObjCClassMethodDecl:
4140 return cxstring::createRef("ObjCClassMethodDecl");
4141 case CXCursor_ObjCImplementationDecl:
4142 return cxstring::createRef("ObjCImplementationDecl");
4143 case CXCursor_ObjCCategoryImplDecl:
4144 return cxstring::createRef("ObjCCategoryImplDecl");
4145 case CXCursor_CXXMethod:
4146 return cxstring::createRef("CXXMethod");
4147 case CXCursor_UnexposedDecl:
4148 return cxstring::createRef("UnexposedDecl");
4149 case CXCursor_ObjCSuperClassRef:
4150 return cxstring::createRef("ObjCSuperClassRef");
4151 case CXCursor_ObjCProtocolRef:
4152 return cxstring::createRef("ObjCProtocolRef");
4153 case CXCursor_ObjCClassRef:
4154 return cxstring::createRef("ObjCClassRef");
4155 case CXCursor_TypeRef:
4156 return cxstring::createRef("TypeRef");
4157 case CXCursor_TemplateRef:
4158 return cxstring::createRef("TemplateRef");
4159 case CXCursor_NamespaceRef:
4160 return cxstring::createRef("NamespaceRef");
4161 case CXCursor_MemberRef:
4162 return cxstring::createRef("MemberRef");
4163 case CXCursor_LabelRef:
4164 return cxstring::createRef("LabelRef");
4165 case CXCursor_OverloadedDeclRef:
4166 return cxstring::createRef("OverloadedDeclRef");
4167 case CXCursor_VariableRef:
4168 return cxstring::createRef("VariableRef");
4169 case CXCursor_IntegerLiteral:
4170 return cxstring::createRef("IntegerLiteral");
4171 case CXCursor_FloatingLiteral:
4172 return cxstring::createRef("FloatingLiteral");
4173 case CXCursor_ImaginaryLiteral:
4174 return cxstring::createRef("ImaginaryLiteral");
4175 case CXCursor_StringLiteral:
4176 return cxstring::createRef("StringLiteral");
4177 case CXCursor_CharacterLiteral:
4178 return cxstring::createRef("CharacterLiteral");
4179 case CXCursor_ParenExpr:
4180 return cxstring::createRef("ParenExpr");
4181 case CXCursor_UnaryOperator:
4182 return cxstring::createRef("UnaryOperator");
4183 case CXCursor_ArraySubscriptExpr:
4184 return cxstring::createRef("ArraySubscriptExpr");
4185 case CXCursor_OMPArraySectionExpr:
4186 return cxstring::createRef("OMPArraySectionExpr");
4187 case CXCursor_BinaryOperator:
4188 return cxstring::createRef("BinaryOperator");
4189 case CXCursor_CompoundAssignOperator:
4190 return cxstring::createRef("CompoundAssignOperator");
4191 case CXCursor_ConditionalOperator:
4192 return cxstring::createRef("ConditionalOperator");
4193 case CXCursor_CStyleCastExpr:
4194 return cxstring::createRef("CStyleCastExpr");
4195 case CXCursor_CompoundLiteralExpr:
4196 return cxstring::createRef("CompoundLiteralExpr");
4197 case CXCursor_InitListExpr:
4198 return cxstring::createRef("InitListExpr");
4199 case CXCursor_AddrLabelExpr:
4200 return cxstring::createRef("AddrLabelExpr");
4201 case CXCursor_StmtExpr:
4202 return cxstring::createRef("StmtExpr");
4203 case CXCursor_GenericSelectionExpr:
4204 return cxstring::createRef("GenericSelectionExpr");
4205 case CXCursor_GNUNullExpr:
4206 return cxstring::createRef("GNUNullExpr");
4207 case CXCursor_CXXStaticCastExpr:
4208 return cxstring::createRef("CXXStaticCastExpr");
4209 case CXCursor_CXXDynamicCastExpr:
4210 return cxstring::createRef("CXXDynamicCastExpr");
4211 case CXCursor_CXXReinterpretCastExpr:
4212 return cxstring::createRef("CXXReinterpretCastExpr");
4213 case CXCursor_CXXConstCastExpr:
4214 return cxstring::createRef("CXXConstCastExpr");
4215 case CXCursor_CXXFunctionalCastExpr:
4216 return cxstring::createRef("CXXFunctionalCastExpr");
4217 case CXCursor_CXXTypeidExpr:
4218 return cxstring::createRef("CXXTypeidExpr");
4219 case CXCursor_CXXBoolLiteralExpr:
4220 return cxstring::createRef("CXXBoolLiteralExpr");
4221 case CXCursor_CXXNullPtrLiteralExpr:
4222 return cxstring::createRef("CXXNullPtrLiteralExpr");
4223 case CXCursor_CXXThisExpr:
4224 return cxstring::createRef("CXXThisExpr");
4225 case CXCursor_CXXThrowExpr:
4226 return cxstring::createRef("CXXThrowExpr");
4227 case CXCursor_CXXNewExpr:
4228 return cxstring::createRef("CXXNewExpr");
4229 case CXCursor_CXXDeleteExpr:
4230 return cxstring::createRef("CXXDeleteExpr");
4231 case CXCursor_UnaryExpr:
4232 return cxstring::createRef("UnaryExpr");
4233 case CXCursor_ObjCStringLiteral:
4234 return cxstring::createRef("ObjCStringLiteral");
4235 case CXCursor_ObjCBoolLiteralExpr:
4236 return cxstring::createRef("ObjCBoolLiteralExpr");
4237 case CXCursor_ObjCSelfExpr:
4238 return cxstring::createRef("ObjCSelfExpr");
4239 case CXCursor_ObjCEncodeExpr:
4240 return cxstring::createRef("ObjCEncodeExpr");
4241 case CXCursor_ObjCSelectorExpr:
4242 return cxstring::createRef("ObjCSelectorExpr");
4243 case CXCursor_ObjCProtocolExpr:
4244 return cxstring::createRef("ObjCProtocolExpr");
4245 case CXCursor_ObjCBridgedCastExpr:
4246 return cxstring::createRef("ObjCBridgedCastExpr");
4247 case CXCursor_BlockExpr:
4248 return cxstring::createRef("BlockExpr");
4249 case CXCursor_PackExpansionExpr:
4250 return cxstring::createRef("PackExpansionExpr");
4251 case CXCursor_SizeOfPackExpr:
4252 return cxstring::createRef("SizeOfPackExpr");
4253 case CXCursor_LambdaExpr:
4254 return cxstring::createRef("LambdaExpr");
4255 case CXCursor_UnexposedExpr:
4256 return cxstring::createRef("UnexposedExpr");
4257 case CXCursor_DeclRefExpr:
4258 return cxstring::createRef("DeclRefExpr");
4259 case CXCursor_MemberRefExpr:
4260 return cxstring::createRef("MemberRefExpr");
4261 case CXCursor_CallExpr:
4262 return cxstring::createRef("CallExpr");
4263 case CXCursor_ObjCMessageExpr:
4264 return cxstring::createRef("ObjCMessageExpr");
4265 case CXCursor_UnexposedStmt:
4266 return cxstring::createRef("UnexposedStmt");
4267 case CXCursor_DeclStmt:
4268 return cxstring::createRef("DeclStmt");
4269 case CXCursor_LabelStmt:
4270 return cxstring::createRef("LabelStmt");
4271 case CXCursor_CompoundStmt:
4272 return cxstring::createRef("CompoundStmt");
4273 case CXCursor_CaseStmt:
4274 return cxstring::createRef("CaseStmt");
4275 case CXCursor_DefaultStmt:
4276 return cxstring::createRef("DefaultStmt");
4277 case CXCursor_IfStmt:
4278 return cxstring::createRef("IfStmt");
4279 case CXCursor_SwitchStmt:
4280 return cxstring::createRef("SwitchStmt");
4281 case CXCursor_WhileStmt:
4282 return cxstring::createRef("WhileStmt");
4283 case CXCursor_DoStmt:
4284 return cxstring::createRef("DoStmt");
4285 case CXCursor_ForStmt:
4286 return cxstring::createRef("ForStmt");
4287 case CXCursor_GotoStmt:
4288 return cxstring::createRef("GotoStmt");
4289 case CXCursor_IndirectGotoStmt:
4290 return cxstring::createRef("IndirectGotoStmt");
4291 case CXCursor_ContinueStmt:
4292 return cxstring::createRef("ContinueStmt");
4293 case CXCursor_BreakStmt:
4294 return cxstring::createRef("BreakStmt");
4295 case CXCursor_ReturnStmt:
4296 return cxstring::createRef("ReturnStmt");
4297 case CXCursor_GCCAsmStmt:
4298 return cxstring::createRef("GCCAsmStmt");
4299 case CXCursor_MSAsmStmt:
4300 return cxstring::createRef("MSAsmStmt");
4301 case CXCursor_ObjCAtTryStmt:
4302 return cxstring::createRef("ObjCAtTryStmt");
4303 case CXCursor_ObjCAtCatchStmt:
4304 return cxstring::createRef("ObjCAtCatchStmt");
4305 case CXCursor_ObjCAtFinallyStmt:
4306 return cxstring::createRef("ObjCAtFinallyStmt");
4307 case CXCursor_ObjCAtThrowStmt:
4308 return cxstring::createRef("ObjCAtThrowStmt");
4309 case CXCursor_ObjCAtSynchronizedStmt:
4310 return cxstring::createRef("ObjCAtSynchronizedStmt");
4311 case CXCursor_ObjCAutoreleasePoolStmt:
4312 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4313 case CXCursor_ObjCForCollectionStmt:
4314 return cxstring::createRef("ObjCForCollectionStmt");
4315 case CXCursor_CXXCatchStmt:
4316 return cxstring::createRef("CXXCatchStmt");
4317 case CXCursor_CXXTryStmt:
4318 return cxstring::createRef("CXXTryStmt");
4319 case CXCursor_CXXForRangeStmt:
4320 return cxstring::createRef("CXXForRangeStmt");
4321 case CXCursor_SEHTryStmt:
4322 return cxstring::createRef("SEHTryStmt");
4323 case CXCursor_SEHExceptStmt:
4324 return cxstring::createRef("SEHExceptStmt");
4325 case CXCursor_SEHFinallyStmt:
4326 return cxstring::createRef("SEHFinallyStmt");
4327 case CXCursor_SEHLeaveStmt:
4328 return cxstring::createRef("SEHLeaveStmt");
4329 case CXCursor_NullStmt:
4330 return cxstring::createRef("NullStmt");
4331 case CXCursor_InvalidFile:
4332 return cxstring::createRef("InvalidFile");
4333 case CXCursor_InvalidCode:
4334 return cxstring::createRef("InvalidCode");
4335 case CXCursor_NoDeclFound:
4336 return cxstring::createRef("NoDeclFound");
4337 case CXCursor_NotImplemented:
4338 return cxstring::createRef("NotImplemented");
4339 case CXCursor_TranslationUnit:
4340 return cxstring::createRef("TranslationUnit");
4341 case CXCursor_UnexposedAttr:
4342 return cxstring::createRef("UnexposedAttr");
4343 case CXCursor_IBActionAttr:
4344 return cxstring::createRef("attribute(ibaction)");
4345 case CXCursor_IBOutletAttr:
4346 return cxstring::createRef("attribute(iboutlet)");
4347 case CXCursor_IBOutletCollectionAttr:
4348 return cxstring::createRef("attribute(iboutletcollection)");
4349 case CXCursor_CXXFinalAttr:
4350 return cxstring::createRef("attribute(final)");
4351 case CXCursor_CXXOverrideAttr:
4352 return cxstring::createRef("attribute(override)");
4353 case CXCursor_AnnotateAttr:
4354 return cxstring::createRef("attribute(annotate)");
4355 case CXCursor_AsmLabelAttr:
4356 return cxstring::createRef("asm label");
4357 case CXCursor_PackedAttr:
4358 return cxstring::createRef("attribute(packed)");
4359 case CXCursor_PureAttr:
4360 return cxstring::createRef("attribute(pure)");
4361 case CXCursor_ConstAttr:
4362 return cxstring::createRef("attribute(const)");
4363 case CXCursor_NoDuplicateAttr:
4364 return cxstring::createRef("attribute(noduplicate)");
4365 case CXCursor_CUDAConstantAttr:
4366 return cxstring::createRef("attribute(constant)");
4367 case CXCursor_CUDADeviceAttr:
4368 return cxstring::createRef("attribute(device)");
4369 case CXCursor_CUDAGlobalAttr:
4370 return cxstring::createRef("attribute(global)");
4371 case CXCursor_CUDAHostAttr:
4372 return cxstring::createRef("attribute(host)");
4373 case CXCursor_CUDASharedAttr:
4374 return cxstring::createRef("attribute(shared)");
4375 case CXCursor_VisibilityAttr:
4376 return cxstring::createRef("attribute(visibility)");
4377 case CXCursor_PreprocessingDirective:
4378 return cxstring::createRef("preprocessing directive");
4379 case CXCursor_MacroDefinition:
4380 return cxstring::createRef("macro definition");
4381 case CXCursor_MacroExpansion:
4382 return cxstring::createRef("macro expansion");
4383 case CXCursor_InclusionDirective:
4384 return cxstring::createRef("inclusion directive");
4385 case CXCursor_Namespace:
4386 return cxstring::createRef("Namespace");
4387 case CXCursor_LinkageSpec:
4388 return cxstring::createRef("LinkageSpec");
4389 case CXCursor_CXXBaseSpecifier:
4390 return cxstring::createRef("C++ base class specifier");
4391 case CXCursor_Constructor:
4392 return cxstring::createRef("CXXConstructor");
4393 case CXCursor_Destructor:
4394 return cxstring::createRef("CXXDestructor");
4395 case CXCursor_ConversionFunction:
4396 return cxstring::createRef("CXXConversion");
4397 case CXCursor_TemplateTypeParameter:
4398 return cxstring::createRef("TemplateTypeParameter");
4399 case CXCursor_NonTypeTemplateParameter:
4400 return cxstring::createRef("NonTypeTemplateParameter");
4401 case CXCursor_TemplateTemplateParameter:
4402 return cxstring::createRef("TemplateTemplateParameter");
4403 case CXCursor_FunctionTemplate:
4404 return cxstring::createRef("FunctionTemplate");
4405 case CXCursor_ClassTemplate:
4406 return cxstring::createRef("ClassTemplate");
4407 case CXCursor_ClassTemplatePartialSpecialization:
4408 return cxstring::createRef("ClassTemplatePartialSpecialization");
4409 case CXCursor_NamespaceAlias:
4410 return cxstring::createRef("NamespaceAlias");
4411 case CXCursor_UsingDirective:
4412 return cxstring::createRef("UsingDirective");
4413 case CXCursor_UsingDeclaration:
4414 return cxstring::createRef("UsingDeclaration");
4415 case CXCursor_TypeAliasDecl:
4416 return cxstring::createRef("TypeAliasDecl");
4417 case CXCursor_ObjCSynthesizeDecl:
4418 return cxstring::createRef("ObjCSynthesizeDecl");
4419 case CXCursor_ObjCDynamicDecl:
4420 return cxstring::createRef("ObjCDynamicDecl");
4421 case CXCursor_CXXAccessSpecifier:
4422 return cxstring::createRef("CXXAccessSpecifier");
4423 case CXCursor_ModuleImportDecl:
4424 return cxstring::createRef("ModuleImport");
4425 case CXCursor_OMPParallelDirective:
4426 return cxstring::createRef("OMPParallelDirective");
4427 case CXCursor_OMPSimdDirective:
4428 return cxstring::createRef("OMPSimdDirective");
4429 case CXCursor_OMPForDirective:
4430 return cxstring::createRef("OMPForDirective");
4431 case CXCursor_OMPForSimdDirective:
4432 return cxstring::createRef("OMPForSimdDirective");
4433 case CXCursor_OMPSectionsDirective:
4434 return cxstring::createRef("OMPSectionsDirective");
4435 case CXCursor_OMPSectionDirective:
4436 return cxstring::createRef("OMPSectionDirective");
4437 case CXCursor_OMPSingleDirective:
4438 return cxstring::createRef("OMPSingleDirective");
4439 case CXCursor_OMPMasterDirective:
4440 return cxstring::createRef("OMPMasterDirective");
4441 case CXCursor_OMPCriticalDirective:
4442 return cxstring::createRef("OMPCriticalDirective");
4443 case CXCursor_OMPParallelForDirective:
4444 return cxstring::createRef("OMPParallelForDirective");
4445 case CXCursor_OMPParallelForSimdDirective:
4446 return cxstring::createRef("OMPParallelForSimdDirective");
4447 case CXCursor_OMPParallelSectionsDirective:
4448 return cxstring::createRef("OMPParallelSectionsDirective");
4449 case CXCursor_OMPTaskDirective:
4450 return cxstring::createRef("OMPTaskDirective");
4451 case CXCursor_OMPTaskyieldDirective:
4452 return cxstring::createRef("OMPTaskyieldDirective");
4453 case CXCursor_OMPBarrierDirective:
4454 return cxstring::createRef("OMPBarrierDirective");
4455 case CXCursor_OMPTaskwaitDirective:
4456 return cxstring::createRef("OMPTaskwaitDirective");
4457 case CXCursor_OMPTaskgroupDirective:
4458 return cxstring::createRef("OMPTaskgroupDirective");
4459 case CXCursor_OMPFlushDirective:
4460 return cxstring::createRef("OMPFlushDirective");
4461 case CXCursor_OMPOrderedDirective:
4462 return cxstring::createRef("OMPOrderedDirective");
4463 case CXCursor_OMPAtomicDirective:
4464 return cxstring::createRef("OMPAtomicDirective");
4465 case CXCursor_OMPTargetDirective:
4466 return cxstring::createRef("OMPTargetDirective");
4467 case CXCursor_OMPTargetDataDirective:
4468 return cxstring::createRef("OMPTargetDataDirective");
4469 case CXCursor_OMPTeamsDirective:
4470 return cxstring::createRef("OMPTeamsDirective");
4471 case CXCursor_OMPCancellationPointDirective:
4472 return cxstring::createRef("OMPCancellationPointDirective");
4473 case CXCursor_OMPCancelDirective:
4474 return cxstring::createRef("OMPCancelDirective");
4475 case CXCursor_OMPTaskLoopDirective:
4476 return cxstring::createRef("OMPTaskLoopDirective");
4477 case CXCursor_OverloadCandidate:
4478 return cxstring::createRef("OverloadCandidate");
4479 case CXCursor_TypeAliasTemplateDecl:
4480 return cxstring::createRef("TypeAliasTemplateDecl");
4483 llvm_unreachable("Unhandled CXCursorKind");
4486 struct GetCursorData {
4487 SourceLocation TokenBeginLoc;
4488 bool PointsAtMacroArgExpansion;
4489 bool VisitedObjCPropertyImplDecl;
4490 SourceLocation VisitedDeclaratorDeclStartLoc;
4491 CXCursor &BestCursor;
4493 GetCursorData(SourceManager &SM,
4494 SourceLocation tokenBegin, CXCursor &outputCursor)
4495 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4496 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4497 VisitedObjCPropertyImplDecl = false;
4501 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4503 CXClientData client_data) {
4504 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4505 CXCursor *BestCursor = &Data->BestCursor;
4507 // If we point inside a macro argument we should provide info of what the
4508 // token is so use the actual cursor, don't replace it with a macro expansion
4510 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4511 return CXChildVisit_Recurse;
4513 if (clang_isDeclaration(cursor.kind)) {
4514 // Avoid having the implicit methods override the property decls.
4515 if (const ObjCMethodDecl *MD
4516 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4517 if (MD->isImplicit())
4518 return CXChildVisit_Break;
4520 } else if (const ObjCInterfaceDecl *ID
4521 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4522 // Check that when we have multiple @class references in the same line,
4523 // that later ones do not override the previous ones.
4526 // source ranges for both start at '@', so 'Bar' will end up overriding
4527 // 'Foo' even though the cursor location was at 'Foo'.
4528 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4529 BestCursor->kind == CXCursor_ObjCClassRef)
4530 if (const ObjCInterfaceDecl *PrevID
4531 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4533 !PrevID->isThisDeclarationADefinition() &&
4534 !ID->isThisDeclarationADefinition())
4535 return CXChildVisit_Break;
4538 } else if (const DeclaratorDecl *DD
4539 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4540 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4541 // Check that when we have multiple declarators in the same line,
4542 // that later ones do not override the previous ones.
4545 // source ranges for both start at 'int', so 'Bar' will end up overriding
4546 // 'Foo' even though the cursor location was at 'Foo'.
4547 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4548 return CXChildVisit_Break;
4549 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4551 } else if (const ObjCPropertyImplDecl *PropImp
4552 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4554 // Check that when we have multiple @synthesize in the same line,
4555 // that later ones do not override the previous ones.
4557 // @synthesize Foo, Bar;
4558 // source ranges for both start at '@', so 'Bar' will end up overriding
4559 // 'Foo' even though the cursor location was at 'Foo'.
4560 if (Data->VisitedObjCPropertyImplDecl)
4561 return CXChildVisit_Break;
4562 Data->VisitedObjCPropertyImplDecl = true;
4566 if (clang_isExpression(cursor.kind) &&
4567 clang_isDeclaration(BestCursor->kind)) {
4568 if (const Decl *D = getCursorDecl(*BestCursor)) {
4569 // Avoid having the cursor of an expression replace the declaration cursor
4570 // when the expression source range overlaps the declaration range.
4571 // This can happen for C++ constructor expressions whose range generally
4572 // include the variable declaration, e.g.:
4573 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4574 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4575 D->getLocation() == Data->TokenBeginLoc)
4576 return CXChildVisit_Break;
4580 // If our current best cursor is the construction of a temporary object,
4581 // don't replace that cursor with a type reference, because we want
4582 // clang_getCursor() to point at the constructor.
4583 if (clang_isExpression(BestCursor->kind) &&
4584 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4585 cursor.kind == CXCursor_TypeRef) {
4586 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4587 // as having the actual point on the type reference.
4588 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4589 return CXChildVisit_Recurse;
4592 // If we already have an Objective-C superclass reference, don't
4593 // update it further.
4594 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4595 return CXChildVisit_Break;
4597 *BestCursor = cursor;
4598 return CXChildVisit_Recurse;
4601 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4602 if (isNotUsableTU(TU)) {
4604 return clang_getNullCursor();
4607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4608 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4610 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4611 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4615 unsigned SearchLine, SearchColumn;
4617 unsigned ResultLine, ResultColumn;
4618 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4619 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4620 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4622 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4624 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4625 &ResultColumn, nullptr);
4626 SearchFileName = clang_getFileName(SearchFile);
4627 ResultFileName = clang_getFileName(ResultFile);
4628 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4629 USR = clang_getCursorUSR(Result);
4630 *Log << llvm::format("(%s:%d:%d) = %s",
4631 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4632 clang_getCString(KindSpelling))
4633 << llvm::format("(%s:%d:%d):%s%s",
4634 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4635 clang_getCString(USR), IsDef);
4636 clang_disposeString(SearchFileName);
4637 clang_disposeString(ResultFileName);
4638 clang_disposeString(KindSpelling);
4639 clang_disposeString(USR);
4641 CXCursor Definition = clang_getCursorDefinition(Result);
4642 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4643 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4644 CXString DefinitionKindSpelling
4645 = clang_getCursorKindSpelling(Definition.kind);
4646 CXFile DefinitionFile;
4647 unsigned DefinitionLine, DefinitionColumn;
4648 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
4649 &DefinitionLine, &DefinitionColumn, nullptr);
4650 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
4651 *Log << llvm::format(" -> %s(%s:%d:%d)",
4652 clang_getCString(DefinitionKindSpelling),
4653 clang_getCString(DefinitionFileName),
4654 DefinitionLine, DefinitionColumn);
4655 clang_disposeString(DefinitionFileName);
4656 clang_disposeString(DefinitionKindSpelling);
4663 CXCursor clang_getNullCursor(void) {
4664 return MakeCXCursorInvalid(CXCursor_InvalidFile);
4667 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
4668 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
4669 // can't set consistently. For example, when visiting a DeclStmt we will set
4670 // it but we don't set it on the result of clang_getCursorDefinition for
4671 // a reference of the same declaration.
4672 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
4673 // when visiting a DeclStmt currently, the AST should be enhanced to be able
4674 // to provide that kind of info.
4675 if (clang_isDeclaration(X.kind))
4676 X.data[1] = nullptr;
4677 if (clang_isDeclaration(Y.kind))
4678 Y.data[1] = nullptr;
4683 unsigned clang_hashCursor(CXCursor C) {
4685 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
4688 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
4689 std::make_pair(C.kind, C.data[Index]));
4692 unsigned clang_isInvalid(enum CXCursorKind K) {
4693 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
4696 unsigned clang_isDeclaration(enum CXCursorKind K) {
4697 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
4698 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
4701 unsigned clang_isReference(enum CXCursorKind K) {
4702 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
4705 unsigned clang_isExpression(enum CXCursorKind K) {
4706 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
4709 unsigned clang_isStatement(enum CXCursorKind K) {
4710 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
4713 unsigned clang_isAttribute(enum CXCursorKind K) {
4714 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
4717 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
4718 return K == CXCursor_TranslationUnit;
4721 unsigned clang_isPreprocessing(enum CXCursorKind K) {
4722 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
4725 unsigned clang_isUnexposed(enum CXCursorKind K) {
4727 case CXCursor_UnexposedDecl:
4728 case CXCursor_UnexposedExpr:
4729 case CXCursor_UnexposedStmt:
4730 case CXCursor_UnexposedAttr:
4737 CXCursorKind clang_getCursorKind(CXCursor C) {
4741 CXSourceLocation clang_getCursorLocation(CXCursor C) {
4742 if (clang_isReference(C.kind)) {
4744 case CXCursor_ObjCSuperClassRef: {
4745 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4746 = getCursorObjCSuperClassRef(C);
4747 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4750 case CXCursor_ObjCProtocolRef: {
4751 std::pair<const ObjCProtocolDecl *, SourceLocation> P
4752 = getCursorObjCProtocolRef(C);
4753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4756 case CXCursor_ObjCClassRef: {
4757 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4758 = getCursorObjCClassRef(C);
4759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4762 case CXCursor_TypeRef: {
4763 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
4764 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4767 case CXCursor_TemplateRef: {
4768 std::pair<const TemplateDecl *, SourceLocation> P =
4769 getCursorTemplateRef(C);
4770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4773 case CXCursor_NamespaceRef: {
4774 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
4775 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4778 case CXCursor_MemberRef: {
4779 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4780 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4783 case CXCursor_VariableRef: {
4784 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4788 case CXCursor_CXXBaseSpecifier: {
4789 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4791 return clang_getNullLocation();
4793 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4794 return cxloc::translateSourceLocation(getCursorContext(C),
4795 TSInfo->getTypeLoc().getBeginLoc());
4797 return cxloc::translateSourceLocation(getCursorContext(C),
4798 BaseSpec->getLocStart());
4801 case CXCursor_LabelRef: {
4802 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4803 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4806 case CXCursor_OverloadedDeclRef:
4807 return cxloc::translateSourceLocation(getCursorContext(C),
4808 getCursorOverloadedDeclRef(C).second);
4811 // FIXME: Need a way to enumerate all non-reference cases.
4812 llvm_unreachable("Missed a reference kind");
4816 if (clang_isExpression(C.kind))
4817 return cxloc::translateSourceLocation(getCursorContext(C),
4818 getLocationFromExpr(getCursorExpr(C)));
4820 if (clang_isStatement(C.kind))
4821 return cxloc::translateSourceLocation(getCursorContext(C),
4822 getCursorStmt(C)->getLocStart());
4824 if (C.kind == CXCursor_PreprocessingDirective) {
4825 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4826 return cxloc::translateSourceLocation(getCursorContext(C), L);
4829 if (C.kind == CXCursor_MacroExpansion) {
4831 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4832 return cxloc::translateSourceLocation(getCursorContext(C), L);
4835 if (C.kind == CXCursor_MacroDefinition) {
4836 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4837 return cxloc::translateSourceLocation(getCursorContext(C), L);
4840 if (C.kind == CXCursor_InclusionDirective) {
4842 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4843 return cxloc::translateSourceLocation(getCursorContext(C), L);
4846 if (clang_isAttribute(C.kind)) {
4848 = cxcursor::getCursorAttr(C)->getLocation();
4849 return cxloc::translateSourceLocation(getCursorContext(C), L);
4852 if (!clang_isDeclaration(C.kind))
4853 return clang_getNullLocation();
4855 const Decl *D = getCursorDecl(C);
4857 return clang_getNullLocation();
4859 SourceLocation Loc = D->getLocation();
4860 // FIXME: Multiple variables declared in a single declaration
4861 // currently lack the information needed to correctly determine their
4862 // ranges when accounting for the type-specifier. We use context
4863 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4864 // and if so, whether it is the first decl.
4865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4866 if (!cxcursor::isFirstInDeclGroup(C))
4867 Loc = VD->getLocation();
4870 // For ObjC methods, give the start location of the method name.
4871 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4872 Loc = MD->getSelectorStartLoc();
4874 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4879 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4882 // Guard against an invalid SourceLocation, or we may assert in one
4883 // of the following calls.
4884 if (SLoc.isInvalid())
4885 return clang_getNullCursor();
4887 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4889 // Translate the given source location to make it point at the beginning of
4890 // the token under the cursor.
4891 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4892 CXXUnit->getASTContext().getLangOpts());
4894 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4895 if (SLoc.isValid()) {
4896 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4897 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4898 /*VisitPreprocessorLast=*/true,
4899 /*VisitIncludedEntities=*/false,
4900 SourceLocation(SLoc));
4901 CursorVis.visitFileRegion();
4907 static SourceRange getRawCursorExtent(CXCursor C) {
4908 if (clang_isReference(C.kind)) {
4910 case CXCursor_ObjCSuperClassRef:
4911 return getCursorObjCSuperClassRef(C).second;
4913 case CXCursor_ObjCProtocolRef:
4914 return getCursorObjCProtocolRef(C).second;
4916 case CXCursor_ObjCClassRef:
4917 return getCursorObjCClassRef(C).second;
4919 case CXCursor_TypeRef:
4920 return getCursorTypeRef(C).second;
4922 case CXCursor_TemplateRef:
4923 return getCursorTemplateRef(C).second;
4925 case CXCursor_NamespaceRef:
4926 return getCursorNamespaceRef(C).second;
4928 case CXCursor_MemberRef:
4929 return getCursorMemberRef(C).second;
4931 case CXCursor_CXXBaseSpecifier:
4932 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4934 case CXCursor_LabelRef:
4935 return getCursorLabelRef(C).second;
4937 case CXCursor_OverloadedDeclRef:
4938 return getCursorOverloadedDeclRef(C).second;
4940 case CXCursor_VariableRef:
4941 return getCursorVariableRef(C).second;
4944 // FIXME: Need a way to enumerate all non-reference cases.
4945 llvm_unreachable("Missed a reference kind");
4949 if (clang_isExpression(C.kind))
4950 return getCursorExpr(C)->getSourceRange();
4952 if (clang_isStatement(C.kind))
4953 return getCursorStmt(C)->getSourceRange();
4955 if (clang_isAttribute(C.kind))
4956 return getCursorAttr(C)->getRange();
4958 if (C.kind == CXCursor_PreprocessingDirective)
4959 return cxcursor::getCursorPreprocessingDirective(C);
4961 if (C.kind == CXCursor_MacroExpansion) {
4962 ASTUnit *TU = getCursorASTUnit(C);
4963 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4964 return TU->mapRangeFromPreamble(Range);
4967 if (C.kind == CXCursor_MacroDefinition) {
4968 ASTUnit *TU = getCursorASTUnit(C);
4969 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4970 return TU->mapRangeFromPreamble(Range);
4973 if (C.kind == CXCursor_InclusionDirective) {
4974 ASTUnit *TU = getCursorASTUnit(C);
4975 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4976 return TU->mapRangeFromPreamble(Range);
4979 if (C.kind == CXCursor_TranslationUnit) {
4980 ASTUnit *TU = getCursorASTUnit(C);
4981 FileID MainID = TU->getSourceManager().getMainFileID();
4982 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4983 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4984 return SourceRange(Start, End);
4987 if (clang_isDeclaration(C.kind)) {
4988 const Decl *D = cxcursor::getCursorDecl(C);
4990 return SourceRange();
4992 SourceRange R = D->getSourceRange();
4993 // FIXME: Multiple variables declared in a single declaration
4994 // currently lack the information needed to correctly determine their
4995 // ranges when accounting for the type-specifier. We use context
4996 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4997 // and if so, whether it is the first decl.
4998 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4999 if (!cxcursor::isFirstInDeclGroup(C))
5000 R.setBegin(VD->getLocation());
5004 return SourceRange();
5007 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
5008 /// the decl-specifier-seq for declarations.
5009 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5010 if (clang_isDeclaration(C.kind)) {
5011 const Decl *D = cxcursor::getCursorDecl(C);
5013 return SourceRange();
5015 SourceRange R = D->getSourceRange();
5017 // Adjust the start of the location for declarations preceded by
5018 // declaration specifiers.
5019 SourceLocation StartLoc;
5020 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5021 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5022 StartLoc = TI->getTypeLoc().getLocStart();
5023 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
5024 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5025 StartLoc = TI->getTypeLoc().getLocStart();
5028 if (StartLoc.isValid() && R.getBegin().isValid() &&
5029 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5030 R.setBegin(StartLoc);
5032 // FIXME: Multiple variables declared in a single declaration
5033 // currently lack the information needed to correctly determine their
5034 // ranges when accounting for the type-specifier. We use context
5035 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5036 // and if so, whether it is the first decl.
5037 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5038 if (!cxcursor::isFirstInDeclGroup(C))
5039 R.setBegin(VD->getLocation());
5045 return getRawCursorExtent(C);
5050 CXSourceRange clang_getCursorExtent(CXCursor C) {
5051 SourceRange R = getRawCursorExtent(C);
5053 return clang_getNullRange();
5055 return cxloc::translateSourceRange(getCursorContext(C), R);
5058 CXCursor clang_getCursorReferenced(CXCursor C) {
5059 if (clang_isInvalid(C.kind))
5060 return clang_getNullCursor();
5062 CXTranslationUnit tu = getCursorTU(C);
5063 if (clang_isDeclaration(C.kind)) {
5064 const Decl *D = getCursorDecl(C);
5066 return clang_getNullCursor();
5067 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5068 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
5069 if (const ObjCPropertyImplDecl *PropImpl =
5070 dyn_cast<ObjCPropertyImplDecl>(D))
5071 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5072 return MakeCXCursor(Property, tu);
5077 if (clang_isExpression(C.kind)) {
5078 const Expr *E = getCursorExpr(C);
5079 const Decl *D = getDeclFromExpr(E);
5081 CXCursor declCursor = MakeCXCursor(D, tu);
5082 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5087 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
5088 return MakeCursorOverloadedDeclRef(Ovl, tu);
5090 return clang_getNullCursor();
5093 if (clang_isStatement(C.kind)) {
5094 const Stmt *S = getCursorStmt(C);
5095 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
5096 if (LabelDecl *label = Goto->getLabel())
5097 if (LabelStmt *labelS = label->getStmt())
5098 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5100 return clang_getNullCursor();
5103 if (C.kind == CXCursor_MacroExpansion) {
5104 if (const MacroDefinitionRecord *Def =
5105 getCursorMacroExpansion(C).getDefinition())
5106 return MakeMacroDefinitionCursor(Def, tu);
5109 if (!clang_isReference(C.kind))
5110 return clang_getNullCursor();
5113 case CXCursor_ObjCSuperClassRef:
5114 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5116 case CXCursor_ObjCProtocolRef: {
5117 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5118 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5119 return MakeCXCursor(Def, tu);
5121 return MakeCXCursor(Prot, tu);
5124 case CXCursor_ObjCClassRef: {
5125 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5126 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5127 return MakeCXCursor(Def, tu);
5129 return MakeCXCursor(Class, tu);
5132 case CXCursor_TypeRef:
5133 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5135 case CXCursor_TemplateRef:
5136 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5138 case CXCursor_NamespaceRef:
5139 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5141 case CXCursor_MemberRef:
5142 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5144 case CXCursor_CXXBaseSpecifier: {
5145 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5146 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5150 case CXCursor_LabelRef:
5151 // FIXME: We end up faking the "parent" declaration here because we
5152 // don't want to make CXCursor larger.
5153 return MakeCXCursor(getCursorLabelRef(C).first,
5154 cxtu::getASTUnit(tu)->getASTContext()
5155 .getTranslationUnitDecl(),
5158 case CXCursor_OverloadedDeclRef:
5161 case CXCursor_VariableRef:
5162 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5165 // We would prefer to enumerate all non-reference cursor kinds here.
5166 llvm_unreachable("Unhandled reference cursor kind");
5170 CXCursor clang_getCursorDefinition(CXCursor C) {
5171 if (clang_isInvalid(C.kind))
5172 return clang_getNullCursor();
5174 CXTranslationUnit TU = getCursorTU(C);
5176 bool WasReference = false;
5177 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5178 C = clang_getCursorReferenced(C);
5179 WasReference = true;
5182 if (C.kind == CXCursor_MacroExpansion)
5183 return clang_getCursorReferenced(C);
5185 if (!clang_isDeclaration(C.kind))
5186 return clang_getNullCursor();
5188 const Decl *D = getCursorDecl(C);
5190 return clang_getNullCursor();
5192 switch (D->getKind()) {
5193 // Declaration kinds that don't really separate the notions of
5194 // declaration and definition.
5195 case Decl::Namespace:
5197 case Decl::TypeAlias:
5198 case Decl::TypeAliasTemplate:
5199 case Decl::TemplateTypeParm:
5200 case Decl::EnumConstant:
5202 case Decl::MSProperty:
5203 case Decl::IndirectField:
5204 case Decl::ObjCIvar:
5205 case Decl::ObjCAtDefsField:
5206 case Decl::ImplicitParam:
5208 case Decl::NonTypeTemplateParm:
5209 case Decl::TemplateTemplateParm:
5210 case Decl::ObjCCategoryImpl:
5211 case Decl::ObjCImplementation:
5212 case Decl::AccessSpec:
5213 case Decl::LinkageSpec:
5214 case Decl::ObjCPropertyImpl:
5215 case Decl::FileScopeAsm:
5216 case Decl::StaticAssert:
5218 case Decl::Captured:
5219 case Decl::Label: // FIXME: Is this right??
5220 case Decl::ClassScopeFunctionSpecialization:
5222 case Decl::OMPThreadPrivate:
5223 case Decl::ObjCTypeParam:
5224 case Decl::BuiltinTemplate:
5227 // Declaration kinds that don't make any sense here, but are
5228 // nonetheless harmless.
5230 case Decl::TranslationUnit:
5231 case Decl::ExternCContext:
5234 // Declaration kinds for which the definition is not resolvable.
5235 case Decl::UnresolvedUsingTypename:
5236 case Decl::UnresolvedUsingValue:
5239 case Decl::UsingDirective:
5240 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5243 case Decl::NamespaceAlias:
5244 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5248 case Decl::CXXRecord:
5249 case Decl::ClassTemplateSpecialization:
5250 case Decl::ClassTemplatePartialSpecialization:
5251 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5252 return MakeCXCursor(Def, TU);
5253 return clang_getNullCursor();
5255 case Decl::Function:
5256 case Decl::CXXMethod:
5257 case Decl::CXXConstructor:
5258 case Decl::CXXDestructor:
5259 case Decl::CXXConversion: {
5260 const FunctionDecl *Def = nullptr;
5261 if (cast<FunctionDecl>(D)->getBody(Def))
5262 return MakeCXCursor(Def, TU);
5263 return clang_getNullCursor();
5267 case Decl::VarTemplateSpecialization:
5268 case Decl::VarTemplatePartialSpecialization: {
5269 // Ask the variable if it has a definition.
5270 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5271 return MakeCXCursor(Def, TU);
5272 return clang_getNullCursor();
5275 case Decl::FunctionTemplate: {
5276 const FunctionDecl *Def = nullptr;
5277 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5278 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5279 return clang_getNullCursor();
5282 case Decl::ClassTemplate: {
5283 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5285 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5287 return clang_getNullCursor();
5290 case Decl::VarTemplate: {
5292 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5293 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5294 return clang_getNullCursor();
5298 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5299 D->getLocation(), TU);
5301 case Decl::UsingShadow:
5302 return clang_getCursorDefinition(
5303 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5306 case Decl::ObjCMethod: {
5307 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5308 if (Method->isThisDeclarationADefinition())
5311 // Dig out the method definition in the associated
5312 // @implementation, if we have it.
5313 // FIXME: The ASTs should make finding the definition easier.
5314 if (const ObjCInterfaceDecl *Class
5315 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5316 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5317 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5318 Method->isInstanceMethod()))
5319 if (Def->isThisDeclarationADefinition())
5320 return MakeCXCursor(Def, TU);
5322 return clang_getNullCursor();
5325 case Decl::ObjCCategory:
5326 if (ObjCCategoryImplDecl *Impl
5327 = cast<ObjCCategoryDecl>(D)->getImplementation())
5328 return MakeCXCursor(Impl, TU);
5329 return clang_getNullCursor();
5331 case Decl::ObjCProtocol:
5332 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5333 return MakeCXCursor(Def, TU);
5334 return clang_getNullCursor();
5336 case Decl::ObjCInterface: {
5337 // There are two notions of a "definition" for an Objective-C
5338 // class: the interface and its implementation. When we resolved a
5339 // reference to an Objective-C class, produce the @interface as
5340 // the definition; when we were provided with the interface,
5341 // produce the @implementation as the definition.
5342 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5344 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5345 return MakeCXCursor(Def, TU);
5346 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5347 return MakeCXCursor(Impl, TU);
5348 return clang_getNullCursor();
5351 case Decl::ObjCProperty:
5352 // FIXME: We don't really know where to find the
5353 // ObjCPropertyImplDecls that implement this property.
5354 return clang_getNullCursor();
5356 case Decl::ObjCCompatibleAlias:
5357 if (const ObjCInterfaceDecl *Class
5358 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5359 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5360 return MakeCXCursor(Def, TU);
5362 return clang_getNullCursor();
5365 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5366 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5367 return clang_getNullCursor();
5369 case Decl::FriendTemplate:
5370 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5371 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5372 return clang_getNullCursor();
5375 return clang_getNullCursor();
5378 unsigned clang_isCursorDefinition(CXCursor C) {
5379 if (!clang_isDeclaration(C.kind))
5382 return clang_getCursorDefinition(C) == C;
5385 CXCursor clang_getCanonicalCursor(CXCursor C) {
5386 if (!clang_isDeclaration(C.kind))
5389 if (const Decl *D = getCursorDecl(C)) {
5390 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5391 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5392 return MakeCXCursor(CatD, getCursorTU(C));
5394 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5395 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5396 return MakeCXCursor(IFD, getCursorTU(C));
5398 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5404 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5405 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5408 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5409 if (C.kind != CXCursor_OverloadedDeclRef)
5412 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5413 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5414 return E->getNumDecls();
5416 if (OverloadedTemplateStorage *S
5417 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5420 const Decl *D = Storage.get<const Decl *>();
5421 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5422 return Using->shadow_size();
5427 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5428 if (cursor.kind != CXCursor_OverloadedDeclRef)
5429 return clang_getNullCursor();
5431 if (index >= clang_getNumOverloadedDecls(cursor))
5432 return clang_getNullCursor();
5434 CXTranslationUnit TU = getCursorTU(cursor);
5435 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5436 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5437 return MakeCXCursor(E->decls_begin()[index], TU);
5439 if (OverloadedTemplateStorage *S
5440 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5441 return MakeCXCursor(S->begin()[index], TU);
5443 const Decl *D = Storage.get<const Decl *>();
5444 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5445 // FIXME: This is, unfortunately, linear time.
5446 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5447 std::advance(Pos, index);
5448 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5451 return clang_getNullCursor();
5454 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5455 const char **startBuf,
5456 const char **endBuf,
5457 unsigned *startLine,
5458 unsigned *startColumn,
5460 unsigned *endColumn) {
5461 assert(getCursorDecl(C) && "CXCursor has null decl");
5462 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5463 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5465 SourceManager &SM = FD->getASTContext().getSourceManager();
5466 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5467 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5468 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5469 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5470 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5471 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5475 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5476 unsigned PieceIndex) {
5477 RefNamePieces Pieces;
5480 case CXCursor_MemberRefExpr:
5481 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5482 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5483 E->getQualifierLoc().getSourceRange());
5486 case CXCursor_DeclRefExpr:
5487 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
5488 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
5489 E->getQualifierLoc().getSourceRange(),
5490 E->getOptionalExplicitTemplateArgs());
5493 case CXCursor_CallExpr:
5494 if (const CXXOperatorCallExpr *OCE =
5495 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5496 const Expr *Callee = OCE->getCallee();
5497 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5498 Callee = ICE->getSubExpr();
5500 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5501 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5502 DRE->getQualifierLoc().getSourceRange());
5510 if (Pieces.empty()) {
5511 if (PieceIndex == 0)
5512 return clang_getCursorExtent(C);
5513 } else if (PieceIndex < Pieces.size()) {
5514 SourceRange R = Pieces[PieceIndex];
5516 return cxloc::translateSourceRange(getCursorContext(C), R);
5519 return clang_getNullRange();
5522 void clang_enableStackTraces(void) {
5523 llvm::sys::PrintStackTraceOnErrorSignal();
5526 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5527 unsigned stack_size) {
5528 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5531 } // end: extern "C"
5533 //===----------------------------------------------------------------------===//
5534 // Token-based Operations.
5535 //===----------------------------------------------------------------------===//
5538 * int_data[0]: a CXTokenKind
5539 * int_data[1]: starting token location
5540 * int_data[2]: token length
5541 * int_data[3]: reserved
5542 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5547 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5548 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5551 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5552 switch (clang_getTokenKind(CXTok)) {
5553 case CXToken_Identifier:
5554 case CXToken_Keyword:
5555 // We know we have an IdentifierInfo*, so use that.
5556 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5559 case CXToken_Literal: {
5560 // We have stashed the starting pointer in the ptr_data field. Use it.
5561 const char *Text = static_cast<const char *>(CXTok.ptr_data);
5562 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5565 case CXToken_Punctuation:
5566 case CXToken_Comment:
5570 if (isNotUsableTU(TU)) {
5572 return cxstring::createEmpty();
5575 // We have to find the starting buffer pointer the hard way, by
5576 // deconstructing the source location.
5577 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5579 return cxstring::createEmpty();
5581 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5582 std::pair<FileID, unsigned> LocInfo
5583 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5584 bool Invalid = false;
5586 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5588 return cxstring::createEmpty();
5590 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5593 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5594 if (isNotUsableTU(TU)) {
5596 return clang_getNullLocation();
5599 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5601 return clang_getNullLocation();
5603 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5604 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5607 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5608 if (isNotUsableTU(TU)) {
5610 return clang_getNullRange();
5613 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5615 return clang_getNullRange();
5617 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5618 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5621 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5622 SmallVectorImpl<CXToken> &CXTokens) {
5623 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5624 std::pair<FileID, unsigned> BeginLocInfo
5625 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5626 std::pair<FileID, unsigned> EndLocInfo
5627 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5629 // Cannot tokenize across files.
5630 if (BeginLocInfo.first != EndLocInfo.first)
5634 bool Invalid = false;
5636 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5640 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5641 CXXUnit->getASTContext().getLangOpts(),
5642 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
5643 Lex.SetCommentRetentionState(true);
5645 // Lex tokens until we hit the end of the range.
5646 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
5648 bool previousWasAt = false;
5650 // Lex the next token
5651 Lex.LexFromRawLexer(Tok);
5652 if (Tok.is(tok::eof))
5655 // Initialize the CXToken.
5659 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
5660 CXTok.int_data[2] = Tok.getLength();
5661 CXTok.int_data[3] = 0;
5663 // - Kind-specific fields
5664 if (Tok.isLiteral()) {
5665 CXTok.int_data[0] = CXToken_Literal;
5666 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
5667 } else if (Tok.is(tok::raw_identifier)) {
5668 // Lookup the identifier to determine whether we have a keyword.
5670 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
5672 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
5673 CXTok.int_data[0] = CXToken_Keyword;
5676 CXTok.int_data[0] = Tok.is(tok::identifier)
5677 ? CXToken_Identifier
5680 CXTok.ptr_data = II;
5681 } else if (Tok.is(tok::comment)) {
5682 CXTok.int_data[0] = CXToken_Comment;
5683 CXTok.ptr_data = nullptr;
5685 CXTok.int_data[0] = CXToken_Punctuation;
5686 CXTok.ptr_data = nullptr;
5688 CXTokens.push_back(CXTok);
5689 previousWasAt = Tok.is(tok::at);
5690 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
5693 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
5694 CXToken **Tokens, unsigned *NumTokens) {
5696 *Log << TU << ' ' << Range;
5704 if (isNotUsableTU(TU)) {
5709 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5710 if (!CXXUnit || !Tokens || !NumTokens)
5713 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5715 SourceRange R = cxloc::translateCXSourceRange(Range);
5719 SmallVector<CXToken, 32> CXTokens;
5720 getTokens(CXXUnit, R, CXTokens);
5722 if (CXTokens.empty())
5725 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
5726 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
5727 *NumTokens = CXTokens.size();
5730 void clang_disposeTokens(CXTranslationUnit TU,
5731 CXToken *Tokens, unsigned NumTokens) {
5735 } // end: extern "C"
5737 //===----------------------------------------------------------------------===//
5738 // Token annotation APIs.
5739 //===----------------------------------------------------------------------===//
5741 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5743 CXClientData client_data);
5744 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5745 CXClientData client_data);
5748 class AnnotateTokensWorker {
5753 unsigned PreprocessingTokIdx;
5754 CursorVisitor AnnotateVis;
5755 SourceManager &SrcMgr;
5756 bool HasContextSensitiveKeywords;
5758 struct PostChildrenInfo {
5760 SourceRange CursorRange;
5761 unsigned BeforeReachingCursorIdx;
5762 unsigned BeforeChildrenTokenIdx;
5764 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
5766 CXToken &getTok(unsigned Idx) {
5767 assert(Idx < NumTokens);
5770 const CXToken &getTok(unsigned Idx) const {
5771 assert(Idx < NumTokens);
5774 bool MoreTokens() const { return TokIdx < NumTokens; }
5775 unsigned NextToken() const { return TokIdx; }
5776 void AdvanceToken() { ++TokIdx; }
5777 SourceLocation GetTokenLoc(unsigned tokI) {
5778 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
5780 bool isFunctionMacroToken(unsigned tokI) const {
5781 return getTok(tokI).int_data[3] != 0;
5783 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
5784 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
5787 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
5788 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
5792 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
5793 CXTranslationUnit TU, SourceRange RegionOfInterest)
5794 : Tokens(tokens), Cursors(cursors),
5795 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
5797 AnnotateTokensVisitor, this,
5798 /*VisitPreprocessorLast=*/true,
5799 /*VisitIncludedEntities=*/false,
5801 /*VisitDeclsOnly=*/false,
5802 AnnotateTokensPostChildrenVisitor),
5803 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
5804 HasContextSensitiveKeywords(false) { }
5806 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
5807 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
5808 bool postVisitChildren(CXCursor cursor);
5809 void AnnotateTokens();
5811 /// \brief Determine whether the annotator saw any cursors that have
5812 /// context-sensitive keywords.
5813 bool hasContextSensitiveKeywords() const {
5814 return HasContextSensitiveKeywords;
5817 ~AnnotateTokensWorker() {
5818 assert(PostChildrenInfos.empty());
5823 void AnnotateTokensWorker::AnnotateTokens() {
5824 // Walk the AST within the region of interest, annotating tokens
5826 AnnotateVis.visitFileRegion();
5829 static inline void updateCursorAnnotation(CXCursor &Cursor,
5830 const CXCursor &updateC) {
5831 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
5836 /// \brief It annotates and advances tokens with a cursor until the comparison
5837 //// between the cursor location and the source range is the same as
5838 /// \arg compResult.
5840 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5841 /// Pass RangeOverlap to annotate tokens inside a range.
5842 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5843 RangeComparisonResult compResult,
5844 SourceRange range) {
5845 while (MoreTokens()) {
5846 const unsigned I = NextToken();
5847 if (isFunctionMacroToken(I))
5848 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
5851 SourceLocation TokLoc = GetTokenLoc(I);
5852 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5853 updateCursorAnnotation(Cursors[I], updateC);
5861 /// \brief Special annotation handling for macro argument tokens.
5862 /// \returns true if it advanced beyond all macro tokens, false otherwise.
5863 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5865 RangeComparisonResult compResult,
5866 SourceRange range) {
5867 assert(MoreTokens());
5868 assert(isFunctionMacroToken(NextToken()) &&
5869 "Should be called only for macro arg tokens");
5871 // This works differently than annotateAndAdvanceTokens; because expanded
5872 // macro arguments can have arbitrary translation-unit source order, we do not
5873 // advance the token index one by one until a token fails the range test.
5874 // We only advance once past all of the macro arg tokens if all of them
5875 // pass the range test. If one of them fails we keep the token index pointing
5876 // at the start of the macro arg tokens so that the failing token will be
5877 // annotated by a subsequent annotation try.
5879 bool atLeastOneCompFail = false;
5881 unsigned I = NextToken();
5882 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5883 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5884 if (TokLoc.isFileID())
5885 continue; // not macro arg token, it's parens or comma.
5886 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5887 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5888 Cursors[I] = updateC;
5890 atLeastOneCompFail = true;
5893 if (atLeastOneCompFail)
5896 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5900 enum CXChildVisitResult
5901 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5902 SourceRange cursorRange = getRawCursorExtent(cursor);
5903 if (cursorRange.isInvalid())
5904 return CXChildVisit_Recurse;
5906 if (!HasContextSensitiveKeywords) {
5907 // Objective-C properties can have context-sensitive keywords.
5908 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5909 if (const ObjCPropertyDecl *Property
5910 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5911 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5913 // Objective-C methods can have context-sensitive keywords.
5914 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5915 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5916 if (const ObjCMethodDecl *Method
5917 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5918 if (Method->getObjCDeclQualifier())
5919 HasContextSensitiveKeywords = true;
5921 for (const auto *P : Method->params()) {
5922 if (P->getObjCDeclQualifier()) {
5923 HasContextSensitiveKeywords = true;
5930 // C++ methods can have context-sensitive keywords.
5931 else if (cursor.kind == CXCursor_CXXMethod) {
5932 if (const CXXMethodDecl *Method
5933 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5934 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5935 HasContextSensitiveKeywords = true;
5938 // C++ classes can have context-sensitive keywords.
5939 else if (cursor.kind == CXCursor_StructDecl ||
5940 cursor.kind == CXCursor_ClassDecl ||
5941 cursor.kind == CXCursor_ClassTemplate ||
5942 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5943 if (const Decl *D = getCursorDecl(cursor))
5944 if (D->hasAttr<FinalAttr>())
5945 HasContextSensitiveKeywords = true;
5949 // Don't override a property annotation with its getter/setter method.
5950 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
5951 parent.kind == CXCursor_ObjCPropertyDecl)
5952 return CXChildVisit_Continue;
5954 if (clang_isPreprocessing(cursor.kind)) {
5955 // Items in the preprocessing record are kept separate from items in
5956 // declarations, so we keep a separate token index.
5957 unsigned SavedTokIdx = TokIdx;
5958 TokIdx = PreprocessingTokIdx;
5960 // Skip tokens up until we catch up to the beginning of the preprocessing
5962 while (MoreTokens()) {
5963 const unsigned I = NextToken();
5964 SourceLocation TokLoc = GetTokenLoc(I);
5965 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5976 // Look at all of the tokens within this range.
5977 while (MoreTokens()) {
5978 const unsigned I = NextToken();
5979 SourceLocation TokLoc = GetTokenLoc(I);
5980 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5982 llvm_unreachable("Infeasible");
5986 // For macro expansions, just note where the beginning of the macro
5987 // expansion occurs.
5988 if (cursor.kind == CXCursor_MacroExpansion) {
5989 if (TokLoc == cursorRange.getBegin())
5990 Cursors[I] = cursor;
5994 // We may have already annotated macro names inside macro definitions.
5995 if (Cursors[I].kind != CXCursor_MacroExpansion)
5996 Cursors[I] = cursor;
6003 // Save the preprocessing token index; restore the non-preprocessing
6005 PreprocessingTokIdx = TokIdx;
6006 TokIdx = SavedTokIdx;
6007 return CXChildVisit_Recurse;
6010 if (cursorRange.isInvalid())
6011 return CXChildVisit_Continue;
6013 unsigned BeforeReachingCursorIdx = NextToken();
6014 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
6015 const enum CXCursorKind K = clang_getCursorKind(parent);
6016 const CXCursor updateC =
6017 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6018 // Attributes are annotated out-of-order, skip tokens until we reach it.
6019 clang_isAttribute(cursor.kind))
6020 ? clang_getNullCursor() : parent;
6022 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6024 // Avoid having the cursor of an expression "overwrite" the annotation of the
6025 // variable declaration that it belongs to.
6026 // This can happen for C++ constructor expressions whose range generally
6027 // include the variable declaration, e.g.:
6028 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
6029 if (clang_isExpression(cursorK) && MoreTokens()) {
6030 const Expr *E = getCursorExpr(cursor);
6031 if (const Decl *D = getCursorParentDecl(cursor)) {
6032 const unsigned I = NextToken();
6033 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6034 E->getLocStart() == D->getLocation() &&
6035 E->getLocStart() == GetTokenLoc(I)) {
6036 updateCursorAnnotation(Cursors[I], updateC);
6042 // Before recursing into the children keep some state that we are going
6043 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6044 // extra work after the child nodes are visited.
6045 // Note that we don't call VisitChildren here to avoid traversing statements
6046 // code-recursively which can blow the stack.
6048 PostChildrenInfo Info;
6049 Info.Cursor = cursor;
6050 Info.CursorRange = cursorRange;
6051 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
6052 Info.BeforeChildrenTokenIdx = NextToken();
6053 PostChildrenInfos.push_back(Info);
6055 return CXChildVisit_Recurse;
6058 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6059 if (PostChildrenInfos.empty())
6061 const PostChildrenInfo &Info = PostChildrenInfos.back();
6062 if (!clang_equalCursors(Info.Cursor, cursor))
6065 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6066 const unsigned AfterChildren = NextToken();
6067 SourceRange cursorRange = Info.CursorRange;
6069 // Scan the tokens that are at the end of the cursor, but are not captured
6070 // but the child cursors.
6071 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6073 // Scan the tokens that are at the beginning of the cursor, but are not
6074 // capture by the child cursors.
6075 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6076 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6079 Cursors[I] = cursor;
6082 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6083 // encountered the attribute cursor.
6084 if (clang_isAttribute(cursor.kind))
6085 TokIdx = Info.BeforeReachingCursorIdx;
6087 PostChildrenInfos.pop_back();
6091 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6093 CXClientData client_data) {
6094 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6097 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6098 CXClientData client_data) {
6099 return static_cast<AnnotateTokensWorker*>(client_data)->
6100 postVisitChildren(cursor);
6105 /// \brief Uses the macro expansions in the preprocessing record to find
6106 /// and mark tokens that are macro arguments. This info is used by the
6107 /// AnnotateTokensWorker.
6108 class MarkMacroArgTokensVisitor {
6115 MarkMacroArgTokensVisitor(SourceManager &SM,
6116 CXToken *tokens, unsigned numTokens)
6117 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6119 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6120 if (cursor.kind != CXCursor_MacroExpansion)
6121 return CXChildVisit_Continue;
6123 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6124 if (macroRange.getBegin() == macroRange.getEnd())
6125 return CXChildVisit_Continue; // it's not a function macro.
6127 for (; CurIdx < NumTokens; ++CurIdx) {
6128 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6129 macroRange.getBegin()))
6133 if (CurIdx == NumTokens)
6134 return CXChildVisit_Break;
6136 for (; CurIdx < NumTokens; ++CurIdx) {
6137 SourceLocation tokLoc = getTokenLoc(CurIdx);
6138 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6141 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6144 if (CurIdx == NumTokens)
6145 return CXChildVisit_Break;
6147 return CXChildVisit_Continue;
6151 CXToken &getTok(unsigned Idx) {
6152 assert(Idx < NumTokens);
6155 const CXToken &getTok(unsigned Idx) const {
6156 assert(Idx < NumTokens);
6160 SourceLocation getTokenLoc(unsigned tokI) {
6161 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6164 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6165 // The third field is reserved and currently not used. Use it here
6166 // to mark macro arg expanded tokens with their expanded locations.
6167 getTok(tokI).int_data[3] = loc.getRawEncoding();
6171 } // end anonymous namespace
6173 static CXChildVisitResult
6174 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6175 CXClientData client_data) {
6176 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6180 /// \brief Used by \c annotatePreprocessorTokens.
6181 /// \returns true if lexing was finished, false otherwise.
6182 static bool lexNext(Lexer &Lex, Token &Tok,
6183 unsigned &NextIdx, unsigned NumTokens) {
6184 if (NextIdx >= NumTokens)
6188 Lex.LexFromRawLexer(Tok);
6189 if (Tok.is(tok::eof))
6195 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6196 SourceRange RegionOfInterest,
6199 unsigned NumTokens) {
6200 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6202 Preprocessor &PP = CXXUnit->getPreprocessor();
6203 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6204 std::pair<FileID, unsigned> BeginLocInfo
6205 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6206 std::pair<FileID, unsigned> EndLocInfo
6207 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6209 if (BeginLocInfo.first != EndLocInfo.first)
6213 bool Invalid = false;
6214 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6215 if (Buffer.empty() || Invalid)
6218 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6219 CXXUnit->getASTContext().getLangOpts(),
6220 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6222 Lex.SetCommentRetentionState(true);
6224 unsigned NextIdx = 0;
6225 // Lex tokens in raw mode until we hit the end of the range, to avoid
6226 // entering #includes or expanding macros.
6229 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6231 unsigned TokIdx = NextIdx-1;
6232 assert(Tok.getLocation() ==
6233 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6236 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6237 // We have found a preprocessing directive. Annotate the tokens
6240 // FIXME: Some simple tests here could identify macro definitions and
6241 // #undefs, to provide specific cursor kinds for those.
6243 SourceLocation BeginLoc = Tok.getLocation();
6244 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6247 MacroInfo *MI = nullptr;
6248 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6249 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6252 if (Tok.is(tok::raw_identifier)) {
6253 IdentifierInfo &II =
6254 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6255 SourceLocation MappedTokLoc =
6256 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6257 MI = getMacroInfo(II, MappedTokLoc, TU);
6261 bool finished = false;
6263 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6267 // If we are in a macro definition, check if the token was ever a
6268 // macro name and annotate it if that's the case.
6270 SourceLocation SaveLoc = Tok.getLocation();
6271 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6272 MacroDefinitionRecord *MacroDef =
6273 checkForMacroInMacroDefinition(MI, Tok, TU);
6274 Tok.setLocation(SaveLoc);
6276 Cursors[NextIdx - 1] =
6277 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6279 } while (!Tok.isAtStartOfLine());
6281 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6282 assert(TokIdx <= LastIdx);
6283 SourceLocation EndLoc =
6284 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6286 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6288 for (; TokIdx <= LastIdx; ++TokIdx)
6289 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6298 // This gets run a separate thread to avoid stack blowout.
6299 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6300 CXToken *Tokens, unsigned NumTokens,
6301 CXCursor *Cursors) {
6302 CIndexer *CXXIdx = TU->CIdx;
6303 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6304 setThreadBackgroundPriority();
6306 // Determine the region of interest, which contains all of the tokens.
6307 SourceRange RegionOfInterest;
6308 RegionOfInterest.setBegin(
6309 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6310 RegionOfInterest.setEnd(
6311 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6312 Tokens[NumTokens-1])));
6314 // Relex the tokens within the source range to look for preprocessing
6316 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6318 // If begin location points inside a macro argument, set it to the expansion
6319 // location so we can have the full context when annotating semantically.
6321 SourceManager &SM = CXXUnit->getSourceManager();
6322 SourceLocation Loc =
6323 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6324 if (Loc.isMacroID())
6325 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6328 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6329 // Search and mark tokens that are macro argument expansions.
6330 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6332 CursorVisitor MacroArgMarker(TU,
6333 MarkMacroArgTokensVisitorDelegate, &Visitor,
6334 /*VisitPreprocessorLast=*/true,
6335 /*VisitIncludedEntities=*/false,
6337 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6340 // Annotate all of the source locations in the region of interest that map to
6341 // a specific cursor.
6342 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6344 // FIXME: We use a ridiculous stack size here because the data-recursion
6345 // algorithm uses a large stack frame than the non-data recursive version,
6346 // and AnnotationTokensWorker currently transforms the data-recursion
6347 // algorithm back into a traditional recursion by explicitly calling
6348 // VisitChildren(). We will need to remove this explicit recursive call.
6351 // If we ran into any entities that involve context-sensitive keywords,
6352 // take another pass through the tokens to mark them as such.
6353 if (W.hasContextSensitiveKeywords()) {
6354 for (unsigned I = 0; I != NumTokens; ++I) {
6355 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6358 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6359 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6360 if (const ObjCPropertyDecl *Property
6361 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6362 if (Property->getPropertyAttributesAsWritten() != 0 &&
6363 llvm::StringSwitch<bool>(II->getName())
6364 .Case("readonly", true)
6365 .Case("assign", true)
6366 .Case("unsafe_unretained", true)
6367 .Case("readwrite", true)
6368 .Case("retain", true)
6370 .Case("nonatomic", true)
6371 .Case("atomic", true)
6372 .Case("getter", true)
6373 .Case("setter", true)
6374 .Case("strong", true)
6377 Tokens[I].int_data[0] = CXToken_Keyword;
6382 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6383 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6384 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6385 if (llvm::StringSwitch<bool>(II->getName())
6388 .Case("inout", true)
6389 .Case("oneway", true)
6390 .Case("bycopy", true)
6391 .Case("byref", true)
6393 Tokens[I].int_data[0] = CXToken_Keyword;
6397 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6398 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6399 Tokens[I].int_data[0] = CXToken_Keyword;
6408 void clang_annotateTokens(CXTranslationUnit TU,
6409 CXToken *Tokens, unsigned NumTokens,
6410 CXCursor *Cursors) {
6411 if (isNotUsableTU(TU)) {
6415 if (NumTokens == 0 || !Tokens || !Cursors) {
6416 LOG_FUNC_SECTION { *Log << "<null input>"; }
6422 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6423 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6424 *Log << clang_getRange(bloc, eloc);
6427 // Any token we don't specifically annotate will have a NULL cursor.
6428 CXCursor C = clang_getNullCursor();
6429 for (unsigned I = 0; I != NumTokens; ++I)
6432 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6436 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6438 auto AnnotateTokensImpl = [=]() {
6439 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6441 llvm::CrashRecoveryContext CRC;
6442 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6443 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6447 } // end: extern "C"
6449 //===----------------------------------------------------------------------===//
6450 // Operations for querying linkage of a cursor.
6451 //===----------------------------------------------------------------------===//
6454 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6455 if (!clang_isDeclaration(cursor.kind))
6456 return CXLinkage_Invalid;
6458 const Decl *D = cxcursor::getCursorDecl(cursor);
6459 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6460 switch (ND->getLinkageInternal()) {
6462 case VisibleNoLinkage: return CXLinkage_NoLinkage;
6463 case InternalLinkage: return CXLinkage_Internal;
6464 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6465 case ExternalLinkage: return CXLinkage_External;
6468 return CXLinkage_Invalid;
6470 } // end: extern "C"
6472 //===----------------------------------------------------------------------===//
6473 // Operations for querying visibility of a cursor.
6474 //===----------------------------------------------------------------------===//
6477 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6478 if (!clang_isDeclaration(cursor.kind))
6479 return CXVisibility_Invalid;
6481 const Decl *D = cxcursor::getCursorDecl(cursor);
6482 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6483 switch (ND->getVisibility()) {
6484 case HiddenVisibility: return CXVisibility_Hidden;
6485 case ProtectedVisibility: return CXVisibility_Protected;
6486 case DefaultVisibility: return CXVisibility_Default;
6489 return CXVisibility_Invalid;
6491 } // end: extern "C"
6493 //===----------------------------------------------------------------------===//
6494 // Operations for querying language of a cursor.
6495 //===----------------------------------------------------------------------===//
6497 static CXLanguageKind getDeclLanguage(const Decl *D) {
6499 return CXLanguage_C;
6501 switch (D->getKind()) {
6504 case Decl::ImplicitParam:
6505 case Decl::ObjCAtDefsField:
6506 case Decl::ObjCCategory:
6507 case Decl::ObjCCategoryImpl:
6508 case Decl::ObjCCompatibleAlias:
6509 case Decl::ObjCImplementation:
6510 case Decl::ObjCInterface:
6511 case Decl::ObjCIvar:
6512 case Decl::ObjCMethod:
6513 case Decl::ObjCProperty:
6514 case Decl::ObjCPropertyImpl:
6515 case Decl::ObjCProtocol:
6516 case Decl::ObjCTypeParam:
6517 return CXLanguage_ObjC;
6518 case Decl::CXXConstructor:
6519 case Decl::CXXConversion:
6520 case Decl::CXXDestructor:
6521 case Decl::CXXMethod:
6522 case Decl::CXXRecord:
6523 case Decl::ClassTemplate:
6524 case Decl::ClassTemplatePartialSpecialization:
6525 case Decl::ClassTemplateSpecialization:
6527 case Decl::FriendTemplate:
6528 case Decl::FunctionTemplate:
6529 case Decl::LinkageSpec:
6530 case Decl::Namespace:
6531 case Decl::NamespaceAlias:
6532 case Decl::NonTypeTemplateParm:
6533 case Decl::StaticAssert:
6534 case Decl::TemplateTemplateParm:
6535 case Decl::TemplateTypeParm:
6536 case Decl::UnresolvedUsingTypename:
6537 case Decl::UnresolvedUsingValue:
6539 case Decl::UsingDirective:
6540 case Decl::UsingShadow:
6541 return CXLanguage_CPlusPlus;
6544 return CXLanguage_C;
6549 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6550 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6551 return CXAvailability_NotAvailable;
6553 switch (D->getAvailability()) {
6555 case AR_NotYetIntroduced:
6556 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6557 return getCursorAvailabilityForDecl(
6558 cast<Decl>(EnumConst->getDeclContext()));
6559 return CXAvailability_Available;
6562 return CXAvailability_Deprecated;
6564 case AR_Unavailable:
6565 return CXAvailability_NotAvailable;
6568 llvm_unreachable("Unknown availability kind!");
6571 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6572 if (clang_isDeclaration(cursor.kind))
6573 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6574 return getCursorAvailabilityForDecl(D);
6576 return CXAvailability_Available;
6579 static CXVersion convertVersion(VersionTuple In) {
6580 CXVersion Out = { -1, -1, -1 };
6584 Out.Major = In.getMajor();
6586 Optional<unsigned> Minor = In.getMinor();
6587 if (Minor.hasValue())
6592 Optional<unsigned> Subminor = In.getSubminor();
6593 if (Subminor.hasValue())
6594 Out.Subminor = *Subminor;
6599 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6600 int *always_deprecated,
6601 CXString *deprecated_message,
6602 int *always_unavailable,
6603 CXString *unavailable_message,
6604 CXPlatformAvailability *availability,
6605 int availability_size) {
6606 bool HadAvailAttr = false;
6608 for (auto A : D->attrs()) {
6609 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6610 HadAvailAttr = true;
6611 if (always_deprecated)
6612 *always_deprecated = 1;
6613 if (deprecated_message) {
6614 clang_disposeString(*deprecated_message);
6615 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6620 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6621 HadAvailAttr = true;
6622 if (always_unavailable)
6623 *always_unavailable = 1;
6624 if (unavailable_message) {
6625 clang_disposeString(*unavailable_message);
6626 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6631 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6632 HadAvailAttr = true;
6633 if (N < availability_size) {
6634 availability[N].Platform
6635 = cxstring::createDup(Avail->getPlatform()->getName());
6636 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6637 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6638 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6639 availability[N].Unavailable = Avail->getUnavailable();
6640 availability[N].Message = cxstring::createDup(Avail->getMessage());
6647 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6648 return getCursorPlatformAvailabilityForDecl(
6649 cast<Decl>(EnumConst->getDeclContext()),
6653 unavailable_message,
6660 int clang_getCursorPlatformAvailability(CXCursor cursor,
6661 int *always_deprecated,
6662 CXString *deprecated_message,
6663 int *always_unavailable,
6664 CXString *unavailable_message,
6665 CXPlatformAvailability *availability,
6666 int availability_size) {
6667 if (always_deprecated)
6668 *always_deprecated = 0;
6669 if (deprecated_message)
6670 *deprecated_message = cxstring::createEmpty();
6671 if (always_unavailable)
6672 *always_unavailable = 0;
6673 if (unavailable_message)
6674 *unavailable_message = cxstring::createEmpty();
6676 if (!clang_isDeclaration(cursor.kind))
6679 const Decl *D = cxcursor::getCursorDecl(cursor);
6683 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
6686 unavailable_message,
6691 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
6692 clang_disposeString(availability->Platform);
6693 clang_disposeString(availability->Message);
6696 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
6697 if (clang_isDeclaration(cursor.kind))
6698 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
6700 return CXLanguage_Invalid;
6703 /// \brief If the given cursor is the "templated" declaration
6704 /// descibing a class or function template, return the class or
6705 /// function template.
6706 static const Decl *maybeGetTemplateCursor(const Decl *D) {
6710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6711 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
6714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6715 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
6722 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
6723 StorageClass sc = SC_None;
6724 const Decl *D = getCursorDecl(C);
6726 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6727 sc = FD->getStorageClass();
6728 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6729 sc = VD->getStorageClass();
6731 return CX_SC_Invalid;
6734 return CX_SC_Invalid;
6740 return CX_SC_Extern;
6742 return CX_SC_Static;
6743 case SC_PrivateExtern:
6744 return CX_SC_PrivateExtern;
6748 return CX_SC_Register;
6750 llvm_unreachable("Unhandled storage class!");
6753 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
6754 if (clang_isDeclaration(cursor.kind)) {
6755 if (const Decl *D = getCursorDecl(cursor)) {
6756 const DeclContext *DC = D->getDeclContext();
6758 return clang_getNullCursor();
6760 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6761 getCursorTU(cursor));
6765 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
6766 if (const Decl *D = getCursorDecl(cursor))
6767 return MakeCXCursor(D, getCursorTU(cursor));
6770 return clang_getNullCursor();
6773 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
6774 if (clang_isDeclaration(cursor.kind)) {
6775 if (const Decl *D = getCursorDecl(cursor)) {
6776 const DeclContext *DC = D->getLexicalDeclContext();
6778 return clang_getNullCursor();
6780 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6781 getCursorTU(cursor));
6785 // FIXME: Note that we can't easily compute the lexical context of a
6786 // statement or expression, so we return nothing.
6787 return clang_getNullCursor();
6790 CXFile clang_getIncludedFile(CXCursor cursor) {
6791 if (cursor.kind != CXCursor_InclusionDirective)
6794 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
6795 return const_cast<FileEntry *>(ID->getFile());
6798 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
6799 if (C.kind != CXCursor_ObjCPropertyDecl)
6800 return CXObjCPropertyAttr_noattr;
6802 unsigned Result = CXObjCPropertyAttr_noattr;
6803 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
6804 ObjCPropertyDecl::PropertyAttributeKind Attr =
6805 PD->getPropertyAttributesAsWritten();
6807 #define SET_CXOBJCPROP_ATTR(A) \
6808 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
6809 Result |= CXObjCPropertyAttr_##A
6810 SET_CXOBJCPROP_ATTR(readonly);
6811 SET_CXOBJCPROP_ATTR(getter);
6812 SET_CXOBJCPROP_ATTR(assign);
6813 SET_CXOBJCPROP_ATTR(readwrite);
6814 SET_CXOBJCPROP_ATTR(retain);
6815 SET_CXOBJCPROP_ATTR(copy);
6816 SET_CXOBJCPROP_ATTR(nonatomic);
6817 SET_CXOBJCPROP_ATTR(setter);
6818 SET_CXOBJCPROP_ATTR(atomic);
6819 SET_CXOBJCPROP_ATTR(weak);
6820 SET_CXOBJCPROP_ATTR(strong);
6821 SET_CXOBJCPROP_ATTR(unsafe_unretained);
6822 #undef SET_CXOBJCPROP_ATTR
6827 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
6828 if (!clang_isDeclaration(C.kind))
6829 return CXObjCDeclQualifier_None;
6831 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
6832 const Decl *D = getCursorDecl(C);
6833 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6834 QT = MD->getObjCDeclQualifier();
6835 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
6836 QT = PD->getObjCDeclQualifier();
6837 if (QT == Decl::OBJC_TQ_None)
6838 return CXObjCDeclQualifier_None;
6840 unsigned Result = CXObjCDeclQualifier_None;
6841 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
6842 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
6843 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
6844 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
6845 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
6846 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
6851 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
6852 if (!clang_isDeclaration(C.kind))
6855 const Decl *D = getCursorDecl(C);
6856 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
6857 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
6858 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6859 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
6864 unsigned clang_Cursor_isVariadic(CXCursor C) {
6865 if (!clang_isDeclaration(C.kind))
6868 const Decl *D = getCursorDecl(C);
6869 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6870 return FD->isVariadic();
6871 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6872 return MD->isVariadic();
6877 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
6878 if (!clang_isDeclaration(C.kind))
6879 return clang_getNullRange();
6881 const Decl *D = getCursorDecl(C);
6882 ASTContext &Context = getCursorContext(C);
6883 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6885 return clang_getNullRange();
6887 return cxloc::translateSourceRange(Context, RC->getSourceRange());
6890 CXString clang_Cursor_getRawCommentText(CXCursor C) {
6891 if (!clang_isDeclaration(C.kind))
6892 return cxstring::createNull();
6894 const Decl *D = getCursorDecl(C);
6895 ASTContext &Context = getCursorContext(C);
6896 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6897 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
6900 // Don't duplicate the string because RawText points directly into source
6902 return cxstring::createRef(RawText);
6905 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
6906 if (!clang_isDeclaration(C.kind))
6907 return cxstring::createNull();
6909 const Decl *D = getCursorDecl(C);
6910 const ASTContext &Context = getCursorContext(C);
6911 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6914 StringRef BriefText = RC->getBriefText(Context);
6916 // Don't duplicate the string because RawComment ensures that this memory
6917 // will not go away.
6918 return cxstring::createRef(BriefText);
6921 return cxstring::createNull();
6924 CXModule clang_Cursor_getModule(CXCursor C) {
6925 if (C.kind == CXCursor_ModuleImportDecl) {
6926 if (const ImportDecl *ImportD =
6927 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
6928 return ImportD->getImportedModule();
6934 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
6935 if (isNotUsableTU(TU)) {
6941 FileEntry *FE = static_cast<FileEntry *>(File);
6943 ASTUnit &Unit = *cxtu::getASTUnit(TU);
6944 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
6945 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
6947 return Header.getModule();
6950 CXFile clang_Module_getASTFile(CXModule CXMod) {
6953 Module *Mod = static_cast<Module*>(CXMod);
6954 return const_cast<FileEntry *>(Mod->getASTFile());
6957 CXModule clang_Module_getParent(CXModule CXMod) {
6960 Module *Mod = static_cast<Module*>(CXMod);
6964 CXString clang_Module_getName(CXModule CXMod) {
6966 return cxstring::createEmpty();
6967 Module *Mod = static_cast<Module*>(CXMod);
6968 return cxstring::createDup(Mod->Name);
6971 CXString clang_Module_getFullName(CXModule CXMod) {
6973 return cxstring::createEmpty();
6974 Module *Mod = static_cast<Module*>(CXMod);
6975 return cxstring::createDup(Mod->getFullModuleName());
6978 int clang_Module_isSystem(CXModule CXMod) {
6981 Module *Mod = static_cast<Module*>(CXMod);
6982 return Mod->IsSystem;
6985 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
6987 if (isNotUsableTU(TU)) {
6993 Module *Mod = static_cast<Module*>(CXMod);
6994 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6995 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6996 return TopHeaders.size();
6999 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7000 CXModule CXMod, unsigned Index) {
7001 if (isNotUsableTU(TU)) {
7007 Module *Mod = static_cast<Module*>(CXMod);
7008 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7010 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7011 if (Index < TopHeaders.size())
7012 return const_cast<FileEntry *>(TopHeaders[Index]);
7017 } // end: extern "C"
7019 //===----------------------------------------------------------------------===//
7020 // C++ AST instrospection.
7021 //===----------------------------------------------------------------------===//
7024 unsigned clang_CXXField_isMutable(CXCursor C) {
7025 if (!clang_isDeclaration(C.kind))
7028 if (const auto D = cxcursor::getCursorDecl(C))
7029 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7030 return FD->isMutable() ? 1 : 0;
7034 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7035 if (!clang_isDeclaration(C.kind))
7038 const Decl *D = cxcursor::getCursorDecl(C);
7039 const CXXMethodDecl *Method =
7040 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7041 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7044 unsigned clang_CXXMethod_isConst(CXCursor C) {
7045 if (!clang_isDeclaration(C.kind))
7048 const Decl *D = cxcursor::getCursorDecl(C);
7049 const CXXMethodDecl *Method =
7050 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7051 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7054 unsigned clang_CXXMethod_isStatic(CXCursor C) {
7055 if (!clang_isDeclaration(C.kind))
7058 const Decl *D = cxcursor::getCursorDecl(C);
7059 const CXXMethodDecl *Method =
7060 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7061 return (Method && Method->isStatic()) ? 1 : 0;
7064 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7065 if (!clang_isDeclaration(C.kind))
7068 const Decl *D = cxcursor::getCursorDecl(C);
7069 const CXXMethodDecl *Method =
7070 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7071 return (Method && Method->isVirtual()) ? 1 : 0;
7073 } // end: extern "C"
7075 //===----------------------------------------------------------------------===//
7076 // Attribute introspection.
7077 //===----------------------------------------------------------------------===//
7080 CXType clang_getIBOutletCollectionType(CXCursor C) {
7081 if (C.kind != CXCursor_IBOutletCollectionAttr)
7082 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7084 const IBOutletCollectionAttr *A =
7085 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7087 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7089 } // end: extern "C"
7091 //===----------------------------------------------------------------------===//
7092 // Inspecting memory usage.
7093 //===----------------------------------------------------------------------===//
7095 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7097 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7098 enum CXTUResourceUsageKind k,
7099 unsigned long amount) {
7100 CXTUResourceUsageEntry entry = { k, amount };
7101 entries.push_back(entry);
7106 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7107 const char *str = "";
7109 case CXTUResourceUsage_AST:
7110 str = "ASTContext: expressions, declarations, and types";
7112 case CXTUResourceUsage_Identifiers:
7113 str = "ASTContext: identifiers";
7115 case CXTUResourceUsage_Selectors:
7116 str = "ASTContext: selectors";
7118 case CXTUResourceUsage_GlobalCompletionResults:
7119 str = "Code completion: cached global results";
7121 case CXTUResourceUsage_SourceManagerContentCache:
7122 str = "SourceManager: content cache allocator";
7124 case CXTUResourceUsage_AST_SideTables:
7125 str = "ASTContext: side tables";
7127 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7128 str = "SourceManager: malloc'ed memory buffers";
7130 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7131 str = "SourceManager: mmap'ed memory buffers";
7133 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7134 str = "ExternalASTSource: malloc'ed memory buffers";
7136 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7137 str = "ExternalASTSource: mmap'ed memory buffers";
7139 case CXTUResourceUsage_Preprocessor:
7140 str = "Preprocessor: malloc'ed memory";
7142 case CXTUResourceUsage_PreprocessingRecord:
7143 str = "Preprocessor: PreprocessingRecord";
7145 case CXTUResourceUsage_SourceManager_DataStructures:
7146 str = "SourceManager: data structures and tables";
7148 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7149 str = "Preprocessor: header search tables";
7155 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7156 if (isNotUsableTU(TU)) {
7158 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7162 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7163 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7164 ASTContext &astContext = astUnit->getASTContext();
7166 // How much memory is used by AST nodes and types?
7167 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7168 (unsigned long) astContext.getASTAllocatedMemory());
7170 // How much memory is used by identifiers?
7171 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7172 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7174 // How much memory is used for selectors?
7175 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7176 (unsigned long) astContext.Selectors.getTotalMemory());
7178 // How much memory is used by ASTContext's side tables?
7179 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7180 (unsigned long) astContext.getSideTableAllocatedMemory());
7182 // How much memory is used for caching global code completion results?
7183 unsigned long completionBytes = 0;
7184 if (GlobalCodeCompletionAllocator *completionAllocator =
7185 astUnit->getCachedCompletionAllocator().get()) {
7186 completionBytes = completionAllocator->getTotalMemory();
7188 createCXTUResourceUsageEntry(*entries,
7189 CXTUResourceUsage_GlobalCompletionResults,
7192 // How much memory is being used by SourceManager's content cache?
7193 createCXTUResourceUsageEntry(*entries,
7194 CXTUResourceUsage_SourceManagerContentCache,
7195 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7197 // How much memory is being used by the MemoryBuffer's in SourceManager?
7198 const SourceManager::MemoryBufferSizes &srcBufs =
7199 astUnit->getSourceManager().getMemoryBufferSizes();
7201 createCXTUResourceUsageEntry(*entries,
7202 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7203 (unsigned long) srcBufs.malloc_bytes);
7204 createCXTUResourceUsageEntry(*entries,
7205 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7206 (unsigned long) srcBufs.mmap_bytes);
7207 createCXTUResourceUsageEntry(*entries,
7208 CXTUResourceUsage_SourceManager_DataStructures,
7209 (unsigned long) astContext.getSourceManager()
7210 .getDataStructureSizes());
7212 // How much memory is being used by the ExternalASTSource?
7213 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7214 const ExternalASTSource::MemoryBufferSizes &sizes =
7215 esrc->getMemoryBufferSizes();
7217 createCXTUResourceUsageEntry(*entries,
7218 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7219 (unsigned long) sizes.malloc_bytes);
7220 createCXTUResourceUsageEntry(*entries,
7221 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7222 (unsigned long) sizes.mmap_bytes);
7225 // How much memory is being used by the Preprocessor?
7226 Preprocessor &pp = astUnit->getPreprocessor();
7227 createCXTUResourceUsageEntry(*entries,
7228 CXTUResourceUsage_Preprocessor,
7229 pp.getTotalMemory());
7231 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7232 createCXTUResourceUsageEntry(*entries,
7233 CXTUResourceUsage_PreprocessingRecord,
7234 pRec->getTotalMemory());
7237 createCXTUResourceUsageEntry(*entries,
7238 CXTUResourceUsage_Preprocessor_HeaderSearch,
7239 pp.getHeaderSearchInfo().getTotalMemory());
7241 CXTUResourceUsage usage = { (void*) entries.get(),
7242 (unsigned) entries->size(),
7243 !entries->empty() ? &(*entries)[0] : nullptr };
7248 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7250 delete (MemUsageEntries*) usage.data;
7253 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7254 CXSourceRangeList *skipped = new CXSourceRangeList;
7256 skipped->ranges = nullptr;
7258 if (isNotUsableTU(TU)) {
7266 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7267 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7271 ASTContext &Ctx = astUnit->getASTContext();
7272 SourceManager &sm = Ctx.getSourceManager();
7273 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7274 FileID wantedFileID = sm.translateFile(fileEntry);
7276 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7277 std::vector<SourceRange> wantedRanges;
7278 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7280 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7281 wantedRanges.push_back(*i);
7284 skipped->count = wantedRanges.size();
7285 skipped->ranges = new CXSourceRange[skipped->count];
7286 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7287 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7292 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7294 delete[] ranges->ranges;
7301 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7302 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7303 for (unsigned I = 0; I != Usage.numEntries; ++I)
7304 fprintf(stderr, " %s: %lu\n",
7305 clang_getTUResourceUsageName(Usage.entries[I].kind),
7306 Usage.entries[I].amount);
7308 clang_disposeCXTUResourceUsage(Usage);
7311 //===----------------------------------------------------------------------===//
7312 // Misc. utility functions.
7313 //===----------------------------------------------------------------------===//
7315 /// Default to using an 8 MB stack size on "safety" threads.
7316 static unsigned SafetyStackThreadSize = 8 << 20;
7320 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7323 Size = GetSafetyThreadStackSize();
7325 return CRC.RunSafelyOnThread(Fn, Size);
7326 return CRC.RunSafely(Fn);
7329 unsigned GetSafetyThreadStackSize() {
7330 return SafetyStackThreadSize;
7333 void SetSafetyThreadStackSize(unsigned Value) {
7334 SafetyStackThreadSize = Value;
7339 void clang::setThreadBackgroundPriority() {
7340 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7343 #ifdef USE_DARWIN_THREADS
7344 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7348 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7352 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7353 DEnd = Unit->stored_diag_end();
7355 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7356 CXString Msg = clang_formatDiagnostic(&Diag,
7357 clang_defaultDiagnosticDisplayOptions());
7358 fprintf(stderr, "%s\n", clang_getCString(Msg));
7359 clang_disposeString(Msg);
7361 #ifdef LLVM_ON_WIN32
7362 // On Windows, force a flush, since there may be multiple copies of
7363 // stderr and stdout in the file system, all with different buffers
7364 // but writing to the same device.
7369 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7370 SourceLocation MacroDefLoc,
7371 CXTranslationUnit TU){
7372 if (MacroDefLoc.isInvalid() || !TU)
7374 if (!II.hadMacroDefinition())
7377 ASTUnit *Unit = cxtu::getASTUnit(TU);
7378 Preprocessor &PP = Unit->getPreprocessor();
7379 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7381 for (MacroDirective::DefInfo
7382 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7383 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7384 return Def.getMacroInfo();
7391 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7392 CXTranslationUnit TU) {
7393 if (!MacroDef || !TU)
7395 const IdentifierInfo *II = MacroDef->getName();
7399 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7402 MacroDefinitionRecord *
7403 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7404 CXTranslationUnit TU) {
7407 if (Tok.isNot(tok::raw_identifier))
7410 if (MI->getNumTokens() == 0)
7412 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7413 MI->getDefinitionEndLoc());
7414 ASTUnit *Unit = cxtu::getASTUnit(TU);
7416 // Check that the token is inside the definition and not its argument list.
7417 SourceManager &SM = Unit->getSourceManager();
7418 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7420 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7423 Preprocessor &PP = Unit->getPreprocessor();
7424 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7428 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7429 if (!II.hadMacroDefinition())
7432 // Check that the identifier is not one of the macro arguments.
7433 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7436 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7440 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7443 MacroDefinitionRecord *
7444 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7445 CXTranslationUnit TU) {
7446 if (Loc.isInvalid() || !MI || !TU)
7449 if (MI->getNumTokens() == 0)
7451 ASTUnit *Unit = cxtu::getASTUnit(TU);
7452 Preprocessor &PP = Unit->getPreprocessor();
7453 if (!PP.getPreprocessingRecord())
7455 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7457 if (PP.getRawToken(Loc, Tok))
7460 return checkForMacroInMacroDefinition(MI, Tok, TU);
7465 CXString clang_getClangVersion() {
7466 return cxstring::createDup(getClangFullVersion());
7469 } // end: extern "C"
7471 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7473 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7474 LogOS << '<' << Unit->getMainFileName() << '>';
7475 if (Unit->isMainFileAST())
7476 LogOS << " (" << Unit->getASTFileName() << ')';
7480 LogOS << "<NULL TU>";
7485 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7486 *this << FE->getName();
7490 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7491 CXString cursorName = clang_getCursorDisplayName(cursor);
7492 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7493 clang_disposeString(cursorName);
7497 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7499 unsigned Line, Column;
7500 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7501 CXString FileName = clang_getFileName(File);
7502 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7503 clang_disposeString(FileName);
7507 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7508 CXSourceLocation BLoc = clang_getRangeStart(range);
7509 CXSourceLocation ELoc = clang_getRangeEnd(range);
7512 unsigned BLine, BColumn;
7513 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7516 unsigned ELine, EColumn;
7517 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7519 CXString BFileName = clang_getFileName(BFile);
7520 if (BFile == EFile) {
7521 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7522 BLine, BColumn, ELine, EColumn);
7524 CXString EFileName = clang_getFileName(EFile);
7525 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7527 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7529 clang_disposeString(EFileName);
7531 clang_disposeString(BFileName);
7535 Logger &cxindex::Logger::operator<<(CXString Str) {
7536 *this << clang_getCString(Str);
7540 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7545 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7547 cxindex::Logger::~Logger() {
7548 llvm::sys::ScopedLock L(*LoggingMutex);
7550 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7552 raw_ostream &OS = llvm::errs();
7553 OS << "[libclang:" << Name << ':';
7555 #ifdef USE_DARWIN_THREADS
7556 // TODO: Portability.
7557 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7561 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7562 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7566 llvm::sys::PrintStackTrace(OS);
7567 OS << "--------------------------------------------------\n";