1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the main API hooks in the Clang-C Source Indexing
13 //===----------------------------------------------------------------------===//
16 #include "CIndexDiagnostic.h"
19 #include "CXSourceLocation.h"
21 #include "CXTranslationUnit.h"
23 #include "CursorVisitor.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Basic/DiagnosticCategories.h"
29 #include "clang/Basic/DiagnosticIDs.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/ASTUnit.h"
33 #include "clang/Frontend/CompilerInstance.h"
34 #include "clang/Frontend/FrontendDiagnostic.h"
35 #include "clang/Index/CommentToXML.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Serialization/SerializationDiagnostic.h"
41 #include "llvm/ADT/Optional.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/StringSwitch.h"
44 #include "llvm/Config/llvm-config.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/Mangler.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/CrashRecoveryContext.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Mutex.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/Threading.h"
58 #include "llvm/Support/Timer.h"
59 #include "llvm/Support/raw_ostream.h"
61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
62 #define USE_DARWIN_THREADS
65 #ifdef USE_DARWIN_THREADS
69 using namespace clang;
70 using namespace clang::cxcursor;
71 using namespace clang::cxtu;
72 using namespace clang::cxindex;
74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
78 CXTranslationUnit D = new CXTranslationUnitImpl();
81 D->StringPool = new cxstring::CXStringPool();
82 D->Diagnostics = nullptr;
83 D->OverridenCursorsPool = createOverridenCXCursorsPool();
84 D->CommentToXML = nullptr;
88 bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
100 cxtu::CXTUOwner::~CXTUOwner() {
102 clang_disposeTranslationUnit(TU);
105 /// \brief Compare two source ranges to determine their relative position in
106 /// the translation unit.
107 static RangeComparisonResult RangeCompare(SourceManager &SM,
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
121 /// \brief Determine if a source location falls within, before, or after a
122 /// a given source range.
123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
136 /// \brief Translate a Clang source range into a CIndex source range.
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
149 EndLoc = SM.getExpansionRange(EndLoc).second;
150 if (R.isTokenRange() && EndLoc.isValid()) {
151 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
153 EndLoc = EndLoc.getLocWithOffset(Length);
156 CXSourceRange Result = {
158 R.getBegin().getRawEncoding(),
159 EndLoc.getRawEncoding()
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 static SourceRange getRawCursorExtent(CXCursor C);
169 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
172 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
173 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
176 /// \brief Visit the given cursor and, if requested by the visitor,
179 /// \param Cursor the cursor to visit.
181 /// \param CheckedRegionOfInterest if true, then the caller already checked
182 /// that this cursor is within the region of interest.
184 /// \returns true if the visitation should be aborted, false if it
186 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
187 if (clang_isInvalid(Cursor.kind))
190 if (clang_isDeclaration(Cursor.kind)) {
191 const Decl *D = getCursorDecl(Cursor);
193 assert(0 && "Invalid declaration cursor");
194 return true; // abort.
197 // Ignore implicit declarations, unless it's an objc method because
198 // currently we should report implicit methods for properties when indexing.
199 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 // If we have a range of interest, and this cursor doesn't intersect with it,
205 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
206 SourceRange Range = getRawCursorExtent(Cursor);
207 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 switch (Visitor(Cursor, Parent, ClientData)) {
212 case CXChildVisit_Break:
215 case CXChildVisit_Continue:
218 case CXChildVisit_Recurse: {
219 bool ret = VisitChildren(Cursor);
220 if (PostChildrenVisitor)
221 if (PostChildrenVisitor(Cursor, ClientData))
227 llvm_unreachable("Invalid CXChildVisitResult!");
230 static bool visitPreprocessedEntitiesInRange(SourceRange R,
231 PreprocessingRecord &PPRec,
232 CursorVisitor &Visitor) {
233 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
236 if (!Visitor.shouldVisitIncludedEntities()) {
237 // If the begin/end of the range lie in the same FileID, do the optimization
238 // where we skip preprocessed entities that do not come from the same FileID.
239 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
240 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
245 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
249 bool CursorVisitor::visitFileRegion() {
250 if (RegionOfInterest.isInvalid())
253 ASTUnit *Unit = cxtu::getASTUnit(TU);
254 SourceManager &SM = Unit->getSourceManager();
256 std::pair<FileID, unsigned>
257 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
258 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
260 if (End.first != Begin.first) {
261 // If the end does not reside in the same file, try to recover by
262 // picking the end of the file of begin location.
263 End.first = Begin.first;
264 End.second = SM.getFileIDSize(Begin.first);
267 assert(Begin.first == End.first);
268 if (Begin.second > End.second)
271 FileID File = Begin.first;
272 unsigned Offset = Begin.second;
273 unsigned Length = End.second - Begin.second;
275 if (!VisitDeclsOnly && !VisitPreprocessorLast)
276 if (visitPreprocessedEntitiesInRegion())
277 return true; // visitation break.
279 if (visitDeclsFromFileRegion(File, Offset, Length))
280 return true; // visitation break.
282 if (!VisitDeclsOnly && VisitPreprocessorLast)
283 return visitPreprocessedEntitiesInRegion();
288 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 for (DeclContext *DeclDC = D->getLexicalDeclContext();
293 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
301 unsigned Offset, unsigned Length) {
302 ASTUnit *Unit = cxtu::getASTUnit(TU);
303 SourceManager &SM = Unit->getSourceManager();
304 SourceRange Range = RegionOfInterest;
306 SmallVector<Decl *, 16> Decls;
307 Unit->findFileRegionDecls(File, Offset, Length, Decls);
309 // If we didn't find any file level decls for the file, try looking at the
310 // file that it was included from.
311 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
312 bool Invalid = false;
313 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 SourceLocation Outer;
318 if (SLEntry.isFile())
319 Outer = SLEntry.getFile().getIncludeLoc();
321 Outer = SLEntry.getExpansion().getExpansionLocStart();
322 if (Outer.isInvalid())
325 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
327 Unit->findFileRegionDecls(File, Offset, Length, Decls);
330 assert(!Decls.empty());
332 bool VisitedAtLeastOnce = false;
333 DeclContext *CurDC = nullptr;
334 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
335 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
337 if (D->getSourceRange().isInvalid())
340 if (isInLexicalContext(D, CurDC))
343 CurDC = dyn_cast<DeclContext>(D);
345 if (TagDecl *TD = dyn_cast<TagDecl>(D))
346 if (!TD->isFreeStanding())
349 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
350 if (CompRes == RangeBefore)
352 if (CompRes == RangeAfter)
355 assert(CompRes == RangeOverlap);
356 VisitedAtLeastOnce = true;
358 if (isa<ObjCContainerDecl>(D)) {
359 FileDI_current = &DIt;
362 FileDI_current = nullptr;
365 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
366 return true; // visitation break.
369 if (VisitedAtLeastOnce)
372 // No Decls overlapped with the range. Move up the lexical context until there
373 // is a context that contains the range or we reach the translation unit
375 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
376 : (*(DIt-1))->getLexicalDeclContext();
378 while (DC && !DC->isTranslationUnit()) {
379 Decl *D = cast<Decl>(DC);
380 SourceRange CurDeclRange = D->getSourceRange();
381 if (CurDeclRange.isInvalid())
384 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
385 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
386 return true; // visitation break.
389 DC = D->getLexicalDeclContext();
395 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
396 if (!AU->getPreprocessor().getPreprocessingRecord())
399 PreprocessingRecord &PPRec
400 = *AU->getPreprocessor().getPreprocessingRecord();
401 SourceManager &SM = AU->getSourceManager();
403 if (RegionOfInterest.isValid()) {
404 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
405 SourceLocation B = MappedRange.getBegin();
406 SourceLocation E = MappedRange.getEnd();
408 if (AU->isInPreambleFileID(B)) {
409 if (SM.isLoadedSourceLocation(E))
410 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
413 // Beginning of range lies in the preamble but it also extends beyond
414 // it into the main file. Split the range into 2 parts, one covering
415 // the preamble and another covering the main file. This allows subsequent
416 // calls to visitPreprocessedEntitiesInRange to accept a source range that
417 // lies in the same FileID, allowing it to skip preprocessed entities that
418 // do not come from the same FileID.
420 visitPreprocessedEntitiesInRange(
421 SourceRange(B, AU->getEndOfPreambleFileID()),
423 if (breaked) return true;
424 return visitPreprocessedEntitiesInRange(
425 SourceRange(AU->getStartOfMainFileID(), E),
429 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
436 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
439 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
442 template<typename InputIterator>
443 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
445 PreprocessingRecord &PPRec,
447 for (; First != Last; ++First) {
448 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
451 PreprocessedEntity *PPE = *First;
455 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
456 if (Visit(MakeMacroExpansionCursor(ME, TU)))
462 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
463 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
469 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
470 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 /// \brief Visit the children of the given cursor.
482 /// \returns true if the visitation should be aborted, false if it
484 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
485 if (clang_isReference(Cursor.kind) &&
486 Cursor.kind != CXCursor_CXXBaseSpecifier) {
487 // By definition, references have no children.
491 // Set the Parent field to Cursor, then back to its old value once we're
493 SetParentRAII SetParent(Parent, StmtParent, Cursor);
495 if (clang_isDeclaration(Cursor.kind)) {
496 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
500 return VisitAttributes(D) || Visit(D);
503 if (clang_isStatement(Cursor.kind)) {
504 if (const Stmt *S = getCursorStmt(Cursor))
510 if (clang_isExpression(Cursor.kind)) {
511 if (const Expr *E = getCursorExpr(Cursor))
517 if (clang_isTranslationUnit(Cursor.kind)) {
518 CXTranslationUnit TU = getCursorTU(Cursor);
519 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
521 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
522 for (unsigned I = 0; I != 2; ++I) {
524 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525 RegionOfInterest.isInvalid()) {
526 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527 TLEnd = CXXUnit->top_level_end();
529 if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
555 const IBOutletCollectionAttr *A =
556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
577 // Nothing to visit at the moment.
581 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
592 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
598 switch (CompareRegionOfInterest(Range)) {
600 // This declaration comes before the region of interest; skip it.
604 // This declaration comes after the region of interest; we're done.
608 // This declaration overlaps the region of interest; visit it.
615 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623 for ( ; I != E; ++I) {
625 if (D->getLexicalDeclContext() != DC)
627 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
629 // Ignore synthesized ivars here, otherwise if we have something like:
630 // @synthesize prop = _prop;
631 // and '_prop' is not declared, we will encounter a '_prop' ivar before
632 // encountering the 'prop' synthesize declaration and we will think that
633 // we passed the region-of-interest.
634 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
635 if (ivarD->getSynthesize())
639 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
640 // declarations is a mismatch with the compiler semantics.
641 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
642 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
643 if (!ID->isThisDeclarationADefinition())
644 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
646 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
647 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
648 if (!PD->isThisDeclarationADefinition())
649 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
652 const Optional<bool> &V = shouldVisitCursor(Cursor);
657 if (Visit(Cursor, true))
663 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
664 llvm_unreachable("Translation units are visited directly by Visit()");
667 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
668 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
669 return Visit(TSInfo->getTypeLoc());
674 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
675 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
676 return Visit(TSInfo->getTypeLoc());
681 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
682 return VisitDeclContext(D);
685 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
686 ClassTemplateSpecializationDecl *D) {
687 bool ShouldVisitBody = false;
688 switch (D->getSpecializationKind()) {
690 case TSK_ImplicitInstantiation:
694 case TSK_ExplicitInstantiationDeclaration:
695 case TSK_ExplicitInstantiationDefinition:
698 case TSK_ExplicitSpecialization:
699 ShouldVisitBody = true;
703 // Visit the template arguments used in the specialization.
704 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
705 TypeLoc TL = SpecType->getTypeLoc();
706 if (TemplateSpecializationTypeLoc TSTLoc =
707 TL.getAs<TemplateSpecializationTypeLoc>()) {
708 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
709 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
714 if (ShouldVisitBody && VisitCXXRecordDecl(D))
720 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
721 ClassTemplatePartialSpecializationDecl *D) {
722 // FIXME: Visit the "outer" template parameter lists on the TagDecl
723 // before visiting these template parameters.
724 if (VisitTemplateParameters(D->getTemplateParameters()))
727 // Visit the partial specialization arguments.
728 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
729 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
730 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
731 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
734 return VisitCXXRecordDecl(D);
737 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
738 // Visit the default argument.
739 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
740 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
741 if (Visit(DefArg->getTypeLoc()))
747 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
748 if (Expr *Init = D->getInitExpr())
749 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
753 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
754 unsigned NumParamList = DD->getNumTemplateParameterLists();
755 for (unsigned i = 0; i < NumParamList; i++) {
756 TemplateParameterList* Params = DD->getTemplateParameterList(i);
757 if (VisitTemplateParameters(Params))
761 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
762 if (Visit(TSInfo->getTypeLoc()))
765 // Visit the nested-name-specifier, if present.
766 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
767 if (VisitNestedNameSpecifierLoc(QualifierLoc))
773 /// \brief Compare two base or member initializers based on their source order.
774 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
775 CXXCtorInitializer *const *Y) {
776 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
779 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
780 unsigned NumParamList = ND->getNumTemplateParameterLists();
781 for (unsigned i = 0; i < NumParamList; i++) {
782 TemplateParameterList* Params = ND->getTemplateParameterList(i);
783 if (VisitTemplateParameters(Params))
787 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
788 // Visit the function declaration's syntactic components in the order
789 // written. This requires a bit of work.
790 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
791 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
793 // If we have a function declared directly (without the use of a typedef),
794 // visit just the return type. Otherwise, just visit the function's type
796 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
800 // Visit the nested-name-specifier, if present.
801 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
802 if (VisitNestedNameSpecifierLoc(QualifierLoc))
805 // Visit the declaration name.
806 if (!isa<CXXDestructorDecl>(ND))
807 if (VisitDeclarationNameInfo(ND->getNameInfo()))
810 // FIXME: Visit explicitly-specified template arguments!
812 // Visit the function parameters, if we have a function type.
813 if (FTL && VisitFunctionTypeLoc(FTL, true))
816 // FIXME: Attributes?
819 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
820 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
821 // Find the initializers that were written in the source.
822 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
823 for (auto *I : Constructor->inits()) {
827 WrittenInits.push_back(I);
830 // Sort the initializers in source order
831 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
832 &CompareCXXCtorInitializers);
834 // Visit the initializers in source order
835 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
836 CXXCtorInitializer *Init = WrittenInits[I];
837 if (Init->isAnyMemberInitializer()) {
838 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
839 Init->getMemberLocation(), TU)))
841 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
842 if (Visit(TInfo->getTypeLoc()))
846 // Visit the initializer value.
847 if (Expr *Initializer = Init->getInit())
848 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
853 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
860 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
861 if (VisitDeclaratorDecl(D))
864 if (Expr *BitWidth = D->getBitWidth())
865 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
870 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
871 if (VisitDeclaratorDecl(D))
874 if (Expr *Init = D->getInit())
875 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
880 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
881 if (VisitDeclaratorDecl(D))
884 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
885 if (Expr *DefArg = D->getDefaultArgument())
886 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
891 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
892 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
893 // before visiting these template parameters.
894 if (VisitTemplateParameters(D->getTemplateParameters()))
897 return VisitFunctionDecl(D->getTemplatedDecl());
900 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
901 // FIXME: Visit the "outer" template parameter lists on the TagDecl
902 // before visiting these template parameters.
903 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return VisitCXXRecordDecl(D->getTemplatedDecl());
909 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
910 if (VisitTemplateParameters(D->getTemplateParameters()))
913 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
914 VisitTemplateArgumentLoc(D->getDefaultArgument()))
920 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
921 // Visit the bound, if it's explicit.
922 if (D->hasExplicitBound()) {
923 if (auto TInfo = D->getTypeSourceInfo()) {
924 if (Visit(TInfo->getTypeLoc()))
932 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
933 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
934 if (Visit(TSInfo->getTypeLoc()))
937 for (const auto *P : ND->params()) {
938 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
942 if (ND->isThisDeclarationADefinition() &&
943 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
949 template <typename DeclIt>
950 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
951 SourceManager &SM, SourceLocation EndLoc,
952 SmallVectorImpl<Decl *> &Decls) {
953 DeclIt next = *DI_current;
954 while (++next != DE_current) {
955 Decl *D_next = *next;
958 SourceLocation L = D_next->getLocStart();
961 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
963 Decls.push_back(D_next);
970 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
971 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
972 // an @implementation can lexically contain Decls that are not properly
973 // nested in the AST. When we identify such cases, we need to retrofit
974 // this nesting here.
975 if (!DI_current && !FileDI_current)
976 return VisitDeclContext(D);
978 // Scan the Decls that immediately come after the container
979 // in the current DeclContext. If any fall within the
980 // container's lexical region, stash them into a vector
981 // for later processing.
982 SmallVector<Decl *, 24> DeclsInContainer;
983 SourceLocation EndLoc = D->getSourceRange().getEnd();
984 SourceManager &SM = AU->getSourceManager();
985 if (EndLoc.isValid()) {
987 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
990 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
996 if (DeclsInContainer.empty())
997 return VisitDeclContext(D);
999 // Get all the Decls in the DeclContext, and sort them with the
1000 // additional ones we've collected. Then visit them.
1001 for (auto *SubDecl : D->decls()) {
1002 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1003 SubDecl->getLocStart().isInvalid())
1005 DeclsInContainer.push_back(SubDecl);
1008 // Now sort the Decls so that they appear in lexical order.
1009 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1010 [&SM](Decl *A, Decl *B) {
1011 SourceLocation L_A = A->getLocStart();
1012 SourceLocation L_B = B->getLocStart();
1013 assert(L_A.isValid() && L_B.isValid());
1014 return SM.isBeforeInTranslationUnit(L_A, L_B);
1017 // Now visit the decls.
1018 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1019 E = DeclsInContainer.end(); I != E; ++I) {
1020 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1021 const Optional<bool> &V = shouldVisitCursor(Cursor);
1026 if (Visit(Cursor, true))
1032 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1033 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1037 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1040 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1041 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1042 E = ND->protocol_end(); I != E; ++I, ++PL)
1043 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1046 return VisitObjCContainerDecl(ND);
1049 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1050 if (!PID->isThisDeclarationADefinition())
1051 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1053 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1054 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1055 E = PID->protocol_end(); I != E; ++I, ++PL)
1056 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1059 return VisitObjCContainerDecl(PID);
1062 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1063 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1066 // FIXME: This implements a workaround with @property declarations also being
1067 // installed in the DeclContext for the @interface. Eventually this code
1068 // should be removed.
1069 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1070 if (!CDecl || !CDecl->IsClassExtension())
1073 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1077 IdentifierInfo *PropertyId = PD->getIdentifier();
1078 ObjCPropertyDecl *prevDecl =
1079 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1084 // Visit synthesized methods since they will be skipped when visiting
1086 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1087 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1088 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1091 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1092 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1093 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1099 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1103 for (auto *typeParam : *typeParamList) {
1104 // Visit the type parameter.
1105 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1112 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1113 if (!D->isThisDeclarationADefinition()) {
1114 // Forward declaration is treated like a reference.
1115 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1118 // Objective-C type parameters.
1119 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1122 // Issue callbacks for super class.
1123 if (D->getSuperClass() &&
1124 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1125 D->getSuperClassLoc(),
1129 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1130 if (Visit(SuperClassTInfo->getTypeLoc()))
1133 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1134 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1135 E = D->protocol_end(); I != E; ++I, ++PL)
1136 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1139 return VisitObjCContainerDecl(D);
1142 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1143 return VisitObjCContainerDecl(D);
1146 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1147 // 'ID' could be null when dealing with invalid code.
1148 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1149 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1152 return VisitObjCImplDecl(D);
1155 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1157 // Issue callbacks for super class.
1158 // FIXME: No source location information!
1159 if (D->getSuperClass() &&
1160 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1161 D->getSuperClassLoc(),
1166 return VisitObjCImplDecl(D);
1169 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1170 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1171 if (PD->isIvarNameSpecified())
1172 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1177 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1178 return VisitDeclContext(D);
1181 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1182 // Visit nested-name-specifier.
1183 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1184 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1187 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1188 D->getTargetNameLoc(), TU));
1191 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1192 // Visit nested-name-specifier.
1193 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1194 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1198 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1201 return VisitDeclarationNameInfo(D->getNameInfo());
1204 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1205 // Visit nested-name-specifier.
1206 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1207 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1210 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1211 D->getIdentLocation(), TU));
1214 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1215 // Visit nested-name-specifier.
1216 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1221 return VisitDeclarationNameInfo(D->getNameInfo());
1224 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1225 UnresolvedUsingTypenameDecl *D) {
1226 // Visit nested-name-specifier.
1227 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1234 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1235 switch (Name.getName().getNameKind()) {
1236 case clang::DeclarationName::Identifier:
1237 case clang::DeclarationName::CXXLiteralOperatorName:
1238 case clang::DeclarationName::CXXOperatorName:
1239 case clang::DeclarationName::CXXUsingDirective:
1242 case clang::DeclarationName::CXXConstructorName:
1243 case clang::DeclarationName::CXXDestructorName:
1244 case clang::DeclarationName::CXXConversionFunctionName:
1245 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1246 return Visit(TSInfo->getTypeLoc());
1249 case clang::DeclarationName::ObjCZeroArgSelector:
1250 case clang::DeclarationName::ObjCOneArgSelector:
1251 case clang::DeclarationName::ObjCMultiArgSelector:
1252 // FIXME: Per-identifier location info?
1256 llvm_unreachable("Invalid DeclarationName::Kind!");
1259 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1260 SourceRange Range) {
1261 // FIXME: This whole routine is a hack to work around the lack of proper
1262 // source information in nested-name-specifiers (PR5791). Since we do have
1263 // a beginning source location, we can visit the first component of the
1264 // nested-name-specifier, if it's a single-token component.
1268 // Get the first component in the nested-name-specifier.
1269 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1272 switch (NNS->getKind()) {
1273 case NestedNameSpecifier::Namespace:
1274 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1277 case NestedNameSpecifier::NamespaceAlias:
1278 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1279 Range.getBegin(), TU));
1281 case NestedNameSpecifier::TypeSpec: {
1282 // If the type has a form where we know that the beginning of the source
1283 // range matches up with a reference cursor. Visit the appropriate reference
1285 const Type *T = NNS->getAsType();
1286 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1287 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1288 if (const TagType *Tag = dyn_cast<TagType>(T))
1289 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1290 if (const TemplateSpecializationType *TST
1291 = dyn_cast<TemplateSpecializationType>(T))
1292 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1296 case NestedNameSpecifier::TypeSpecWithTemplate:
1297 case NestedNameSpecifier::Global:
1298 case NestedNameSpecifier::Identifier:
1299 case NestedNameSpecifier::Super:
1307 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1308 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1309 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1310 Qualifiers.push_back(Qualifier);
1312 while (!Qualifiers.empty()) {
1313 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1314 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1315 switch (NNS->getKind()) {
1316 case NestedNameSpecifier::Namespace:
1317 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1318 Q.getLocalBeginLoc(),
1324 case NestedNameSpecifier::NamespaceAlias:
1325 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1326 Q.getLocalBeginLoc(),
1332 case NestedNameSpecifier::TypeSpec:
1333 case NestedNameSpecifier::TypeSpecWithTemplate:
1334 if (Visit(Q.getTypeLoc()))
1339 case NestedNameSpecifier::Global:
1340 case NestedNameSpecifier::Identifier:
1341 case NestedNameSpecifier::Super:
1349 bool CursorVisitor::VisitTemplateParameters(
1350 const TemplateParameterList *Params) {
1354 for (TemplateParameterList::const_iterator P = Params->begin(),
1355 PEnd = Params->end();
1357 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1364 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1365 switch (Name.getKind()) {
1366 case TemplateName::Template:
1367 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1369 case TemplateName::OverloadedTemplate:
1370 // Visit the overloaded template set.
1371 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1376 case TemplateName::DependentTemplate:
1377 // FIXME: Visit nested-name-specifier.
1380 case TemplateName::QualifiedTemplate:
1381 // FIXME: Visit nested-name-specifier.
1382 return Visit(MakeCursorTemplateRef(
1383 Name.getAsQualifiedTemplateName()->getDecl(),
1386 case TemplateName::SubstTemplateTemplateParm:
1387 return Visit(MakeCursorTemplateRef(
1388 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1391 case TemplateName::SubstTemplateTemplateParmPack:
1392 return Visit(MakeCursorTemplateRef(
1393 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1397 llvm_unreachable("Invalid TemplateName::Kind!");
1400 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1401 switch (TAL.getArgument().getKind()) {
1402 case TemplateArgument::Null:
1403 case TemplateArgument::Integral:
1404 case TemplateArgument::Pack:
1407 case TemplateArgument::Type:
1408 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1409 return Visit(TSInfo->getTypeLoc());
1412 case TemplateArgument::Declaration:
1413 if (Expr *E = TAL.getSourceDeclExpression())
1414 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1417 case TemplateArgument::NullPtr:
1418 if (Expr *E = TAL.getSourceNullPtrExpression())
1419 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1422 case TemplateArgument::Expression:
1423 if (Expr *E = TAL.getSourceExpression())
1424 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1427 case TemplateArgument::Template:
1428 case TemplateArgument::TemplateExpansion:
1429 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1432 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1433 TAL.getTemplateNameLoc());
1436 llvm_unreachable("Invalid TemplateArgument::Kind!");
1439 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1440 return VisitDeclContext(D);
1443 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1444 return Visit(TL.getUnqualifiedLoc());
1447 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1448 ASTContext &Context = AU->getASTContext();
1450 // Some builtin types (such as Objective-C's "id", "sel", and
1451 // "Class") have associated declarations. Create cursors for those.
1453 switch (TL.getTypePtr()->getKind()) {
1455 case BuiltinType::Void:
1456 case BuiltinType::NullPtr:
1457 case BuiltinType::Dependent:
1458 case BuiltinType::OCLImage1d:
1459 case BuiltinType::OCLImage1dArray:
1460 case BuiltinType::OCLImage1dBuffer:
1461 case BuiltinType::OCLImage2d:
1462 case BuiltinType::OCLImage2dArray:
1463 case BuiltinType::OCLImage2dDepth:
1464 case BuiltinType::OCLImage2dArrayDepth:
1465 case BuiltinType::OCLImage2dMSAA:
1466 case BuiltinType::OCLImage2dArrayMSAA:
1467 case BuiltinType::OCLImage2dMSAADepth:
1468 case BuiltinType::OCLImage2dArrayMSAADepth:
1469 case BuiltinType::OCLImage3d:
1470 case BuiltinType::OCLSampler:
1471 case BuiltinType::OCLEvent:
1472 case BuiltinType::OCLClkEvent:
1473 case BuiltinType::OCLQueue:
1474 case BuiltinType::OCLNDRange:
1475 case BuiltinType::OCLReserveID:
1476 #define BUILTIN_TYPE(Id, SingletonId)
1477 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1478 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1479 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1480 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1481 #include "clang/AST/BuiltinTypes.def"
1484 case BuiltinType::ObjCId:
1485 VisitType = Context.getObjCIdType();
1488 case BuiltinType::ObjCClass:
1489 VisitType = Context.getObjCClassType();
1492 case BuiltinType::ObjCSel:
1493 VisitType = Context.getObjCSelType();
1497 if (!VisitType.isNull()) {
1498 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1499 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1506 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1507 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1510 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1511 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1514 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1515 if (TL.isDefinition())
1516 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1518 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1521 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1522 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1525 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1526 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1529 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1530 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1533 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1534 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1538 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1539 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1547 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1548 return Visit(TL.getPointeeLoc());
1551 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1552 return Visit(TL.getInnerLoc());
1555 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1556 return Visit(TL.getPointeeLoc());
1559 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1560 return Visit(TL.getPointeeLoc());
1563 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1564 return Visit(TL.getPointeeLoc());
1567 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1568 return Visit(TL.getPointeeLoc());
1571 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1572 return Visit(TL.getPointeeLoc());
1575 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1576 return Visit(TL.getModifiedLoc());
1579 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1580 bool SkipResultType) {
1581 if (!SkipResultType && Visit(TL.getReturnLoc()))
1584 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1585 if (Decl *D = TL.getParam(I))
1586 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1592 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1593 if (Visit(TL.getElementLoc()))
1596 if (Expr *Size = TL.getSizeExpr())
1597 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1602 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1603 return Visit(TL.getOriginalLoc());
1606 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1607 return Visit(TL.getOriginalLoc());
1610 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1611 TemplateSpecializationTypeLoc TL) {
1612 // Visit the template name.
1613 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1614 TL.getTemplateNameLoc()))
1617 // Visit the template arguments.
1618 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1619 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1625 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1626 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1629 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1630 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1631 return Visit(TSInfo->getTypeLoc());
1636 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1637 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1638 return Visit(TSInfo->getTypeLoc());
1643 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1644 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1647 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1648 DependentTemplateSpecializationTypeLoc TL) {
1649 // Visit the nested-name-specifier, if there is one.
1650 if (TL.getQualifierLoc() &&
1651 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1654 // Visit the template arguments.
1655 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1656 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1662 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1663 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1666 return Visit(TL.getNamedTypeLoc());
1669 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1670 return Visit(TL.getPatternLoc());
1673 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1674 if (Expr *E = TL.getUnderlyingExpr())
1675 return Visit(MakeCXCursor(E, StmtParent, TU));
1680 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1681 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1684 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1685 return Visit(TL.getValueLoc());
1688 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1689 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1690 return Visit##PARENT##Loc(TL); \
1693 DEFAULT_TYPELOC_IMPL(Complex, Type)
1694 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1695 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1696 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1697 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1698 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1699 DEFAULT_TYPELOC_IMPL(Vector, Type)
1700 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1701 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1702 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1703 DEFAULT_TYPELOC_IMPL(Record, TagType)
1704 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1705 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1706 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1707 DEFAULT_TYPELOC_IMPL(Auto, Type)
1709 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1710 // Visit the nested-name-specifier, if present.
1711 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1712 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1715 if (D->isCompleteDefinition()) {
1716 for (const auto &I : D->bases()) {
1717 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1722 return VisitTagDecl(D);
1725 bool CursorVisitor::VisitAttributes(Decl *D) {
1726 for (const auto *I : D->attrs())
1727 if (Visit(MakeCXCursor(I, D, TU)))
1733 //===----------------------------------------------------------------------===//
1734 // Data-recursive visitor methods.
1735 //===----------------------------------------------------------------------===//
1738 #define DEF_JOB(NAME, DATA, KIND)\
1739 class NAME : public VisitorJob {\
1741 NAME(const DATA *d, CXCursor parent) : \
1742 VisitorJob(parent, VisitorJob::KIND, d) {} \
1743 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1744 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1747 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1748 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1749 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1750 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1751 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1752 ExplicitTemplateArgsVisitKind)
1753 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1754 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1755 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1758 class DeclVisit : public VisitorJob {
1760 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1761 VisitorJob(parent, VisitorJob::DeclVisitKind,
1762 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1763 static bool classof(const VisitorJob *VJ) {
1764 return VJ->getKind() == DeclVisitKind;
1766 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1767 bool isFirst() const { return data[1] != nullptr; }
1769 class TypeLocVisit : public VisitorJob {
1771 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1772 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1773 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1775 static bool classof(const VisitorJob *VJ) {
1776 return VJ->getKind() == TypeLocVisitKind;
1779 TypeLoc get() const {
1780 QualType T = QualType::getFromOpaquePtr(data[0]);
1781 return TypeLoc(T, const_cast<void *>(data[1]));
1785 class LabelRefVisit : public VisitorJob {
1787 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1788 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1789 labelLoc.getPtrEncoding()) {}
1791 static bool classof(const VisitorJob *VJ) {
1792 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1794 const LabelDecl *get() const {
1795 return static_cast<const LabelDecl *>(data[0]);
1797 SourceLocation getLoc() const {
1798 return SourceLocation::getFromPtrEncoding(data[1]); }
1801 class NestedNameSpecifierLocVisit : public VisitorJob {
1803 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1804 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1805 Qualifier.getNestedNameSpecifier(),
1806 Qualifier.getOpaqueData()) { }
1808 static bool classof(const VisitorJob *VJ) {
1809 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1812 NestedNameSpecifierLoc get() const {
1813 return NestedNameSpecifierLoc(
1814 const_cast<NestedNameSpecifier *>(
1815 static_cast<const NestedNameSpecifier *>(data[0])),
1816 const_cast<void *>(data[1]));
1820 class DeclarationNameInfoVisit : public VisitorJob {
1822 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1823 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1824 static bool classof(const VisitorJob *VJ) {
1825 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1827 DeclarationNameInfo get() const {
1828 const Stmt *S = static_cast<const Stmt *>(data[0]);
1829 switch (S->getStmtClass()) {
1831 llvm_unreachable("Unhandled Stmt");
1832 case clang::Stmt::MSDependentExistsStmtClass:
1833 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1834 case Stmt::CXXDependentScopeMemberExprClass:
1835 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1836 case Stmt::DependentScopeDeclRefExprClass:
1837 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1838 case Stmt::OMPCriticalDirectiveClass:
1839 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1843 class MemberRefVisit : public VisitorJob {
1845 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1846 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1847 L.getPtrEncoding()) {}
1848 static bool classof(const VisitorJob *VJ) {
1849 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1851 const FieldDecl *get() const {
1852 return static_cast<const FieldDecl *>(data[0]);
1854 SourceLocation getLoc() const {
1855 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1858 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1859 friend class OMPClauseEnqueue;
1860 VisitorWorkList &WL;
1863 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1864 : WL(wl), Parent(parent) {}
1866 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1867 void VisitBlockExpr(const BlockExpr *B);
1868 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1869 void VisitCompoundStmt(const CompoundStmt *S);
1870 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1871 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1872 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1873 void VisitCXXNewExpr(const CXXNewExpr *E);
1874 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1875 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1876 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1877 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1878 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1879 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1880 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1881 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1882 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1883 void VisitDeclRefExpr(const DeclRefExpr *D);
1884 void VisitDeclStmt(const DeclStmt *S);
1885 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1886 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1887 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1888 void VisitForStmt(const ForStmt *FS);
1889 void VisitGotoStmt(const GotoStmt *GS);
1890 void VisitIfStmt(const IfStmt *If);
1891 void VisitInitListExpr(const InitListExpr *IE);
1892 void VisitMemberExpr(const MemberExpr *M);
1893 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1894 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1895 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1896 void VisitOverloadExpr(const OverloadExpr *E);
1897 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1898 void VisitStmt(const Stmt *S);
1899 void VisitSwitchStmt(const SwitchStmt *S);
1900 void VisitWhileStmt(const WhileStmt *W);
1901 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1902 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1903 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1904 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1905 void VisitVAArgExpr(const VAArgExpr *E);
1906 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1907 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1908 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1909 void VisitLambdaExpr(const LambdaExpr *E);
1910 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1911 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1912 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1913 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1914 void VisitOMPForDirective(const OMPForDirective *D);
1915 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1916 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1917 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1918 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1919 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1920 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1921 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1922 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1923 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1924 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1925 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1926 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1927 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1928 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1930 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1931 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1932 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1933 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1934 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1935 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1936 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1937 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1940 void AddDeclarationNameInfo(const Stmt *S);
1941 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1942 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1943 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1944 void AddStmt(const Stmt *S);
1945 void AddDecl(const Decl *D, bool isFirst = true);
1946 void AddTypeLoc(TypeSourceInfo *TI);
1947 void EnqueueChildren(const Stmt *S);
1948 void EnqueueChildren(const OMPClause *S);
1950 } // end anonyous namespace
1952 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1953 // 'S' should always be non-null, since it comes from the
1954 // statement we are visiting.
1955 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1959 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1961 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1964 void EnqueueVisitor::AddStmt(const Stmt *S) {
1966 WL.push_back(StmtVisit(S, Parent));
1968 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1970 WL.push_back(DeclVisit(D, Parent, isFirst));
1972 void EnqueueVisitor::
1973 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1975 WL.push_back(ExplicitTemplateArgsVisit(A, Parent));
1977 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
1979 WL.push_back(MemberRefVisit(D, L, Parent));
1981 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1983 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1985 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
1986 unsigned size = WL.size();
1987 for (const Stmt *SubStmt : S->children()) {
1990 if (size == WL.size())
1992 // Now reverse the entries we just added. This will match the DFS
1993 // ordering performed by the worklist.
1994 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1998 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
1999 EnqueueVisitor *Visitor;
2000 /// \brief Process clauses with list of variables.
2001 template <typename T>
2002 void VisitOMPClauseList(T *Node);
2004 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2005 #define OPENMP_CLAUSE(Name, Class) \
2006 void Visit##Class(const Class *C);
2007 #include "clang/Basic/OpenMPKinds.def"
2010 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2011 Visitor->AddStmt(C->getCondition());
2014 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2015 Visitor->AddStmt(C->getCondition());
2018 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2019 Visitor->AddStmt(C->getNumThreads());
2022 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2023 Visitor->AddStmt(C->getSafelen());
2026 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2027 Visitor->AddStmt(C->getSimdlen());
2030 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2031 Visitor->AddStmt(C->getNumForLoops());
2034 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2036 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2038 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2039 Visitor->AddStmt(C->getChunkSize());
2040 Visitor->AddStmt(C->getHelperChunkSize());
2043 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2044 Visitor->AddStmt(C->getNumForLoops());
2047 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2049 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2051 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2053 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2055 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2057 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2059 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2061 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2063 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2065 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2067 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2068 Visitor->AddStmt(C->getDevice());
2071 template<typename T>
2072 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2073 for (const auto *I : Node->varlists()) {
2074 Visitor->AddStmt(I);
2078 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2079 VisitOMPClauseList(C);
2080 for (const auto *E : C->private_copies()) {
2081 Visitor->AddStmt(E);
2084 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2085 const OMPFirstprivateClause *C) {
2086 VisitOMPClauseList(C);
2088 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2089 const OMPLastprivateClause *C) {
2090 VisitOMPClauseList(C);
2091 for (auto *E : C->private_copies()) {
2092 Visitor->AddStmt(E);
2094 for (auto *E : C->source_exprs()) {
2095 Visitor->AddStmt(E);
2097 for (auto *E : C->destination_exprs()) {
2098 Visitor->AddStmt(E);
2100 for (auto *E : C->assignment_ops()) {
2101 Visitor->AddStmt(E);
2104 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2105 VisitOMPClauseList(C);
2107 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2108 VisitOMPClauseList(C);
2109 for (auto *E : C->privates()) {
2110 Visitor->AddStmt(E);
2112 for (auto *E : C->lhs_exprs()) {
2113 Visitor->AddStmt(E);
2115 for (auto *E : C->rhs_exprs()) {
2116 Visitor->AddStmt(E);
2118 for (auto *E : C->reduction_ops()) {
2119 Visitor->AddStmt(E);
2122 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2123 VisitOMPClauseList(C);
2124 for (const auto *E : C->privates()) {
2125 Visitor->AddStmt(E);
2127 for (const auto *E : C->inits()) {
2128 Visitor->AddStmt(E);
2130 for (const auto *E : C->updates()) {
2131 Visitor->AddStmt(E);
2133 for (const auto *E : C->finals()) {
2134 Visitor->AddStmt(E);
2136 Visitor->AddStmt(C->getStep());
2137 Visitor->AddStmt(C->getCalcStep());
2139 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2140 VisitOMPClauseList(C);
2141 Visitor->AddStmt(C->getAlignment());
2143 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2144 VisitOMPClauseList(C);
2145 for (auto *E : C->source_exprs()) {
2146 Visitor->AddStmt(E);
2148 for (auto *E : C->destination_exprs()) {
2149 Visitor->AddStmt(E);
2151 for (auto *E : C->assignment_ops()) {
2152 Visitor->AddStmt(E);
2156 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2157 VisitOMPClauseList(C);
2158 for (auto *E : C->source_exprs()) {
2159 Visitor->AddStmt(E);
2161 for (auto *E : C->destination_exprs()) {
2162 Visitor->AddStmt(E);
2164 for (auto *E : C->assignment_ops()) {
2165 Visitor->AddStmt(E);
2168 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2169 VisitOMPClauseList(C);
2171 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2172 VisitOMPClauseList(C);
2176 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2177 unsigned size = WL.size();
2178 OMPClauseEnqueue Visitor(this);
2180 if (size == WL.size())
2182 // Now reverse the entries we just added. This will match the DFS
2183 // ordering performed by the worklist.
2184 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2187 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2188 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2190 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2191 AddDecl(B->getBlockDecl());
2193 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2195 AddTypeLoc(E->getTypeSourceInfo());
2197 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2198 for (auto &I : llvm::reverse(S->body()))
2201 void EnqueueVisitor::
2202 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2203 AddStmt(S->getSubStmt());
2204 AddDeclarationNameInfo(S);
2205 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2206 AddNestedNameSpecifierLoc(QualifierLoc);
2209 void EnqueueVisitor::
2210 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2211 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2212 AddDeclarationNameInfo(E);
2213 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2214 AddNestedNameSpecifierLoc(QualifierLoc);
2215 if (!E->isImplicitAccess())
2216 AddStmt(E->getBase());
2218 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2219 // Enqueue the initializer , if any.
2220 AddStmt(E->getInitializer());
2221 // Enqueue the array size, if any.
2222 AddStmt(E->getArraySize());
2223 // Enqueue the allocated type.
2224 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2225 // Enqueue the placement arguments.
2226 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2227 AddStmt(E->getPlacementArg(I-1));
2229 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2230 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2231 AddStmt(CE->getArg(I-1));
2232 AddStmt(CE->getCallee());
2233 AddStmt(CE->getArg(0));
2235 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2236 const CXXPseudoDestructorExpr *E) {
2237 // Visit the name of the type being destroyed.
2238 AddTypeLoc(E->getDestroyedTypeInfo());
2239 // Visit the scope type that looks disturbingly like the nested-name-specifier
2241 AddTypeLoc(E->getScopeTypeInfo());
2242 // Visit the nested-name-specifier.
2243 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2244 AddNestedNameSpecifierLoc(QualifierLoc);
2245 // Visit base expression.
2246 AddStmt(E->getBase());
2248 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2249 const CXXScalarValueInitExpr *E) {
2250 AddTypeLoc(E->getTypeSourceInfo());
2252 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2253 const CXXTemporaryObjectExpr *E) {
2255 AddTypeLoc(E->getTypeSourceInfo());
2257 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2259 if (E->isTypeOperand())
2260 AddTypeLoc(E->getTypeOperandSourceInfo());
2263 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2264 const CXXUnresolvedConstructExpr *E) {
2266 AddTypeLoc(E->getTypeSourceInfo());
2268 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2270 if (E->isTypeOperand())
2271 AddTypeLoc(E->getTypeOperandSourceInfo());
2274 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2276 AddDecl(S->getExceptionDecl());
2279 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2280 AddStmt(S->getBody());
2281 AddStmt(S->getRangeInit());
2282 AddDecl(S->getLoopVariable());
2285 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2286 if (DR->hasExplicitTemplateArgs()) {
2287 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
2289 WL.push_back(DeclRefExprParts(DR, Parent));
2291 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2292 const DependentScopeDeclRefExpr *E) {
2293 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2294 AddDeclarationNameInfo(E);
2295 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2297 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2298 unsigned size = WL.size();
2299 bool isFirst = true;
2300 for (const auto *D : S->decls()) {
2301 AddDecl(D, isFirst);
2304 if (size == WL.size())
2306 // Now reverse the entries we just added. This will match the DFS
2307 // ordering performed by the worklist.
2308 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2311 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2312 AddStmt(E->getInit());
2313 for (DesignatedInitExpr::const_reverse_designators_iterator
2314 D = E->designators_rbegin(), DEnd = E->designators_rend();
2316 if (D->isFieldDesignator()) {
2317 if (FieldDecl *Field = D->getField())
2318 AddMemberRef(Field, D->getFieldLoc());
2321 if (D->isArrayDesignator()) {
2322 AddStmt(E->getArrayIndex(*D));
2325 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2326 AddStmt(E->getArrayRangeEnd(*D));
2327 AddStmt(E->getArrayRangeStart(*D));
2330 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2332 AddTypeLoc(E->getTypeInfoAsWritten());
2334 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2335 AddStmt(FS->getBody());
2336 AddStmt(FS->getInc());
2337 AddStmt(FS->getCond());
2338 AddDecl(FS->getConditionVariable());
2339 AddStmt(FS->getInit());
2341 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2342 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2344 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2345 AddStmt(If->getElse());
2346 AddStmt(If->getThen());
2347 AddStmt(If->getCond());
2348 AddDecl(If->getConditionVariable());
2350 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2351 // We care about the syntactic form of the initializer list, only.
2352 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2354 EnqueueChildren(IE);
2356 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2357 WL.push_back(MemberExprParts(M, Parent));
2359 // If the base of the member access expression is an implicit 'this', don't
2361 // FIXME: If we ever want to show these implicit accesses, this will be
2362 // unfortunate. However, clang_getCursor() relies on this behavior.
2363 if (M->isImplicitAccess())
2366 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2367 // real field that that we are interested in.
2368 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2369 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2370 if (FD->isAnonymousStructOrUnion()) {
2371 AddStmt(SubME->getBase());
2377 AddStmt(M->getBase());
2379 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2380 AddTypeLoc(E->getEncodedTypeSourceInfo());
2382 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2384 AddTypeLoc(M->getClassReceiverTypeInfo());
2386 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2387 // Visit the components of the offsetof expression.
2388 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2389 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2390 const OffsetOfNode &Node = E->getComponent(I-1);
2391 switch (Node.getKind()) {
2392 case OffsetOfNode::Array:
2393 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2395 case OffsetOfNode::Field:
2396 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2398 case OffsetOfNode::Identifier:
2399 case OffsetOfNode::Base:
2403 // Visit the type into which we're computing the offset.
2404 AddTypeLoc(E->getTypeSourceInfo());
2406 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2407 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2408 WL.push_back(OverloadExprParts(E, Parent));
2410 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2411 const UnaryExprOrTypeTraitExpr *E) {
2413 if (E->isArgumentType())
2414 AddTypeLoc(E->getArgumentTypeInfo());
2416 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2419 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2420 AddStmt(S->getBody());
2421 AddStmt(S->getCond());
2422 AddDecl(S->getConditionVariable());
2425 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2426 AddStmt(W->getBody());
2427 AddStmt(W->getCond());
2428 AddDecl(W->getConditionVariable());
2431 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2432 for (unsigned I = E->getNumArgs(); I > 0; --I)
2433 AddTypeLoc(E->getArg(I-1));
2436 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2437 AddTypeLoc(E->getQueriedTypeSourceInfo());
2440 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2444 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2445 VisitOverloadExpr(U);
2446 if (!U->isImplicitAccess())
2447 AddStmt(U->getBase());
2449 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2450 AddStmt(E->getSubExpr());
2451 AddTypeLoc(E->getWrittenTypeInfo());
2453 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2454 WL.push_back(SizeOfPackExprParts(E, Parent));
2456 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2457 // If the opaque value has a source expression, just transparently
2458 // visit that. This is useful for (e.g.) pseudo-object expressions.
2459 if (Expr *SourceExpr = E->getSourceExpr())
2460 return Visit(SourceExpr);
2462 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2463 AddStmt(E->getBody());
2464 WL.push_back(LambdaExprParts(E, Parent));
2466 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2467 // Treat the expression like its syntactic form.
2468 Visit(E->getSyntacticForm());
2471 void EnqueueVisitor::VisitOMPExecutableDirective(
2472 const OMPExecutableDirective *D) {
2474 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2475 E = D->clauses().end();
2477 EnqueueChildren(*I);
2480 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2481 VisitOMPExecutableDirective(D);
2484 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2485 VisitOMPExecutableDirective(D);
2488 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2489 VisitOMPLoopDirective(D);
2492 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2493 VisitOMPLoopDirective(D);
2496 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2497 VisitOMPLoopDirective(D);
2500 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2501 VisitOMPExecutableDirective(D);
2504 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2505 VisitOMPExecutableDirective(D);
2508 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2509 VisitOMPExecutableDirective(D);
2512 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2513 VisitOMPExecutableDirective(D);
2516 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2517 VisitOMPExecutableDirective(D);
2518 AddDeclarationNameInfo(D);
2522 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2523 VisitOMPLoopDirective(D);
2526 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2527 const OMPParallelForSimdDirective *D) {
2528 VisitOMPLoopDirective(D);
2531 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2532 const OMPParallelSectionsDirective *D) {
2533 VisitOMPExecutableDirective(D);
2536 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2537 VisitOMPExecutableDirective(D);
2541 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2542 VisitOMPExecutableDirective(D);
2545 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2546 VisitOMPExecutableDirective(D);
2549 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2550 VisitOMPExecutableDirective(D);
2553 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2554 const OMPTaskgroupDirective *D) {
2555 VisitOMPExecutableDirective(D);
2558 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2559 VisitOMPExecutableDirective(D);
2562 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2563 VisitOMPExecutableDirective(D);
2566 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2567 VisitOMPExecutableDirective(D);
2570 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2571 VisitOMPExecutableDirective(D);
2574 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2575 OMPTargetDataDirective *D) {
2576 VisitOMPExecutableDirective(D);
2579 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2580 VisitOMPExecutableDirective(D);
2583 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2584 const OMPCancellationPointDirective *D) {
2585 VisitOMPExecutableDirective(D);
2588 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2589 VisitOMPExecutableDirective(D);
2592 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2593 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2596 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2597 if (RegionOfInterest.isValid()) {
2598 SourceRange Range = getRawCursorExtent(C);
2599 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2605 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2606 while (!WL.empty()) {
2607 // Dequeue the worklist item.
2608 VisitorJob LI = WL.pop_back_val();
2610 // Set the Parent field, then back to its old value once we're done.
2611 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2613 switch (LI.getKind()) {
2614 case VisitorJob::DeclVisitKind: {
2615 const Decl *D = cast<DeclVisit>(&LI)->get();
2619 // For now, perform default visitation for Decls.
2620 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2621 cast<DeclVisit>(&LI)->isFirst())))
2626 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2627 const ASTTemplateArgumentListInfo *ArgList =
2628 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2629 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2630 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2631 Arg != ArgEnd; ++Arg) {
2632 if (VisitTemplateArgumentLoc(*Arg))
2637 case VisitorJob::TypeLocVisitKind: {
2638 // Perform default visitation for TypeLocs.
2639 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2643 case VisitorJob::LabelRefVisitKind: {
2644 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2645 if (LabelStmt *stmt = LS->getStmt()) {
2646 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2654 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2655 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2656 if (VisitNestedNameSpecifierLoc(V->get()))
2661 case VisitorJob::DeclarationNameInfoVisitKind: {
2662 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2667 case VisitorJob::MemberRefVisitKind: {
2668 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2669 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2673 case VisitorJob::StmtVisitKind: {
2674 const Stmt *S = cast<StmtVisit>(&LI)->get();
2678 // Update the current cursor.
2679 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2680 if (!IsInRegionOfInterest(Cursor))
2682 switch (Visitor(Cursor, Parent, ClientData)) {
2683 case CXChildVisit_Break: return true;
2684 case CXChildVisit_Continue: break;
2685 case CXChildVisit_Recurse:
2686 if (PostChildrenVisitor)
2687 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2688 EnqueueWorkList(WL, S);
2693 case VisitorJob::MemberExprPartsKind: {
2694 // Handle the other pieces in the MemberExpr besides the base.
2695 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2697 // Visit the nested-name-specifier
2698 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2699 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2702 // Visit the declaration name.
2703 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2706 // Visit the explicitly-specified template arguments, if any.
2707 if (M->hasExplicitTemplateArgs()) {
2708 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2709 *ArgEnd = Arg + M->getNumTemplateArgs();
2710 Arg != ArgEnd; ++Arg) {
2711 if (VisitTemplateArgumentLoc(*Arg))
2717 case VisitorJob::DeclRefExprPartsKind: {
2718 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2719 // Visit nested-name-specifier, if present.
2720 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2721 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2723 // Visit declaration name.
2724 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2728 case VisitorJob::OverloadExprPartsKind: {
2729 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2730 // Visit the nested-name-specifier.
2731 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2732 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2734 // Visit the declaration name.
2735 if (VisitDeclarationNameInfo(O->getNameInfo()))
2737 // Visit the overloaded declaration reference.
2738 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2742 case VisitorJob::SizeOfPackExprPartsKind: {
2743 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2744 NamedDecl *Pack = E->getPack();
2745 if (isa<TemplateTypeParmDecl>(Pack)) {
2746 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2747 E->getPackLoc(), TU)))
2753 if (isa<TemplateTemplateParmDecl>(Pack)) {
2754 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2755 E->getPackLoc(), TU)))
2761 // Non-type template parameter packs and function parameter packs are
2762 // treated like DeclRefExpr cursors.
2766 case VisitorJob::LambdaExprPartsKind: {
2768 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2769 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2770 CEnd = E->explicit_capture_end();
2772 // FIXME: Lambda init-captures.
2773 if (!C->capturesVariable())
2776 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2782 // Visit parameters and return type, if present.
2783 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2784 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2785 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2786 // Visit the whole type.
2789 } else if (FunctionProtoTypeLoc Proto =
2790 TL.getAs<FunctionProtoTypeLoc>()) {
2791 if (E->hasExplicitParameters()) {
2792 // Visit parameters.
2793 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2794 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2797 // Visit result type.
2798 if (Visit(Proto.getReturnLoc()))
2806 case VisitorJob::PostChildrenVisitKind:
2807 if (PostChildrenVisitor(Parent, ClientData))
2815 bool CursorVisitor::Visit(const Stmt *S) {
2816 VisitorWorkList *WL = nullptr;
2817 if (!WorkListFreeList.empty()) {
2818 WL = WorkListFreeList.back();
2820 WorkListFreeList.pop_back();
2823 WL = new VisitorWorkList();
2824 WorkListCache.push_back(WL);
2826 EnqueueWorkList(*WL, S);
2827 bool result = RunVisitorWorkList(*WL);
2828 WorkListFreeList.push_back(WL);
2833 typedef SmallVector<SourceRange, 4> RefNamePieces;
2835 buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2836 const DeclarationNameInfo &NI, SourceRange QLoc,
2837 const ASTTemplateArgumentListInfo *TemplateArgs = nullptr) {
2838 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2839 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2840 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2842 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2844 RefNamePieces Pieces;
2846 if (WantQualifier && QLoc.isValid())
2847 Pieces.push_back(QLoc);
2849 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2850 Pieces.push_back(NI.getLoc());
2852 if (WantTemplateArgs && TemplateArgs)
2853 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2854 TemplateArgs->RAngleLoc));
2856 if (Kind == DeclarationName::CXXOperatorName) {
2857 Pieces.push_back(SourceLocation::getFromRawEncoding(
2858 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2859 Pieces.push_back(SourceLocation::getFromRawEncoding(
2860 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2863 if (WantSinglePiece) {
2864 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2866 Pieces.push_back(R);
2873 //===----------------------------------------------------------------------===//
2875 //===----------------------------------------------------------------------===//
2877 static void fatal_error_handler(void *user_data, const std::string& reason,
2878 bool gen_crash_diag) {
2879 // Write the result out to stderr avoiding errs() because raw_ostreams can
2880 // call report_fatal_error.
2881 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2886 struct RegisterFatalErrorHandler {
2887 RegisterFatalErrorHandler() {
2888 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
2893 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
2896 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2897 int displayDiagnostics) {
2898 // We use crash recovery to make some of our APIs more reliable, implicitly
2900 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
2901 llvm::CrashRecoveryContext::Enable();
2903 // Look through the managed static to trigger construction of the managed
2904 // static which registers our fatal error handler. This ensures it is only
2906 (void)*RegisterFatalErrorHandlerOnce;
2908 // Initialize targets for clang module support.
2909 llvm::InitializeAllTargets();
2910 llvm::InitializeAllTargetMCs();
2911 llvm::InitializeAllAsmPrinters();
2912 llvm::InitializeAllAsmParsers();
2914 CIndexer *CIdxr = new CIndexer();
2916 if (excludeDeclarationsFromPCH)
2917 CIdxr->setOnlyLocalDecls();
2918 if (displayDiagnostics)
2919 CIdxr->setDisplayDiagnostics();
2921 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2922 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2923 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2924 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2925 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2926 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2931 void clang_disposeIndex(CXIndex CIdx) {
2933 delete static_cast<CIndexer *>(CIdx);
2936 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2938 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2941 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2943 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2947 void clang_toggleCrashRecovery(unsigned isEnabled) {
2949 llvm::CrashRecoveryContext::Enable();
2951 llvm::CrashRecoveryContext::Disable();
2954 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2955 const char *ast_filename) {
2956 CXTranslationUnit TU;
2957 enum CXErrorCode Result =
2958 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
2960 assert((TU && Result == CXError_Success) ||
2961 (!TU && Result != CXError_Success));
2965 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
2966 const char *ast_filename,
2967 CXTranslationUnit *out_TU) {
2971 if (!CIdx || !ast_filename || !out_TU)
2972 return CXError_InvalidArguments;
2975 *Log << ast_filename;
2978 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2979 FileSystemOptions FileSystemOpts;
2981 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
2982 CompilerInstance::createDiagnostics(new DiagnosticOptions());
2983 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
2984 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
2985 FileSystemOpts, /*UseDebugInfo=*/false,
2986 CXXIdx->getOnlyLocalDecls(), None,
2987 /*CaptureDiagnostics=*/true,
2988 /*AllowPCHWithCompilerErrors=*/true,
2989 /*UserFilesAreVolatile=*/true);
2990 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
2991 return *out_TU ? CXError_Success : CXError_Failure;
2994 unsigned clang_defaultEditingTranslationUnitOptions() {
2995 return CXTranslationUnit_PrecompiledPreamble |
2996 CXTranslationUnit_CacheCompletionResults;
3000 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3001 const char *source_filename,
3002 int num_command_line_args,
3003 const char * const *command_line_args,
3004 unsigned num_unsaved_files,
3005 struct CXUnsavedFile *unsaved_files) {
3006 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3007 return clang_parseTranslationUnit(CIdx, source_filename,
3008 command_line_args, num_command_line_args,
3009 unsaved_files, num_unsaved_files,
3014 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3015 const char *const *command_line_args,
3016 int num_command_line_args,
3017 ArrayRef<CXUnsavedFile> unsaved_files,
3018 unsigned options, CXTranslationUnit *out_TU) {
3019 // Set up the initial return values.
3024 if (!CIdx || !out_TU)
3025 return CXError_InvalidArguments;
3027 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3029 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3030 setThreadBackgroundPriority();
3032 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3033 // FIXME: Add a flag for modules.
3034 TranslationUnitKind TUKind
3035 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3036 bool CacheCodeCompletionResults
3037 = options & CXTranslationUnit_CacheCompletionResults;
3038 bool IncludeBriefCommentsInCodeCompletion
3039 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3040 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3041 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3043 // Configure the diagnostics.
3044 IntrusiveRefCntPtr<DiagnosticsEngine>
3045 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3047 // Recover resources if we crash before exiting this function.
3048 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3049 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3050 DiagCleanup(Diags.get());
3052 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3053 new std::vector<ASTUnit::RemappedFile>());
3055 // Recover resources if we crash before exiting this function.
3056 llvm::CrashRecoveryContextCleanupRegistrar<
3057 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3059 for (auto &UF : unsaved_files) {
3060 std::unique_ptr<llvm::MemoryBuffer> MB =
3061 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3062 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3065 std::unique_ptr<std::vector<const char *>> Args(
3066 new std::vector<const char *>());
3068 // Recover resources if we crash before exiting this method.
3069 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3070 ArgsCleanup(Args.get());
3072 // Since the Clang C library is primarily used by batch tools dealing with
3073 // (often very broken) source code, where spell-checking can have a
3074 // significant negative impact on performance (particularly when
3075 // precompiled headers are involved), we disable it by default.
3076 // Only do this if we haven't found a spell-checking-related argument.
3077 bool FoundSpellCheckingArgument = false;
3078 for (int I = 0; I != num_command_line_args; ++I) {
3079 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3080 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3081 FoundSpellCheckingArgument = true;
3085 if (!FoundSpellCheckingArgument)
3086 Args->push_back("-fno-spell-checking");
3088 Args->insert(Args->end(), command_line_args,
3089 command_line_args + num_command_line_args);
3091 // The 'source_filename' argument is optional. If the caller does not
3092 // specify it then it is assumed that the source file is specified
3093 // in the actual argument list.
3094 // Put the source file after command_line_args otherwise if '-x' flag is
3095 // present it will be unused.
3096 if (source_filename)
3097 Args->push_back(source_filename);
3099 // Do we need the detailed preprocessing record?
3100 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3101 Args->push_back("-Xclang");
3102 Args->push_back("-detailed-preprocessing-record");
3105 unsigned NumErrors = Diags->getClient()->getNumErrors();
3106 std::unique_ptr<ASTUnit> ErrUnit;
3107 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3108 Args->data(), Args->data() + Args->size(),
3109 CXXIdx->getPCHContainerOperations(), Diags,
3110 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3111 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3112 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreamble, TUKind,
3113 CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3114 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3115 /*UserFilesAreVolatile=*/true, ForSerialization, &ErrUnit));
3117 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3118 if (!Unit && !ErrUnit)
3119 return CXError_ASTReadError;
3121 if (NumErrors != Diags->getClient()->getNumErrors()) {
3122 // Make sure to check that 'Unit' is non-NULL.
3123 if (CXXIdx->getDisplayDiagnostics())
3124 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3127 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3128 return CXError_ASTReadError;
3130 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3131 return *out_TU ? CXError_Success : CXError_Failure;
3135 clang_parseTranslationUnit(CXIndex CIdx,
3136 const char *source_filename,
3137 const char *const *command_line_args,
3138 int num_command_line_args,
3139 struct CXUnsavedFile *unsaved_files,
3140 unsigned num_unsaved_files,
3142 CXTranslationUnit TU;
3143 enum CXErrorCode Result = clang_parseTranslationUnit2(
3144 CIdx, source_filename, command_line_args, num_command_line_args,
3145 unsaved_files, num_unsaved_files, options, &TU);
3147 assert((TU && Result == CXError_Success) ||
3148 (!TU && Result != CXError_Success));
3152 enum CXErrorCode clang_parseTranslationUnit2(
3154 const char *source_filename,
3155 const char *const *command_line_args,
3156 int num_command_line_args,
3157 struct CXUnsavedFile *unsaved_files,
3158 unsigned num_unsaved_files,
3160 CXTranslationUnit *out_TU) {
3162 *Log << source_filename << ": ";
3163 for (int i = 0; i != num_command_line_args; ++i)
3164 *Log << command_line_args[i] << " ";
3167 if (num_unsaved_files && !unsaved_files)
3168 return CXError_InvalidArguments;
3170 CXErrorCode result = CXError_Failure;
3171 auto ParseTranslationUnitImpl = [=, &result] {
3172 result = clang_parseTranslationUnit_Impl(
3173 CIdx, source_filename, command_line_args, num_command_line_args,
3174 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3176 llvm::CrashRecoveryContext CRC;
3178 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3179 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3180 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3181 fprintf(stderr, " 'command_line_args' : [");
3182 for (int i = 0; i != num_command_line_args; ++i) {
3184 fprintf(stderr, ", ");
3185 fprintf(stderr, "'%s'", command_line_args[i]);
3187 fprintf(stderr, "],\n");
3188 fprintf(stderr, " 'unsaved_files' : [");
3189 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3191 fprintf(stderr, ", ");
3192 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3193 unsaved_files[i].Length);
3195 fprintf(stderr, "],\n");
3196 fprintf(stderr, " 'options' : %d,\n", options);
3197 fprintf(stderr, "}\n");
3199 return CXError_Crashed;
3200 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3201 if (CXTranslationUnit *TU = out_TU)
3202 PrintLibclangResourceUsage(*TU);
3208 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3209 return CXSaveTranslationUnit_None;
3212 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3213 const char *FileName,
3215 CIndexer *CXXIdx = TU->CIdx;
3216 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3217 setThreadBackgroundPriority();
3219 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3220 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3223 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3226 *Log << TU << ' ' << FileName;
3229 if (isNotUsableTU(TU)) {
3231 return CXSaveError_InvalidTU;
3234 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3235 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3236 if (!CXXUnit->hasSema())
3237 return CXSaveError_InvalidTU;
3240 auto SaveTranslationUnitImpl = [=, &result]() {
3241 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3244 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3245 getenv("LIBCLANG_NOTHREADS")) {
3246 SaveTranslationUnitImpl();
3248 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3249 PrintLibclangResourceUsage(TU);
3254 // We have an AST that has invalid nodes due to compiler errors.
3255 // Use a crash recovery thread for protection.
3257 llvm::CrashRecoveryContext CRC;
3259 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3260 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3261 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3262 fprintf(stderr, " 'options' : %d,\n", options);
3263 fprintf(stderr, "}\n");
3265 return CXSaveError_Unknown;
3267 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3268 PrintLibclangResourceUsage(TU);
3274 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3276 // If the translation unit has been marked as unsafe to free, just discard
3278 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3279 if (Unit && Unit->isUnsafeToFree())
3282 delete cxtu::getASTUnit(CTUnit);
3283 delete CTUnit->StringPool;
3284 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3285 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3286 delete CTUnit->CommentToXML;
3291 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3292 return CXReparse_None;
3296 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3297 ArrayRef<CXUnsavedFile> unsaved_files,
3300 if (isNotUsableTU(TU)) {
3302 return CXError_InvalidArguments;
3305 // Reset the associated diagnostics.
3306 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3307 TU->Diagnostics = nullptr;
3309 CIndexer *CXXIdx = TU->CIdx;
3310 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3311 setThreadBackgroundPriority();
3313 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3314 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3316 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3317 new std::vector<ASTUnit::RemappedFile>());
3319 // Recover resources if we crash before exiting this function.
3320 llvm::CrashRecoveryContextCleanupRegistrar<
3321 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3323 for (auto &UF : unsaved_files) {
3324 std::unique_ptr<llvm::MemoryBuffer> MB =
3325 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3326 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3329 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3330 *RemappedFiles.get()))
3331 return CXError_Success;
3332 if (isASTReadError(CXXUnit))
3333 return CXError_ASTReadError;
3334 return CXError_Failure;
3337 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3338 unsigned num_unsaved_files,
3339 struct CXUnsavedFile *unsaved_files,
3345 if (num_unsaved_files && !unsaved_files)
3346 return CXError_InvalidArguments;
3349 auto ReparseTranslationUnitImpl = [=, &result]() {
3350 result = clang_reparseTranslationUnit_Impl(
3351 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3354 if (getenv("LIBCLANG_NOTHREADS")) {
3355 ReparseTranslationUnitImpl();
3359 llvm::CrashRecoveryContext CRC;
3361 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3362 fprintf(stderr, "libclang: crash detected during reparsing\n");
3363 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3364 return CXError_Crashed;
3365 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3366 PrintLibclangResourceUsage(TU);
3372 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3373 if (isNotUsableTU(CTUnit)) {
3375 return cxstring::createEmpty();
3378 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3379 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3382 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3383 if (isNotUsableTU(TU)) {
3385 return clang_getNullCursor();
3388 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3389 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3392 } // end: extern "C"
3394 //===----------------------------------------------------------------------===//
3395 // CXFile Operations.
3396 //===----------------------------------------------------------------------===//
3399 CXString clang_getFileName(CXFile SFile) {
3401 return cxstring::createNull();
3403 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3404 return cxstring::createRef(FEnt->getName());
3407 time_t clang_getFileTime(CXFile SFile) {
3411 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3412 return FEnt->getModificationTime();
3415 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3416 if (isNotUsableTU(TU)) {
3421 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3423 FileManager &FMgr = CXXUnit->getFileManager();
3424 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3427 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3429 if (isNotUsableTU(TU)) {
3437 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3438 FileEntry *FEnt = static_cast<FileEntry *>(file);
3439 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3440 .isFileMultipleIncludeGuarded(FEnt);
3443 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3444 if (!file || !outID)
3447 FileEntry *FEnt = static_cast<FileEntry *>(file);
3448 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3449 outID->data[0] = ID.getDevice();
3450 outID->data[1] = ID.getFile();
3451 outID->data[2] = FEnt->getModificationTime();
3455 int clang_File_isEqual(CXFile file1, CXFile file2) {
3459 if (!file1 || !file2)
3462 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3463 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3464 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3467 } // end: extern "C"
3469 //===----------------------------------------------------------------------===//
3470 // CXCursor Operations.
3471 //===----------------------------------------------------------------------===//
3473 static const Decl *getDeclFromExpr(const Stmt *E) {
3474 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3475 return getDeclFromExpr(CE->getSubExpr());
3477 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3478 return RefExpr->getDecl();
3479 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3480 return ME->getMemberDecl();
3481 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3482 return RE->getDecl();
3483 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3484 if (PRE->isExplicitProperty())
3485 return PRE->getExplicitProperty();
3486 // It could be messaging both getter and setter as in:
3488 // in which case prefer to associate the setter since it is less obvious
3489 // from inspecting the source that the setter is going to get called.
3490 if (PRE->isMessagingSetter())
3491 return PRE->getImplicitPropertySetter();
3492 return PRE->getImplicitPropertyGetter();
3494 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3495 return getDeclFromExpr(POE->getSyntacticForm());
3496 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3497 if (Expr *Src = OVE->getSourceExpr())
3498 return getDeclFromExpr(Src);
3500 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3501 return getDeclFromExpr(CE->getCallee());
3502 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3503 if (!CE->isElidable())
3504 return CE->getConstructor();
3505 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3506 return OME->getMethodDecl();
3508 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3509 return PE->getProtocol();
3510 if (const SubstNonTypeTemplateParmPackExpr *NTTP
3511 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3512 return NTTP->getParameterPack();
3513 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3514 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3515 isa<ParmVarDecl>(SizeOfPack->getPack()))
3516 return SizeOfPack->getPack();
3521 static SourceLocation getLocationFromExpr(const Expr *E) {
3522 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3523 return getLocationFromExpr(CE->getSubExpr());
3525 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3526 return /*FIXME:*/Msg->getLeftLoc();
3527 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3528 return DRE->getLocation();
3529 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3530 return Member->getMemberLoc();
3531 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3532 return Ivar->getLocation();
3533 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3534 return SizeOfPack->getPackLoc();
3535 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3536 return PropRef->getLocation();
3538 return E->getLocStart();
3543 unsigned clang_visitChildren(CXCursor parent,
3544 CXCursorVisitor visitor,
3545 CXClientData client_data) {
3546 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3547 /*VisitPreprocessorLast=*/false);
3548 return CursorVis.VisitChildren(parent);
3551 #ifndef __has_feature
3552 #define __has_feature(x) 0
3554 #if __has_feature(blocks)
3555 typedef enum CXChildVisitResult
3556 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3558 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3559 CXClientData client_data) {
3560 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3561 return block(cursor, parent);
3564 // If we are compiled with a compiler that doesn't have native blocks support,
3565 // define and call the block manually, so the
3566 typedef struct _CXChildVisitResult
3571 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3573 } *CXCursorVisitorBlock;
3575 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3576 CXClientData client_data) {
3577 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3578 return block->invoke(block, cursor, parent);
3583 unsigned clang_visitChildrenWithBlock(CXCursor parent,
3584 CXCursorVisitorBlock block) {
3585 return clang_visitChildren(parent, visitWithBlock, block);
3588 static CXString getDeclSpelling(const Decl *D) {
3590 return cxstring::createEmpty();
3592 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3594 if (const ObjCPropertyImplDecl *PropImpl =
3595 dyn_cast<ObjCPropertyImplDecl>(D))
3596 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3597 return cxstring::createDup(Property->getIdentifier()->getName());
3599 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3600 if (Module *Mod = ImportD->getImportedModule())
3601 return cxstring::createDup(Mod->getFullModuleName());
3603 return cxstring::createEmpty();
3606 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3607 return cxstring::createDup(OMD->getSelector().getAsString());
3609 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3610 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3611 // and returns different names. NamedDecl returns the class name and
3612 // ObjCCategoryImplDecl returns the category name.
3613 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
3615 if (isa<UsingDirectiveDecl>(D))
3616 return cxstring::createEmpty();
3618 SmallString<1024> S;
3619 llvm::raw_svector_ostream os(S);
3622 return cxstring::createDup(os.str());
3625 CXString clang_getCursorSpelling(CXCursor C) {
3626 if (clang_isTranslationUnit(C.kind))
3627 return clang_getTranslationUnitSpelling(getCursorTU(C));
3629 if (clang_isReference(C.kind)) {
3631 case CXCursor_ObjCSuperClassRef: {
3632 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3633 return cxstring::createRef(Super->getIdentifier()->getNameStart());
3635 case CXCursor_ObjCClassRef: {
3636 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3637 return cxstring::createRef(Class->getIdentifier()->getNameStart());
3639 case CXCursor_ObjCProtocolRef: {
3640 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3641 assert(OID && "getCursorSpelling(): Missing protocol decl");
3642 return cxstring::createRef(OID->getIdentifier()->getNameStart());
3644 case CXCursor_CXXBaseSpecifier: {
3645 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3646 return cxstring::createDup(B->getType().getAsString());
3648 case CXCursor_TypeRef: {
3649 const TypeDecl *Type = getCursorTypeRef(C).first;
3650 assert(Type && "Missing type decl");
3652 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
3655 case CXCursor_TemplateRef: {
3656 const TemplateDecl *Template = getCursorTemplateRef(C).first;
3657 assert(Template && "Missing template decl");
3659 return cxstring::createDup(Template->getNameAsString());
3662 case CXCursor_NamespaceRef: {
3663 const NamedDecl *NS = getCursorNamespaceRef(C).first;
3664 assert(NS && "Missing namespace decl");
3666 return cxstring::createDup(NS->getNameAsString());
3669 case CXCursor_MemberRef: {
3670 const FieldDecl *Field = getCursorMemberRef(C).first;
3671 assert(Field && "Missing member decl");
3673 return cxstring::createDup(Field->getNameAsString());
3676 case CXCursor_LabelRef: {
3677 const LabelStmt *Label = getCursorLabelRef(C).first;
3678 assert(Label && "Missing label");
3680 return cxstring::createRef(Label->getName());
3683 case CXCursor_OverloadedDeclRef: {
3684 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3685 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3686 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3687 return cxstring::createDup(ND->getNameAsString());
3688 return cxstring::createEmpty();
3690 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3691 return cxstring::createDup(E->getName().getAsString());
3692 OverloadedTemplateStorage *Ovl
3693 = Storage.get<OverloadedTemplateStorage*>();
3694 if (Ovl->size() == 0)
3695 return cxstring::createEmpty();
3696 return cxstring::createDup((*Ovl->begin())->getNameAsString());
3699 case CXCursor_VariableRef: {
3700 const VarDecl *Var = getCursorVariableRef(C).first;
3701 assert(Var && "Missing variable decl");
3703 return cxstring::createDup(Var->getNameAsString());
3707 return cxstring::createRef("<not implemented>");
3711 if (clang_isExpression(C.kind)) {
3712 const Expr *E = getCursorExpr(C);
3714 if (C.kind == CXCursor_ObjCStringLiteral ||
3715 C.kind == CXCursor_StringLiteral) {
3716 const StringLiteral *SLit;
3717 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
3718 SLit = OSL->getString();
3720 SLit = cast<StringLiteral>(E);
3722 SmallString<256> Buf;
3723 llvm::raw_svector_ostream OS(Buf);
3724 SLit->outputString(OS);
3725 return cxstring::createDup(OS.str());
3728 const Decl *D = getDeclFromExpr(getCursorExpr(C));
3730 return getDeclSpelling(D);
3731 return cxstring::createEmpty();
3734 if (clang_isStatement(C.kind)) {
3735 const Stmt *S = getCursorStmt(C);
3736 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3737 return cxstring::createRef(Label->getName());
3739 return cxstring::createEmpty();
3742 if (C.kind == CXCursor_MacroExpansion)
3743 return cxstring::createRef(getCursorMacroExpansion(C).getName()
3746 if (C.kind == CXCursor_MacroDefinition)
3747 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
3750 if (C.kind == CXCursor_InclusionDirective)
3751 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
3753 if (clang_isDeclaration(C.kind))
3754 return getDeclSpelling(getCursorDecl(C));
3756 if (C.kind == CXCursor_AnnotateAttr) {
3757 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3758 return cxstring::createDup(AA->getAnnotation());
3761 if (C.kind == CXCursor_AsmLabelAttr) {
3762 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3763 return cxstring::createDup(AA->getLabel());
3766 if (C.kind == CXCursor_PackedAttr) {
3767 return cxstring::createRef("packed");
3770 if (C.kind == CXCursor_VisibilityAttr) {
3771 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
3772 switch (AA->getVisibility()) {
3773 case VisibilityAttr::VisibilityType::Default:
3774 return cxstring::createRef("default");
3775 case VisibilityAttr::VisibilityType::Hidden:
3776 return cxstring::createRef("hidden");
3777 case VisibilityAttr::VisibilityType::Protected:
3778 return cxstring::createRef("protected");
3780 llvm_unreachable("unknown visibility type");
3783 return cxstring::createEmpty();
3786 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3787 unsigned pieceIndex,
3789 if (clang_Cursor_isNull(C))
3790 return clang_getNullRange();
3792 ASTContext &Ctx = getCursorContext(C);
3794 if (clang_isStatement(C.kind)) {
3795 const Stmt *S = getCursorStmt(C);
3796 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3798 return clang_getNullRange();
3799 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3802 return clang_getNullRange();
3805 if (C.kind == CXCursor_ObjCMessageExpr) {
3806 if (const ObjCMessageExpr *
3807 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3808 if (pieceIndex >= ME->getNumSelectorLocs())
3809 return clang_getNullRange();
3810 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3814 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3815 C.kind == CXCursor_ObjCClassMethodDecl) {
3816 if (const ObjCMethodDecl *
3817 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3818 if (pieceIndex >= MD->getNumSelectorLocs())
3819 return clang_getNullRange();
3820 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3824 if (C.kind == CXCursor_ObjCCategoryDecl ||
3825 C.kind == CXCursor_ObjCCategoryImplDecl) {
3827 return clang_getNullRange();
3828 if (const ObjCCategoryDecl *
3829 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3830 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3831 if (const ObjCCategoryImplDecl *
3832 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3833 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3836 if (C.kind == CXCursor_ModuleImportDecl) {
3838 return clang_getNullRange();
3839 if (const ImportDecl *ImportD =
3840 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3841 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3843 return cxloc::translateSourceRange(Ctx,
3844 SourceRange(Locs.front(), Locs.back()));
3846 return clang_getNullRange();
3849 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
3850 C.kind == CXCursor_ConversionFunction) {
3852 return clang_getNullRange();
3853 if (const FunctionDecl *FD =
3854 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
3855 DeclarationNameInfo FunctionName = FD->getNameInfo();
3856 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
3858 return clang_getNullRange();
3861 // FIXME: A CXCursor_InclusionDirective should give the location of the
3862 // filename, but we don't keep track of this.
3864 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3865 // but we don't keep track of this.
3867 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3868 // but we don't keep track of this.
3870 // Default handling, give the location of the cursor.
3873 return clang_getNullRange();
3875 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3876 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3877 return cxloc::translateSourceRange(Ctx, Loc);
3880 CXString clang_Cursor_getMangling(CXCursor C) {
3881 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
3882 return cxstring::createEmpty();
3884 // Mangling only works for functions and variables.
3885 const Decl *D = getCursorDecl(C);
3886 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
3887 return cxstring::createEmpty();
3889 // First apply frontend mangling.
3890 const NamedDecl *ND = cast<NamedDecl>(D);
3891 ASTContext &Ctx = ND->getASTContext();
3892 std::unique_ptr<MangleContext> MC(Ctx.createMangleContext());
3894 std::string FrontendBuf;
3895 llvm::raw_string_ostream FrontendBufOS(FrontendBuf);
3896 if (MC->shouldMangleDeclName(ND)) {
3897 MC->mangleName(ND, FrontendBufOS);
3899 ND->printName(FrontendBufOS);
3902 // Now apply backend mangling.
3903 std::unique_ptr<llvm::DataLayout> DL(
3904 new llvm::DataLayout(Ctx.getTargetInfo().getDataLayoutString()));
3906 std::string FinalBuf;
3907 llvm::raw_string_ostream FinalBufOS(FinalBuf);
3908 llvm::Mangler::getNameWithPrefix(FinalBufOS, llvm::Twine(FrontendBufOS.str()),
3911 return cxstring::createDup(FinalBufOS.str());
3914 CXString clang_getCursorDisplayName(CXCursor C) {
3915 if (!clang_isDeclaration(C.kind))
3916 return clang_getCursorSpelling(C);
3918 const Decl *D = getCursorDecl(C);
3920 return cxstring::createEmpty();
3922 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3923 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3924 D = FunTmpl->getTemplatedDecl();
3926 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3927 SmallString<64> Str;
3928 llvm::raw_svector_ostream OS(Str);
3930 if (Function->getPrimaryTemplate())
3933 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3936 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3939 if (Function->isVariadic()) {
3940 if (Function->getNumParams())
3945 return cxstring::createDup(OS.str());
3948 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3949 SmallString<64> Str;
3950 llvm::raw_svector_ostream OS(Str);
3951 OS << *ClassTemplate;
3953 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3954 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3958 NamedDecl *Param = Params->getParam(I);
3959 if (Param->getIdentifier()) {
3960 OS << Param->getIdentifier()->getName();
3964 // There is no parameter name, which makes this tricky. Try to come up
3965 // with something useful that isn't too long.
3966 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3967 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3968 else if (NonTypeTemplateParmDecl *NTTP
3969 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3970 OS << NTTP->getType().getAsString(Policy);
3972 OS << "template<...> class";
3976 return cxstring::createDup(OS.str());
3979 if (const ClassTemplateSpecializationDecl *ClassSpec
3980 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3981 // If the type was explicitly written, use that.
3982 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3983 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
3985 SmallString<128> Str;
3986 llvm::raw_svector_ostream OS(Str);
3988 TemplateSpecializationType::PrintTemplateArgumentList(OS,
3989 ClassSpec->getTemplateArgs().data(),
3990 ClassSpec->getTemplateArgs().size(),
3992 return cxstring::createDup(OS.str());
3995 return clang_getCursorSpelling(C);
3998 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4000 case CXCursor_FunctionDecl:
4001 return cxstring::createRef("FunctionDecl");
4002 case CXCursor_TypedefDecl:
4003 return cxstring::createRef("TypedefDecl");
4004 case CXCursor_EnumDecl:
4005 return cxstring::createRef("EnumDecl");
4006 case CXCursor_EnumConstantDecl:
4007 return cxstring::createRef("EnumConstantDecl");
4008 case CXCursor_StructDecl:
4009 return cxstring::createRef("StructDecl");
4010 case CXCursor_UnionDecl:
4011 return cxstring::createRef("UnionDecl");
4012 case CXCursor_ClassDecl:
4013 return cxstring::createRef("ClassDecl");
4014 case CXCursor_FieldDecl:
4015 return cxstring::createRef("FieldDecl");
4016 case CXCursor_VarDecl:
4017 return cxstring::createRef("VarDecl");
4018 case CXCursor_ParmDecl:
4019 return cxstring::createRef("ParmDecl");
4020 case CXCursor_ObjCInterfaceDecl:
4021 return cxstring::createRef("ObjCInterfaceDecl");
4022 case CXCursor_ObjCCategoryDecl:
4023 return cxstring::createRef("ObjCCategoryDecl");
4024 case CXCursor_ObjCProtocolDecl:
4025 return cxstring::createRef("ObjCProtocolDecl");
4026 case CXCursor_ObjCPropertyDecl:
4027 return cxstring::createRef("ObjCPropertyDecl");
4028 case CXCursor_ObjCIvarDecl:
4029 return cxstring::createRef("ObjCIvarDecl");
4030 case CXCursor_ObjCInstanceMethodDecl:
4031 return cxstring::createRef("ObjCInstanceMethodDecl");
4032 case CXCursor_ObjCClassMethodDecl:
4033 return cxstring::createRef("ObjCClassMethodDecl");
4034 case CXCursor_ObjCImplementationDecl:
4035 return cxstring::createRef("ObjCImplementationDecl");
4036 case CXCursor_ObjCCategoryImplDecl:
4037 return cxstring::createRef("ObjCCategoryImplDecl");
4038 case CXCursor_CXXMethod:
4039 return cxstring::createRef("CXXMethod");
4040 case CXCursor_UnexposedDecl:
4041 return cxstring::createRef("UnexposedDecl");
4042 case CXCursor_ObjCSuperClassRef:
4043 return cxstring::createRef("ObjCSuperClassRef");
4044 case CXCursor_ObjCProtocolRef:
4045 return cxstring::createRef("ObjCProtocolRef");
4046 case CXCursor_ObjCClassRef:
4047 return cxstring::createRef("ObjCClassRef");
4048 case CXCursor_TypeRef:
4049 return cxstring::createRef("TypeRef");
4050 case CXCursor_TemplateRef:
4051 return cxstring::createRef("TemplateRef");
4052 case CXCursor_NamespaceRef:
4053 return cxstring::createRef("NamespaceRef");
4054 case CXCursor_MemberRef:
4055 return cxstring::createRef("MemberRef");
4056 case CXCursor_LabelRef:
4057 return cxstring::createRef("LabelRef");
4058 case CXCursor_OverloadedDeclRef:
4059 return cxstring::createRef("OverloadedDeclRef");
4060 case CXCursor_VariableRef:
4061 return cxstring::createRef("VariableRef");
4062 case CXCursor_IntegerLiteral:
4063 return cxstring::createRef("IntegerLiteral");
4064 case CXCursor_FloatingLiteral:
4065 return cxstring::createRef("FloatingLiteral");
4066 case CXCursor_ImaginaryLiteral:
4067 return cxstring::createRef("ImaginaryLiteral");
4068 case CXCursor_StringLiteral:
4069 return cxstring::createRef("StringLiteral");
4070 case CXCursor_CharacterLiteral:
4071 return cxstring::createRef("CharacterLiteral");
4072 case CXCursor_ParenExpr:
4073 return cxstring::createRef("ParenExpr");
4074 case CXCursor_UnaryOperator:
4075 return cxstring::createRef("UnaryOperator");
4076 case CXCursor_ArraySubscriptExpr:
4077 return cxstring::createRef("ArraySubscriptExpr");
4078 case CXCursor_OMPArraySectionExpr:
4079 return cxstring::createRef("OMPArraySectionExpr");
4080 case CXCursor_BinaryOperator:
4081 return cxstring::createRef("BinaryOperator");
4082 case CXCursor_CompoundAssignOperator:
4083 return cxstring::createRef("CompoundAssignOperator");
4084 case CXCursor_ConditionalOperator:
4085 return cxstring::createRef("ConditionalOperator");
4086 case CXCursor_CStyleCastExpr:
4087 return cxstring::createRef("CStyleCastExpr");
4088 case CXCursor_CompoundLiteralExpr:
4089 return cxstring::createRef("CompoundLiteralExpr");
4090 case CXCursor_InitListExpr:
4091 return cxstring::createRef("InitListExpr");
4092 case CXCursor_AddrLabelExpr:
4093 return cxstring::createRef("AddrLabelExpr");
4094 case CXCursor_StmtExpr:
4095 return cxstring::createRef("StmtExpr");
4096 case CXCursor_GenericSelectionExpr:
4097 return cxstring::createRef("GenericSelectionExpr");
4098 case CXCursor_GNUNullExpr:
4099 return cxstring::createRef("GNUNullExpr");
4100 case CXCursor_CXXStaticCastExpr:
4101 return cxstring::createRef("CXXStaticCastExpr");
4102 case CXCursor_CXXDynamicCastExpr:
4103 return cxstring::createRef("CXXDynamicCastExpr");
4104 case CXCursor_CXXReinterpretCastExpr:
4105 return cxstring::createRef("CXXReinterpretCastExpr");
4106 case CXCursor_CXXConstCastExpr:
4107 return cxstring::createRef("CXXConstCastExpr");
4108 case CXCursor_CXXFunctionalCastExpr:
4109 return cxstring::createRef("CXXFunctionalCastExpr");
4110 case CXCursor_CXXTypeidExpr:
4111 return cxstring::createRef("CXXTypeidExpr");
4112 case CXCursor_CXXBoolLiteralExpr:
4113 return cxstring::createRef("CXXBoolLiteralExpr");
4114 case CXCursor_CXXNullPtrLiteralExpr:
4115 return cxstring::createRef("CXXNullPtrLiteralExpr");
4116 case CXCursor_CXXThisExpr:
4117 return cxstring::createRef("CXXThisExpr");
4118 case CXCursor_CXXThrowExpr:
4119 return cxstring::createRef("CXXThrowExpr");
4120 case CXCursor_CXXNewExpr:
4121 return cxstring::createRef("CXXNewExpr");
4122 case CXCursor_CXXDeleteExpr:
4123 return cxstring::createRef("CXXDeleteExpr");
4124 case CXCursor_UnaryExpr:
4125 return cxstring::createRef("UnaryExpr");
4126 case CXCursor_ObjCStringLiteral:
4127 return cxstring::createRef("ObjCStringLiteral");
4128 case CXCursor_ObjCBoolLiteralExpr:
4129 return cxstring::createRef("ObjCBoolLiteralExpr");
4130 case CXCursor_ObjCSelfExpr:
4131 return cxstring::createRef("ObjCSelfExpr");
4132 case CXCursor_ObjCEncodeExpr:
4133 return cxstring::createRef("ObjCEncodeExpr");
4134 case CXCursor_ObjCSelectorExpr:
4135 return cxstring::createRef("ObjCSelectorExpr");
4136 case CXCursor_ObjCProtocolExpr:
4137 return cxstring::createRef("ObjCProtocolExpr");
4138 case CXCursor_ObjCBridgedCastExpr:
4139 return cxstring::createRef("ObjCBridgedCastExpr");
4140 case CXCursor_BlockExpr:
4141 return cxstring::createRef("BlockExpr");
4142 case CXCursor_PackExpansionExpr:
4143 return cxstring::createRef("PackExpansionExpr");
4144 case CXCursor_SizeOfPackExpr:
4145 return cxstring::createRef("SizeOfPackExpr");
4146 case CXCursor_LambdaExpr:
4147 return cxstring::createRef("LambdaExpr");
4148 case CXCursor_UnexposedExpr:
4149 return cxstring::createRef("UnexposedExpr");
4150 case CXCursor_DeclRefExpr:
4151 return cxstring::createRef("DeclRefExpr");
4152 case CXCursor_MemberRefExpr:
4153 return cxstring::createRef("MemberRefExpr");
4154 case CXCursor_CallExpr:
4155 return cxstring::createRef("CallExpr");
4156 case CXCursor_ObjCMessageExpr:
4157 return cxstring::createRef("ObjCMessageExpr");
4158 case CXCursor_UnexposedStmt:
4159 return cxstring::createRef("UnexposedStmt");
4160 case CXCursor_DeclStmt:
4161 return cxstring::createRef("DeclStmt");
4162 case CXCursor_LabelStmt:
4163 return cxstring::createRef("LabelStmt");
4164 case CXCursor_CompoundStmt:
4165 return cxstring::createRef("CompoundStmt");
4166 case CXCursor_CaseStmt:
4167 return cxstring::createRef("CaseStmt");
4168 case CXCursor_DefaultStmt:
4169 return cxstring::createRef("DefaultStmt");
4170 case CXCursor_IfStmt:
4171 return cxstring::createRef("IfStmt");
4172 case CXCursor_SwitchStmt:
4173 return cxstring::createRef("SwitchStmt");
4174 case CXCursor_WhileStmt:
4175 return cxstring::createRef("WhileStmt");
4176 case CXCursor_DoStmt:
4177 return cxstring::createRef("DoStmt");
4178 case CXCursor_ForStmt:
4179 return cxstring::createRef("ForStmt");
4180 case CXCursor_GotoStmt:
4181 return cxstring::createRef("GotoStmt");
4182 case CXCursor_IndirectGotoStmt:
4183 return cxstring::createRef("IndirectGotoStmt");
4184 case CXCursor_ContinueStmt:
4185 return cxstring::createRef("ContinueStmt");
4186 case CXCursor_BreakStmt:
4187 return cxstring::createRef("BreakStmt");
4188 case CXCursor_ReturnStmt:
4189 return cxstring::createRef("ReturnStmt");
4190 case CXCursor_GCCAsmStmt:
4191 return cxstring::createRef("GCCAsmStmt");
4192 case CXCursor_MSAsmStmt:
4193 return cxstring::createRef("MSAsmStmt");
4194 case CXCursor_ObjCAtTryStmt:
4195 return cxstring::createRef("ObjCAtTryStmt");
4196 case CXCursor_ObjCAtCatchStmt:
4197 return cxstring::createRef("ObjCAtCatchStmt");
4198 case CXCursor_ObjCAtFinallyStmt:
4199 return cxstring::createRef("ObjCAtFinallyStmt");
4200 case CXCursor_ObjCAtThrowStmt:
4201 return cxstring::createRef("ObjCAtThrowStmt");
4202 case CXCursor_ObjCAtSynchronizedStmt:
4203 return cxstring::createRef("ObjCAtSynchronizedStmt");
4204 case CXCursor_ObjCAutoreleasePoolStmt:
4205 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4206 case CXCursor_ObjCForCollectionStmt:
4207 return cxstring::createRef("ObjCForCollectionStmt");
4208 case CXCursor_CXXCatchStmt:
4209 return cxstring::createRef("CXXCatchStmt");
4210 case CXCursor_CXXTryStmt:
4211 return cxstring::createRef("CXXTryStmt");
4212 case CXCursor_CXXForRangeStmt:
4213 return cxstring::createRef("CXXForRangeStmt");
4214 case CXCursor_SEHTryStmt:
4215 return cxstring::createRef("SEHTryStmt");
4216 case CXCursor_SEHExceptStmt:
4217 return cxstring::createRef("SEHExceptStmt");
4218 case CXCursor_SEHFinallyStmt:
4219 return cxstring::createRef("SEHFinallyStmt");
4220 case CXCursor_SEHLeaveStmt:
4221 return cxstring::createRef("SEHLeaveStmt");
4222 case CXCursor_NullStmt:
4223 return cxstring::createRef("NullStmt");
4224 case CXCursor_InvalidFile:
4225 return cxstring::createRef("InvalidFile");
4226 case CXCursor_InvalidCode:
4227 return cxstring::createRef("InvalidCode");
4228 case CXCursor_NoDeclFound:
4229 return cxstring::createRef("NoDeclFound");
4230 case CXCursor_NotImplemented:
4231 return cxstring::createRef("NotImplemented");
4232 case CXCursor_TranslationUnit:
4233 return cxstring::createRef("TranslationUnit");
4234 case CXCursor_UnexposedAttr:
4235 return cxstring::createRef("UnexposedAttr");
4236 case CXCursor_IBActionAttr:
4237 return cxstring::createRef("attribute(ibaction)");
4238 case CXCursor_IBOutletAttr:
4239 return cxstring::createRef("attribute(iboutlet)");
4240 case CXCursor_IBOutletCollectionAttr:
4241 return cxstring::createRef("attribute(iboutletcollection)");
4242 case CXCursor_CXXFinalAttr:
4243 return cxstring::createRef("attribute(final)");
4244 case CXCursor_CXXOverrideAttr:
4245 return cxstring::createRef("attribute(override)");
4246 case CXCursor_AnnotateAttr:
4247 return cxstring::createRef("attribute(annotate)");
4248 case CXCursor_AsmLabelAttr:
4249 return cxstring::createRef("asm label");
4250 case CXCursor_PackedAttr:
4251 return cxstring::createRef("attribute(packed)");
4252 case CXCursor_PureAttr:
4253 return cxstring::createRef("attribute(pure)");
4254 case CXCursor_ConstAttr:
4255 return cxstring::createRef("attribute(const)");
4256 case CXCursor_NoDuplicateAttr:
4257 return cxstring::createRef("attribute(noduplicate)");
4258 case CXCursor_CUDAConstantAttr:
4259 return cxstring::createRef("attribute(constant)");
4260 case CXCursor_CUDADeviceAttr:
4261 return cxstring::createRef("attribute(device)");
4262 case CXCursor_CUDAGlobalAttr:
4263 return cxstring::createRef("attribute(global)");
4264 case CXCursor_CUDAHostAttr:
4265 return cxstring::createRef("attribute(host)");
4266 case CXCursor_CUDASharedAttr:
4267 return cxstring::createRef("attribute(shared)");
4268 case CXCursor_VisibilityAttr:
4269 return cxstring::createRef("attribute(visibility)");
4270 case CXCursor_PreprocessingDirective:
4271 return cxstring::createRef("preprocessing directive");
4272 case CXCursor_MacroDefinition:
4273 return cxstring::createRef("macro definition");
4274 case CXCursor_MacroExpansion:
4275 return cxstring::createRef("macro expansion");
4276 case CXCursor_InclusionDirective:
4277 return cxstring::createRef("inclusion directive");
4278 case CXCursor_Namespace:
4279 return cxstring::createRef("Namespace");
4280 case CXCursor_LinkageSpec:
4281 return cxstring::createRef("LinkageSpec");
4282 case CXCursor_CXXBaseSpecifier:
4283 return cxstring::createRef("C++ base class specifier");
4284 case CXCursor_Constructor:
4285 return cxstring::createRef("CXXConstructor");
4286 case CXCursor_Destructor:
4287 return cxstring::createRef("CXXDestructor");
4288 case CXCursor_ConversionFunction:
4289 return cxstring::createRef("CXXConversion");
4290 case CXCursor_TemplateTypeParameter:
4291 return cxstring::createRef("TemplateTypeParameter");
4292 case CXCursor_NonTypeTemplateParameter:
4293 return cxstring::createRef("NonTypeTemplateParameter");
4294 case CXCursor_TemplateTemplateParameter:
4295 return cxstring::createRef("TemplateTemplateParameter");
4296 case CXCursor_FunctionTemplate:
4297 return cxstring::createRef("FunctionTemplate");
4298 case CXCursor_ClassTemplate:
4299 return cxstring::createRef("ClassTemplate");
4300 case CXCursor_ClassTemplatePartialSpecialization:
4301 return cxstring::createRef("ClassTemplatePartialSpecialization");
4302 case CXCursor_NamespaceAlias:
4303 return cxstring::createRef("NamespaceAlias");
4304 case CXCursor_UsingDirective:
4305 return cxstring::createRef("UsingDirective");
4306 case CXCursor_UsingDeclaration:
4307 return cxstring::createRef("UsingDeclaration");
4308 case CXCursor_TypeAliasDecl:
4309 return cxstring::createRef("TypeAliasDecl");
4310 case CXCursor_ObjCSynthesizeDecl:
4311 return cxstring::createRef("ObjCSynthesizeDecl");
4312 case CXCursor_ObjCDynamicDecl:
4313 return cxstring::createRef("ObjCDynamicDecl");
4314 case CXCursor_CXXAccessSpecifier:
4315 return cxstring::createRef("CXXAccessSpecifier");
4316 case CXCursor_ModuleImportDecl:
4317 return cxstring::createRef("ModuleImport");
4318 case CXCursor_OMPParallelDirective:
4319 return cxstring::createRef("OMPParallelDirective");
4320 case CXCursor_OMPSimdDirective:
4321 return cxstring::createRef("OMPSimdDirective");
4322 case CXCursor_OMPForDirective:
4323 return cxstring::createRef("OMPForDirective");
4324 case CXCursor_OMPForSimdDirective:
4325 return cxstring::createRef("OMPForSimdDirective");
4326 case CXCursor_OMPSectionsDirective:
4327 return cxstring::createRef("OMPSectionsDirective");
4328 case CXCursor_OMPSectionDirective:
4329 return cxstring::createRef("OMPSectionDirective");
4330 case CXCursor_OMPSingleDirective:
4331 return cxstring::createRef("OMPSingleDirective");
4332 case CXCursor_OMPMasterDirective:
4333 return cxstring::createRef("OMPMasterDirective");
4334 case CXCursor_OMPCriticalDirective:
4335 return cxstring::createRef("OMPCriticalDirective");
4336 case CXCursor_OMPParallelForDirective:
4337 return cxstring::createRef("OMPParallelForDirective");
4338 case CXCursor_OMPParallelForSimdDirective:
4339 return cxstring::createRef("OMPParallelForSimdDirective");
4340 case CXCursor_OMPParallelSectionsDirective:
4341 return cxstring::createRef("OMPParallelSectionsDirective");
4342 case CXCursor_OMPTaskDirective:
4343 return cxstring::createRef("OMPTaskDirective");
4344 case CXCursor_OMPTaskyieldDirective:
4345 return cxstring::createRef("OMPTaskyieldDirective");
4346 case CXCursor_OMPBarrierDirective:
4347 return cxstring::createRef("OMPBarrierDirective");
4348 case CXCursor_OMPTaskwaitDirective:
4349 return cxstring::createRef("OMPTaskwaitDirective");
4350 case CXCursor_OMPTaskgroupDirective:
4351 return cxstring::createRef("OMPTaskgroupDirective");
4352 case CXCursor_OMPFlushDirective:
4353 return cxstring::createRef("OMPFlushDirective");
4354 case CXCursor_OMPOrderedDirective:
4355 return cxstring::createRef("OMPOrderedDirective");
4356 case CXCursor_OMPAtomicDirective:
4357 return cxstring::createRef("OMPAtomicDirective");
4358 case CXCursor_OMPTargetDirective:
4359 return cxstring::createRef("OMPTargetDirective");
4360 case CXCursor_OMPTargetDataDirective:
4361 return cxstring::createRef("OMPTargetDataDirective");
4362 case CXCursor_OMPTeamsDirective:
4363 return cxstring::createRef("OMPTeamsDirective");
4364 case CXCursor_OMPCancellationPointDirective:
4365 return cxstring::createRef("OMPCancellationPointDirective");
4366 case CXCursor_OMPCancelDirective:
4367 return cxstring::createRef("OMPCancelDirective");
4368 case CXCursor_OverloadCandidate:
4369 return cxstring::createRef("OverloadCandidate");
4372 llvm_unreachable("Unhandled CXCursorKind");
4375 struct GetCursorData {
4376 SourceLocation TokenBeginLoc;
4377 bool PointsAtMacroArgExpansion;
4378 bool VisitedObjCPropertyImplDecl;
4379 SourceLocation VisitedDeclaratorDeclStartLoc;
4380 CXCursor &BestCursor;
4382 GetCursorData(SourceManager &SM,
4383 SourceLocation tokenBegin, CXCursor &outputCursor)
4384 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4385 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4386 VisitedObjCPropertyImplDecl = false;
4390 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4392 CXClientData client_data) {
4393 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4394 CXCursor *BestCursor = &Data->BestCursor;
4396 // If we point inside a macro argument we should provide info of what the
4397 // token is so use the actual cursor, don't replace it with a macro expansion
4399 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4400 return CXChildVisit_Recurse;
4402 if (clang_isDeclaration(cursor.kind)) {
4403 // Avoid having the implicit methods override the property decls.
4404 if (const ObjCMethodDecl *MD
4405 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4406 if (MD->isImplicit())
4407 return CXChildVisit_Break;
4409 } else if (const ObjCInterfaceDecl *ID
4410 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4411 // Check that when we have multiple @class references in the same line,
4412 // that later ones do not override the previous ones.
4415 // source ranges for both start at '@', so 'Bar' will end up overriding
4416 // 'Foo' even though the cursor location was at 'Foo'.
4417 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4418 BestCursor->kind == CXCursor_ObjCClassRef)
4419 if (const ObjCInterfaceDecl *PrevID
4420 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4422 !PrevID->isThisDeclarationADefinition() &&
4423 !ID->isThisDeclarationADefinition())
4424 return CXChildVisit_Break;
4427 } else if (const DeclaratorDecl *DD
4428 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4429 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4430 // Check that when we have multiple declarators in the same line,
4431 // that later ones do not override the previous ones.
4434 // source ranges for both start at 'int', so 'Bar' will end up overriding
4435 // 'Foo' even though the cursor location was at 'Foo'.
4436 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4437 return CXChildVisit_Break;
4438 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4440 } else if (const ObjCPropertyImplDecl *PropImp
4441 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4443 // Check that when we have multiple @synthesize in the same line,
4444 // that later ones do not override the previous ones.
4446 // @synthesize Foo, Bar;
4447 // source ranges for both start at '@', so 'Bar' will end up overriding
4448 // 'Foo' even though the cursor location was at 'Foo'.
4449 if (Data->VisitedObjCPropertyImplDecl)
4450 return CXChildVisit_Break;
4451 Data->VisitedObjCPropertyImplDecl = true;
4455 if (clang_isExpression(cursor.kind) &&
4456 clang_isDeclaration(BestCursor->kind)) {
4457 if (const Decl *D = getCursorDecl(*BestCursor)) {
4458 // Avoid having the cursor of an expression replace the declaration cursor
4459 // when the expression source range overlaps the declaration range.
4460 // This can happen for C++ constructor expressions whose range generally
4461 // include the variable declaration, e.g.:
4462 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4463 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4464 D->getLocation() == Data->TokenBeginLoc)
4465 return CXChildVisit_Break;
4469 // If our current best cursor is the construction of a temporary object,
4470 // don't replace that cursor with a type reference, because we want
4471 // clang_getCursor() to point at the constructor.
4472 if (clang_isExpression(BestCursor->kind) &&
4473 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4474 cursor.kind == CXCursor_TypeRef) {
4475 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4476 // as having the actual point on the type reference.
4477 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4478 return CXChildVisit_Recurse;
4481 // If we already have an Objective-C superclass reference, don't
4482 // update it further.
4483 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4484 return CXChildVisit_Break;
4486 *BestCursor = cursor;
4487 return CXChildVisit_Recurse;
4490 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4491 if (isNotUsableTU(TU)) {
4493 return clang_getNullCursor();
4496 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4497 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4499 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4500 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4504 unsigned SearchLine, SearchColumn;
4506 unsigned ResultLine, ResultColumn;
4507 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4508 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4509 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4511 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4513 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4514 &ResultColumn, nullptr);
4515 SearchFileName = clang_getFileName(SearchFile);
4516 ResultFileName = clang_getFileName(ResultFile);
4517 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4518 USR = clang_getCursorUSR(Result);
4519 *Log << llvm::format("(%s:%d:%d) = %s",
4520 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4521 clang_getCString(KindSpelling))
4522 << llvm::format("(%s:%d:%d):%s%s",
4523 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4524 clang_getCString(USR), IsDef);
4525 clang_disposeString(SearchFileName);
4526 clang_disposeString(ResultFileName);
4527 clang_disposeString(KindSpelling);
4528 clang_disposeString(USR);
4530 CXCursor Definition = clang_getCursorDefinition(Result);
4531 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4532 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4533 CXString DefinitionKindSpelling
4534 = clang_getCursorKindSpelling(Definition.kind);
4535 CXFile DefinitionFile;
4536 unsigned DefinitionLine, DefinitionColumn;
4537 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
4538 &DefinitionLine, &DefinitionColumn, nullptr);
4539 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
4540 *Log << llvm::format(" -> %s(%s:%d:%d)",
4541 clang_getCString(DefinitionKindSpelling),
4542 clang_getCString(DefinitionFileName),
4543 DefinitionLine, DefinitionColumn);
4544 clang_disposeString(DefinitionFileName);
4545 clang_disposeString(DefinitionKindSpelling);
4552 CXCursor clang_getNullCursor(void) {
4553 return MakeCXCursorInvalid(CXCursor_InvalidFile);
4556 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
4557 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
4558 // can't set consistently. For example, when visiting a DeclStmt we will set
4559 // it but we don't set it on the result of clang_getCursorDefinition for
4560 // a reference of the same declaration.
4561 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
4562 // when visiting a DeclStmt currently, the AST should be enhanced to be able
4563 // to provide that kind of info.
4564 if (clang_isDeclaration(X.kind))
4565 X.data[1] = nullptr;
4566 if (clang_isDeclaration(Y.kind))
4567 Y.data[1] = nullptr;
4572 unsigned clang_hashCursor(CXCursor C) {
4574 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
4577 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
4578 std::make_pair(C.kind, C.data[Index]));
4581 unsigned clang_isInvalid(enum CXCursorKind K) {
4582 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
4585 unsigned clang_isDeclaration(enum CXCursorKind K) {
4586 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
4587 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
4590 unsigned clang_isReference(enum CXCursorKind K) {
4591 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
4594 unsigned clang_isExpression(enum CXCursorKind K) {
4595 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
4598 unsigned clang_isStatement(enum CXCursorKind K) {
4599 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
4602 unsigned clang_isAttribute(enum CXCursorKind K) {
4603 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
4606 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
4607 return K == CXCursor_TranslationUnit;
4610 unsigned clang_isPreprocessing(enum CXCursorKind K) {
4611 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
4614 unsigned clang_isUnexposed(enum CXCursorKind K) {
4616 case CXCursor_UnexposedDecl:
4617 case CXCursor_UnexposedExpr:
4618 case CXCursor_UnexposedStmt:
4619 case CXCursor_UnexposedAttr:
4626 CXCursorKind clang_getCursorKind(CXCursor C) {
4630 CXSourceLocation clang_getCursorLocation(CXCursor C) {
4631 if (clang_isReference(C.kind)) {
4633 case CXCursor_ObjCSuperClassRef: {
4634 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4635 = getCursorObjCSuperClassRef(C);
4636 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4639 case CXCursor_ObjCProtocolRef: {
4640 std::pair<const ObjCProtocolDecl *, SourceLocation> P
4641 = getCursorObjCProtocolRef(C);
4642 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4645 case CXCursor_ObjCClassRef: {
4646 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4647 = getCursorObjCClassRef(C);
4648 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4651 case CXCursor_TypeRef: {
4652 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
4653 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4656 case CXCursor_TemplateRef: {
4657 std::pair<const TemplateDecl *, SourceLocation> P =
4658 getCursorTemplateRef(C);
4659 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4662 case CXCursor_NamespaceRef: {
4663 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
4664 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4667 case CXCursor_MemberRef: {
4668 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4669 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4672 case CXCursor_VariableRef: {
4673 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4674 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4677 case CXCursor_CXXBaseSpecifier: {
4678 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4680 return clang_getNullLocation();
4682 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4683 return cxloc::translateSourceLocation(getCursorContext(C),
4684 TSInfo->getTypeLoc().getBeginLoc());
4686 return cxloc::translateSourceLocation(getCursorContext(C),
4687 BaseSpec->getLocStart());
4690 case CXCursor_LabelRef: {
4691 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4692 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4695 case CXCursor_OverloadedDeclRef:
4696 return cxloc::translateSourceLocation(getCursorContext(C),
4697 getCursorOverloadedDeclRef(C).second);
4700 // FIXME: Need a way to enumerate all non-reference cases.
4701 llvm_unreachable("Missed a reference kind");
4705 if (clang_isExpression(C.kind))
4706 return cxloc::translateSourceLocation(getCursorContext(C),
4707 getLocationFromExpr(getCursorExpr(C)));
4709 if (clang_isStatement(C.kind))
4710 return cxloc::translateSourceLocation(getCursorContext(C),
4711 getCursorStmt(C)->getLocStart());
4713 if (C.kind == CXCursor_PreprocessingDirective) {
4714 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4715 return cxloc::translateSourceLocation(getCursorContext(C), L);
4718 if (C.kind == CXCursor_MacroExpansion) {
4720 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4721 return cxloc::translateSourceLocation(getCursorContext(C), L);
4724 if (C.kind == CXCursor_MacroDefinition) {
4725 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4726 return cxloc::translateSourceLocation(getCursorContext(C), L);
4729 if (C.kind == CXCursor_InclusionDirective) {
4731 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4732 return cxloc::translateSourceLocation(getCursorContext(C), L);
4735 if (clang_isAttribute(C.kind)) {
4737 = cxcursor::getCursorAttr(C)->getLocation();
4738 return cxloc::translateSourceLocation(getCursorContext(C), L);
4741 if (!clang_isDeclaration(C.kind))
4742 return clang_getNullLocation();
4744 const Decl *D = getCursorDecl(C);
4746 return clang_getNullLocation();
4748 SourceLocation Loc = D->getLocation();
4749 // FIXME: Multiple variables declared in a single declaration
4750 // currently lack the information needed to correctly determine their
4751 // ranges when accounting for the type-specifier. We use context
4752 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4753 // and if so, whether it is the first decl.
4754 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4755 if (!cxcursor::isFirstInDeclGroup(C))
4756 Loc = VD->getLocation();
4759 // For ObjC methods, give the start location of the method name.
4760 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4761 Loc = MD->getSelectorStartLoc();
4763 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4768 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4771 // Guard against an invalid SourceLocation, or we may assert in one
4772 // of the following calls.
4773 if (SLoc.isInvalid())
4774 return clang_getNullCursor();
4776 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4778 // Translate the given source location to make it point at the beginning of
4779 // the token under the cursor.
4780 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4781 CXXUnit->getASTContext().getLangOpts());
4783 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4784 if (SLoc.isValid()) {
4785 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4786 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4787 /*VisitPreprocessorLast=*/true,
4788 /*VisitIncludedEntities=*/false,
4789 SourceLocation(SLoc));
4790 CursorVis.visitFileRegion();
4796 static SourceRange getRawCursorExtent(CXCursor C) {
4797 if (clang_isReference(C.kind)) {
4799 case CXCursor_ObjCSuperClassRef:
4800 return getCursorObjCSuperClassRef(C).second;
4802 case CXCursor_ObjCProtocolRef:
4803 return getCursorObjCProtocolRef(C).second;
4805 case CXCursor_ObjCClassRef:
4806 return getCursorObjCClassRef(C).second;
4808 case CXCursor_TypeRef:
4809 return getCursorTypeRef(C).second;
4811 case CXCursor_TemplateRef:
4812 return getCursorTemplateRef(C).second;
4814 case CXCursor_NamespaceRef:
4815 return getCursorNamespaceRef(C).second;
4817 case CXCursor_MemberRef:
4818 return getCursorMemberRef(C).second;
4820 case CXCursor_CXXBaseSpecifier:
4821 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4823 case CXCursor_LabelRef:
4824 return getCursorLabelRef(C).second;
4826 case CXCursor_OverloadedDeclRef:
4827 return getCursorOverloadedDeclRef(C).second;
4829 case CXCursor_VariableRef:
4830 return getCursorVariableRef(C).second;
4833 // FIXME: Need a way to enumerate all non-reference cases.
4834 llvm_unreachable("Missed a reference kind");
4838 if (clang_isExpression(C.kind))
4839 return getCursorExpr(C)->getSourceRange();
4841 if (clang_isStatement(C.kind))
4842 return getCursorStmt(C)->getSourceRange();
4844 if (clang_isAttribute(C.kind))
4845 return getCursorAttr(C)->getRange();
4847 if (C.kind == CXCursor_PreprocessingDirective)
4848 return cxcursor::getCursorPreprocessingDirective(C);
4850 if (C.kind == CXCursor_MacroExpansion) {
4851 ASTUnit *TU = getCursorASTUnit(C);
4852 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4853 return TU->mapRangeFromPreamble(Range);
4856 if (C.kind == CXCursor_MacroDefinition) {
4857 ASTUnit *TU = getCursorASTUnit(C);
4858 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4859 return TU->mapRangeFromPreamble(Range);
4862 if (C.kind == CXCursor_InclusionDirective) {
4863 ASTUnit *TU = getCursorASTUnit(C);
4864 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4865 return TU->mapRangeFromPreamble(Range);
4868 if (C.kind == CXCursor_TranslationUnit) {
4869 ASTUnit *TU = getCursorASTUnit(C);
4870 FileID MainID = TU->getSourceManager().getMainFileID();
4871 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4872 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4873 return SourceRange(Start, End);
4876 if (clang_isDeclaration(C.kind)) {
4877 const Decl *D = cxcursor::getCursorDecl(C);
4879 return SourceRange();
4881 SourceRange R = D->getSourceRange();
4882 // FIXME: Multiple variables declared in a single declaration
4883 // currently lack the information needed to correctly determine their
4884 // ranges when accounting for the type-specifier. We use context
4885 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4886 // and if so, whether it is the first decl.
4887 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4888 if (!cxcursor::isFirstInDeclGroup(C))
4889 R.setBegin(VD->getLocation());
4893 return SourceRange();
4896 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
4897 /// the decl-specifier-seq for declarations.
4898 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4899 if (clang_isDeclaration(C.kind)) {
4900 const Decl *D = cxcursor::getCursorDecl(C);
4902 return SourceRange();
4904 SourceRange R = D->getSourceRange();
4906 // Adjust the start of the location for declarations preceded by
4907 // declaration specifiers.
4908 SourceLocation StartLoc;
4909 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4910 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4911 StartLoc = TI->getTypeLoc().getLocStart();
4912 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4913 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4914 StartLoc = TI->getTypeLoc().getLocStart();
4917 if (StartLoc.isValid() && R.getBegin().isValid() &&
4918 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4919 R.setBegin(StartLoc);
4921 // FIXME: Multiple variables declared in a single declaration
4922 // currently lack the information needed to correctly determine their
4923 // ranges when accounting for the type-specifier. We use context
4924 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4925 // and if so, whether it is the first decl.
4926 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4927 if (!cxcursor::isFirstInDeclGroup(C))
4928 R.setBegin(VD->getLocation());
4934 return getRawCursorExtent(C);
4939 CXSourceRange clang_getCursorExtent(CXCursor C) {
4940 SourceRange R = getRawCursorExtent(C);
4942 return clang_getNullRange();
4944 return cxloc::translateSourceRange(getCursorContext(C), R);
4947 CXCursor clang_getCursorReferenced(CXCursor C) {
4948 if (clang_isInvalid(C.kind))
4949 return clang_getNullCursor();
4951 CXTranslationUnit tu = getCursorTU(C);
4952 if (clang_isDeclaration(C.kind)) {
4953 const Decl *D = getCursorDecl(C);
4955 return clang_getNullCursor();
4956 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4957 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4958 if (const ObjCPropertyImplDecl *PropImpl =
4959 dyn_cast<ObjCPropertyImplDecl>(D))
4960 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4961 return MakeCXCursor(Property, tu);
4966 if (clang_isExpression(C.kind)) {
4967 const Expr *E = getCursorExpr(C);
4968 const Decl *D = getDeclFromExpr(E);
4970 CXCursor declCursor = MakeCXCursor(D, tu);
4971 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4976 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4977 return MakeCursorOverloadedDeclRef(Ovl, tu);
4979 return clang_getNullCursor();
4982 if (clang_isStatement(C.kind)) {
4983 const Stmt *S = getCursorStmt(C);
4984 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4985 if (LabelDecl *label = Goto->getLabel())
4986 if (LabelStmt *labelS = label->getStmt())
4987 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4989 return clang_getNullCursor();
4992 if (C.kind == CXCursor_MacroExpansion) {
4993 if (const MacroDefinitionRecord *Def =
4994 getCursorMacroExpansion(C).getDefinition())
4995 return MakeMacroDefinitionCursor(Def, tu);
4998 if (!clang_isReference(C.kind))
4999 return clang_getNullCursor();
5002 case CXCursor_ObjCSuperClassRef:
5003 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5005 case CXCursor_ObjCProtocolRef: {
5006 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5007 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5008 return MakeCXCursor(Def, tu);
5010 return MakeCXCursor(Prot, tu);
5013 case CXCursor_ObjCClassRef: {
5014 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5015 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5016 return MakeCXCursor(Def, tu);
5018 return MakeCXCursor(Class, tu);
5021 case CXCursor_TypeRef:
5022 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5024 case CXCursor_TemplateRef:
5025 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5027 case CXCursor_NamespaceRef:
5028 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5030 case CXCursor_MemberRef:
5031 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5033 case CXCursor_CXXBaseSpecifier: {
5034 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5035 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5039 case CXCursor_LabelRef:
5040 // FIXME: We end up faking the "parent" declaration here because we
5041 // don't want to make CXCursor larger.
5042 return MakeCXCursor(getCursorLabelRef(C).first,
5043 cxtu::getASTUnit(tu)->getASTContext()
5044 .getTranslationUnitDecl(),
5047 case CXCursor_OverloadedDeclRef:
5050 case CXCursor_VariableRef:
5051 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5054 // We would prefer to enumerate all non-reference cursor kinds here.
5055 llvm_unreachable("Unhandled reference cursor kind");
5059 CXCursor clang_getCursorDefinition(CXCursor C) {
5060 if (clang_isInvalid(C.kind))
5061 return clang_getNullCursor();
5063 CXTranslationUnit TU = getCursorTU(C);
5065 bool WasReference = false;
5066 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5067 C = clang_getCursorReferenced(C);
5068 WasReference = true;
5071 if (C.kind == CXCursor_MacroExpansion)
5072 return clang_getCursorReferenced(C);
5074 if (!clang_isDeclaration(C.kind))
5075 return clang_getNullCursor();
5077 const Decl *D = getCursorDecl(C);
5079 return clang_getNullCursor();
5081 switch (D->getKind()) {
5082 // Declaration kinds that don't really separate the notions of
5083 // declaration and definition.
5084 case Decl::Namespace:
5086 case Decl::TypeAlias:
5087 case Decl::TypeAliasTemplate:
5088 case Decl::TemplateTypeParm:
5089 case Decl::EnumConstant:
5091 case Decl::MSProperty:
5092 case Decl::IndirectField:
5093 case Decl::ObjCIvar:
5094 case Decl::ObjCAtDefsField:
5095 case Decl::ImplicitParam:
5097 case Decl::NonTypeTemplateParm:
5098 case Decl::TemplateTemplateParm:
5099 case Decl::ObjCCategoryImpl:
5100 case Decl::ObjCImplementation:
5101 case Decl::AccessSpec:
5102 case Decl::LinkageSpec:
5103 case Decl::ObjCPropertyImpl:
5104 case Decl::FileScopeAsm:
5105 case Decl::StaticAssert:
5107 case Decl::Captured:
5108 case Decl::Label: // FIXME: Is this right??
5109 case Decl::ClassScopeFunctionSpecialization:
5111 case Decl::OMPThreadPrivate:
5112 case Decl::ObjCTypeParam:
5115 // Declaration kinds that don't make any sense here, but are
5116 // nonetheless harmless.
5118 case Decl::TranslationUnit:
5119 case Decl::ExternCContext:
5122 // Declaration kinds for which the definition is not resolvable.
5123 case Decl::UnresolvedUsingTypename:
5124 case Decl::UnresolvedUsingValue:
5127 case Decl::UsingDirective:
5128 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5131 case Decl::NamespaceAlias:
5132 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5136 case Decl::CXXRecord:
5137 case Decl::ClassTemplateSpecialization:
5138 case Decl::ClassTemplatePartialSpecialization:
5139 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5140 return MakeCXCursor(Def, TU);
5141 return clang_getNullCursor();
5143 case Decl::Function:
5144 case Decl::CXXMethod:
5145 case Decl::CXXConstructor:
5146 case Decl::CXXDestructor:
5147 case Decl::CXXConversion: {
5148 const FunctionDecl *Def = nullptr;
5149 if (cast<FunctionDecl>(D)->getBody(Def))
5150 return MakeCXCursor(Def, TU);
5151 return clang_getNullCursor();
5155 case Decl::VarTemplateSpecialization:
5156 case Decl::VarTemplatePartialSpecialization: {
5157 // Ask the variable if it has a definition.
5158 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5159 return MakeCXCursor(Def, TU);
5160 return clang_getNullCursor();
5163 case Decl::FunctionTemplate: {
5164 const FunctionDecl *Def = nullptr;
5165 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5166 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5167 return clang_getNullCursor();
5170 case Decl::ClassTemplate: {
5171 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5173 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5175 return clang_getNullCursor();
5178 case Decl::VarTemplate: {
5180 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5181 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5182 return clang_getNullCursor();
5186 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5187 D->getLocation(), TU);
5189 case Decl::UsingShadow:
5190 return clang_getCursorDefinition(
5191 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5194 case Decl::ObjCMethod: {
5195 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5196 if (Method->isThisDeclarationADefinition())
5199 // Dig out the method definition in the associated
5200 // @implementation, if we have it.
5201 // FIXME: The ASTs should make finding the definition easier.
5202 if (const ObjCInterfaceDecl *Class
5203 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5204 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5205 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5206 Method->isInstanceMethod()))
5207 if (Def->isThisDeclarationADefinition())
5208 return MakeCXCursor(Def, TU);
5210 return clang_getNullCursor();
5213 case Decl::ObjCCategory:
5214 if (ObjCCategoryImplDecl *Impl
5215 = cast<ObjCCategoryDecl>(D)->getImplementation())
5216 return MakeCXCursor(Impl, TU);
5217 return clang_getNullCursor();
5219 case Decl::ObjCProtocol:
5220 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5221 return MakeCXCursor(Def, TU);
5222 return clang_getNullCursor();
5224 case Decl::ObjCInterface: {
5225 // There are two notions of a "definition" for an Objective-C
5226 // class: the interface and its implementation. When we resolved a
5227 // reference to an Objective-C class, produce the @interface as
5228 // the definition; when we were provided with the interface,
5229 // produce the @implementation as the definition.
5230 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5232 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5233 return MakeCXCursor(Def, TU);
5234 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5235 return MakeCXCursor(Impl, TU);
5236 return clang_getNullCursor();
5239 case Decl::ObjCProperty:
5240 // FIXME: We don't really know where to find the
5241 // ObjCPropertyImplDecls that implement this property.
5242 return clang_getNullCursor();
5244 case Decl::ObjCCompatibleAlias:
5245 if (const ObjCInterfaceDecl *Class
5246 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5247 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5248 return MakeCXCursor(Def, TU);
5250 return clang_getNullCursor();
5253 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5254 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5255 return clang_getNullCursor();
5257 case Decl::FriendTemplate:
5258 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5259 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5260 return clang_getNullCursor();
5263 return clang_getNullCursor();
5266 unsigned clang_isCursorDefinition(CXCursor C) {
5267 if (!clang_isDeclaration(C.kind))
5270 return clang_getCursorDefinition(C) == C;
5273 CXCursor clang_getCanonicalCursor(CXCursor C) {
5274 if (!clang_isDeclaration(C.kind))
5277 if (const Decl *D = getCursorDecl(C)) {
5278 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5279 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5280 return MakeCXCursor(CatD, getCursorTU(C));
5282 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5283 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5284 return MakeCXCursor(IFD, getCursorTU(C));
5286 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5292 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5293 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5296 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5297 if (C.kind != CXCursor_OverloadedDeclRef)
5300 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5301 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5302 return E->getNumDecls();
5304 if (OverloadedTemplateStorage *S
5305 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5308 const Decl *D = Storage.get<const Decl *>();
5309 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5310 return Using->shadow_size();
5315 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5316 if (cursor.kind != CXCursor_OverloadedDeclRef)
5317 return clang_getNullCursor();
5319 if (index >= clang_getNumOverloadedDecls(cursor))
5320 return clang_getNullCursor();
5322 CXTranslationUnit TU = getCursorTU(cursor);
5323 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5324 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5325 return MakeCXCursor(E->decls_begin()[index], TU);
5327 if (OverloadedTemplateStorage *S
5328 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5329 return MakeCXCursor(S->begin()[index], TU);
5331 const Decl *D = Storage.get<const Decl *>();
5332 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5333 // FIXME: This is, unfortunately, linear time.
5334 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5335 std::advance(Pos, index);
5336 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5339 return clang_getNullCursor();
5342 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5343 const char **startBuf,
5344 const char **endBuf,
5345 unsigned *startLine,
5346 unsigned *startColumn,
5348 unsigned *endColumn) {
5349 assert(getCursorDecl(C) && "CXCursor has null decl");
5350 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5351 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5353 SourceManager &SM = FD->getASTContext().getSourceManager();
5354 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5355 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5356 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5357 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5358 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5359 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5363 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5364 unsigned PieceIndex) {
5365 RefNamePieces Pieces;
5368 case CXCursor_MemberRefExpr:
5369 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5370 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5371 E->getQualifierLoc().getSourceRange());
5374 case CXCursor_DeclRefExpr:
5375 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
5376 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
5377 E->getQualifierLoc().getSourceRange(),
5378 E->getOptionalExplicitTemplateArgs());
5381 case CXCursor_CallExpr:
5382 if (const CXXOperatorCallExpr *OCE =
5383 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5384 const Expr *Callee = OCE->getCallee();
5385 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5386 Callee = ICE->getSubExpr();
5388 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5389 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5390 DRE->getQualifierLoc().getSourceRange());
5398 if (Pieces.empty()) {
5399 if (PieceIndex == 0)
5400 return clang_getCursorExtent(C);
5401 } else if (PieceIndex < Pieces.size()) {
5402 SourceRange R = Pieces[PieceIndex];
5404 return cxloc::translateSourceRange(getCursorContext(C), R);
5407 return clang_getNullRange();
5410 void clang_enableStackTraces(void) {
5411 llvm::sys::PrintStackTraceOnErrorSignal();
5414 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5415 unsigned stack_size) {
5416 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5419 } // end: extern "C"
5421 //===----------------------------------------------------------------------===//
5422 // Token-based Operations.
5423 //===----------------------------------------------------------------------===//
5426 * int_data[0]: a CXTokenKind
5427 * int_data[1]: starting token location
5428 * int_data[2]: token length
5429 * int_data[3]: reserved
5430 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5435 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5436 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5439 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5440 switch (clang_getTokenKind(CXTok)) {
5441 case CXToken_Identifier:
5442 case CXToken_Keyword:
5443 // We know we have an IdentifierInfo*, so use that.
5444 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5447 case CXToken_Literal: {
5448 // We have stashed the starting pointer in the ptr_data field. Use it.
5449 const char *Text = static_cast<const char *>(CXTok.ptr_data);
5450 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5453 case CXToken_Punctuation:
5454 case CXToken_Comment:
5458 if (isNotUsableTU(TU)) {
5460 return cxstring::createEmpty();
5463 // We have to find the starting buffer pointer the hard way, by
5464 // deconstructing the source location.
5465 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5467 return cxstring::createEmpty();
5469 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5470 std::pair<FileID, unsigned> LocInfo
5471 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5472 bool Invalid = false;
5474 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5476 return cxstring::createEmpty();
5478 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5481 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5482 if (isNotUsableTU(TU)) {
5484 return clang_getNullLocation();
5487 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5489 return clang_getNullLocation();
5491 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5492 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5495 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5496 if (isNotUsableTU(TU)) {
5498 return clang_getNullRange();
5501 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5503 return clang_getNullRange();
5505 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5506 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5509 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5510 SmallVectorImpl<CXToken> &CXTokens) {
5511 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5512 std::pair<FileID, unsigned> BeginLocInfo
5513 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5514 std::pair<FileID, unsigned> EndLocInfo
5515 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5517 // Cannot tokenize across files.
5518 if (BeginLocInfo.first != EndLocInfo.first)
5522 bool Invalid = false;
5524 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5528 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5529 CXXUnit->getASTContext().getLangOpts(),
5530 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
5531 Lex.SetCommentRetentionState(true);
5533 // Lex tokens until we hit the end of the range.
5534 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
5536 bool previousWasAt = false;
5538 // Lex the next token
5539 Lex.LexFromRawLexer(Tok);
5540 if (Tok.is(tok::eof))
5543 // Initialize the CXToken.
5547 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
5548 CXTok.int_data[2] = Tok.getLength();
5549 CXTok.int_data[3] = 0;
5551 // - Kind-specific fields
5552 if (Tok.isLiteral()) {
5553 CXTok.int_data[0] = CXToken_Literal;
5554 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
5555 } else if (Tok.is(tok::raw_identifier)) {
5556 // Lookup the identifier to determine whether we have a keyword.
5558 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
5560 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
5561 CXTok.int_data[0] = CXToken_Keyword;
5564 CXTok.int_data[0] = Tok.is(tok::identifier)
5565 ? CXToken_Identifier
5568 CXTok.ptr_data = II;
5569 } else if (Tok.is(tok::comment)) {
5570 CXTok.int_data[0] = CXToken_Comment;
5571 CXTok.ptr_data = nullptr;
5573 CXTok.int_data[0] = CXToken_Punctuation;
5574 CXTok.ptr_data = nullptr;
5576 CXTokens.push_back(CXTok);
5577 previousWasAt = Tok.is(tok::at);
5578 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
5581 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
5582 CXToken **Tokens, unsigned *NumTokens) {
5584 *Log << TU << ' ' << Range;
5592 if (isNotUsableTU(TU)) {
5597 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5598 if (!CXXUnit || !Tokens || !NumTokens)
5601 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5603 SourceRange R = cxloc::translateCXSourceRange(Range);
5607 SmallVector<CXToken, 32> CXTokens;
5608 getTokens(CXXUnit, R, CXTokens);
5610 if (CXTokens.empty())
5613 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
5614 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
5615 *NumTokens = CXTokens.size();
5618 void clang_disposeTokens(CXTranslationUnit TU,
5619 CXToken *Tokens, unsigned NumTokens) {
5623 } // end: extern "C"
5625 //===----------------------------------------------------------------------===//
5626 // Token annotation APIs.
5627 //===----------------------------------------------------------------------===//
5629 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5631 CXClientData client_data);
5632 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5633 CXClientData client_data);
5636 class AnnotateTokensWorker {
5641 unsigned PreprocessingTokIdx;
5642 CursorVisitor AnnotateVis;
5643 SourceManager &SrcMgr;
5644 bool HasContextSensitiveKeywords;
5646 struct PostChildrenInfo {
5648 SourceRange CursorRange;
5649 unsigned BeforeReachingCursorIdx;
5650 unsigned BeforeChildrenTokenIdx;
5652 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
5654 CXToken &getTok(unsigned Idx) {
5655 assert(Idx < NumTokens);
5658 const CXToken &getTok(unsigned Idx) const {
5659 assert(Idx < NumTokens);
5662 bool MoreTokens() const { return TokIdx < NumTokens; }
5663 unsigned NextToken() const { return TokIdx; }
5664 void AdvanceToken() { ++TokIdx; }
5665 SourceLocation GetTokenLoc(unsigned tokI) {
5666 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
5668 bool isFunctionMacroToken(unsigned tokI) const {
5669 return getTok(tokI).int_data[3] != 0;
5671 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
5672 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
5675 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
5676 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
5680 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
5681 CXTranslationUnit TU, SourceRange RegionOfInterest)
5682 : Tokens(tokens), Cursors(cursors),
5683 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
5685 AnnotateTokensVisitor, this,
5686 /*VisitPreprocessorLast=*/true,
5687 /*VisitIncludedEntities=*/false,
5689 /*VisitDeclsOnly=*/false,
5690 AnnotateTokensPostChildrenVisitor),
5691 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
5692 HasContextSensitiveKeywords(false) { }
5694 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
5695 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
5696 bool postVisitChildren(CXCursor cursor);
5697 void AnnotateTokens();
5699 /// \brief Determine whether the annotator saw any cursors that have
5700 /// context-sensitive keywords.
5701 bool hasContextSensitiveKeywords() const {
5702 return HasContextSensitiveKeywords;
5705 ~AnnotateTokensWorker() {
5706 assert(PostChildrenInfos.empty());
5711 void AnnotateTokensWorker::AnnotateTokens() {
5712 // Walk the AST within the region of interest, annotating tokens
5714 AnnotateVis.visitFileRegion();
5717 static inline void updateCursorAnnotation(CXCursor &Cursor,
5718 const CXCursor &updateC) {
5719 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
5724 /// \brief It annotates and advances tokens with a cursor until the comparison
5725 //// between the cursor location and the source range is the same as
5726 /// \arg compResult.
5728 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5729 /// Pass RangeOverlap to annotate tokens inside a range.
5730 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5731 RangeComparisonResult compResult,
5732 SourceRange range) {
5733 while (MoreTokens()) {
5734 const unsigned I = NextToken();
5735 if (isFunctionMacroToken(I))
5736 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
5739 SourceLocation TokLoc = GetTokenLoc(I);
5740 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5741 updateCursorAnnotation(Cursors[I], updateC);
5749 /// \brief Special annotation handling for macro argument tokens.
5750 /// \returns true if it advanced beyond all macro tokens, false otherwise.
5751 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5753 RangeComparisonResult compResult,
5754 SourceRange range) {
5755 assert(MoreTokens());
5756 assert(isFunctionMacroToken(NextToken()) &&
5757 "Should be called only for macro arg tokens");
5759 // This works differently than annotateAndAdvanceTokens; because expanded
5760 // macro arguments can have arbitrary translation-unit source order, we do not
5761 // advance the token index one by one until a token fails the range test.
5762 // We only advance once past all of the macro arg tokens if all of them
5763 // pass the range test. If one of them fails we keep the token index pointing
5764 // at the start of the macro arg tokens so that the failing token will be
5765 // annotated by a subsequent annotation try.
5767 bool atLeastOneCompFail = false;
5769 unsigned I = NextToken();
5770 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5771 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5772 if (TokLoc.isFileID())
5773 continue; // not macro arg token, it's parens or comma.
5774 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5775 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5776 Cursors[I] = updateC;
5778 atLeastOneCompFail = true;
5781 if (atLeastOneCompFail)
5784 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5788 enum CXChildVisitResult
5789 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5790 SourceRange cursorRange = getRawCursorExtent(cursor);
5791 if (cursorRange.isInvalid())
5792 return CXChildVisit_Recurse;
5794 if (!HasContextSensitiveKeywords) {
5795 // Objective-C properties can have context-sensitive keywords.
5796 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5797 if (const ObjCPropertyDecl *Property
5798 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5799 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5801 // Objective-C methods can have context-sensitive keywords.
5802 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5803 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5804 if (const ObjCMethodDecl *Method
5805 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5806 if (Method->getObjCDeclQualifier())
5807 HasContextSensitiveKeywords = true;
5809 for (const auto *P : Method->params()) {
5810 if (P->getObjCDeclQualifier()) {
5811 HasContextSensitiveKeywords = true;
5818 // C++ methods can have context-sensitive keywords.
5819 else if (cursor.kind == CXCursor_CXXMethod) {
5820 if (const CXXMethodDecl *Method
5821 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5822 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5823 HasContextSensitiveKeywords = true;
5826 // C++ classes can have context-sensitive keywords.
5827 else if (cursor.kind == CXCursor_StructDecl ||
5828 cursor.kind == CXCursor_ClassDecl ||
5829 cursor.kind == CXCursor_ClassTemplate ||
5830 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5831 if (const Decl *D = getCursorDecl(cursor))
5832 if (D->hasAttr<FinalAttr>())
5833 HasContextSensitiveKeywords = true;
5837 // Don't override a property annotation with its getter/setter method.
5838 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
5839 parent.kind == CXCursor_ObjCPropertyDecl)
5840 return CXChildVisit_Continue;
5842 if (clang_isPreprocessing(cursor.kind)) {
5843 // Items in the preprocessing record are kept separate from items in
5844 // declarations, so we keep a separate token index.
5845 unsigned SavedTokIdx = TokIdx;
5846 TokIdx = PreprocessingTokIdx;
5848 // Skip tokens up until we catch up to the beginning of the preprocessing
5850 while (MoreTokens()) {
5851 const unsigned I = NextToken();
5852 SourceLocation TokLoc = GetTokenLoc(I);
5853 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5864 // Look at all of the tokens within this range.
5865 while (MoreTokens()) {
5866 const unsigned I = NextToken();
5867 SourceLocation TokLoc = GetTokenLoc(I);
5868 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5870 llvm_unreachable("Infeasible");
5874 // For macro expansions, just note where the beginning of the macro
5875 // expansion occurs.
5876 if (cursor.kind == CXCursor_MacroExpansion) {
5877 if (TokLoc == cursorRange.getBegin())
5878 Cursors[I] = cursor;
5882 // We may have already annotated macro names inside macro definitions.
5883 if (Cursors[I].kind != CXCursor_MacroExpansion)
5884 Cursors[I] = cursor;
5891 // Save the preprocessing token index; restore the non-preprocessing
5893 PreprocessingTokIdx = TokIdx;
5894 TokIdx = SavedTokIdx;
5895 return CXChildVisit_Recurse;
5898 if (cursorRange.isInvalid())
5899 return CXChildVisit_Continue;
5901 unsigned BeforeReachingCursorIdx = NextToken();
5902 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5903 const enum CXCursorKind K = clang_getCursorKind(parent);
5904 const CXCursor updateC =
5905 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
5906 // Attributes are annotated out-of-order, skip tokens until we reach it.
5907 clang_isAttribute(cursor.kind))
5908 ? clang_getNullCursor() : parent;
5910 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5912 // Avoid having the cursor of an expression "overwrite" the annotation of the
5913 // variable declaration that it belongs to.
5914 // This can happen for C++ constructor expressions whose range generally
5915 // include the variable declaration, e.g.:
5916 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5917 if (clang_isExpression(cursorK) && MoreTokens()) {
5918 const Expr *E = getCursorExpr(cursor);
5919 if (const Decl *D = getCursorParentDecl(cursor)) {
5920 const unsigned I = NextToken();
5921 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5922 E->getLocStart() == D->getLocation() &&
5923 E->getLocStart() == GetTokenLoc(I)) {
5924 updateCursorAnnotation(Cursors[I], updateC);
5930 // Before recursing into the children keep some state that we are going
5931 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5932 // extra work after the child nodes are visited.
5933 // Note that we don't call VisitChildren here to avoid traversing statements
5934 // code-recursively which can blow the stack.
5936 PostChildrenInfo Info;
5937 Info.Cursor = cursor;
5938 Info.CursorRange = cursorRange;
5939 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
5940 Info.BeforeChildrenTokenIdx = NextToken();
5941 PostChildrenInfos.push_back(Info);
5943 return CXChildVisit_Recurse;
5946 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5947 if (PostChildrenInfos.empty())
5949 const PostChildrenInfo &Info = PostChildrenInfos.back();
5950 if (!clang_equalCursors(Info.Cursor, cursor))
5953 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5954 const unsigned AfterChildren = NextToken();
5955 SourceRange cursorRange = Info.CursorRange;
5957 // Scan the tokens that are at the end of the cursor, but are not captured
5958 // but the child cursors.
5959 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5961 // Scan the tokens that are at the beginning of the cursor, but are not
5962 // capture by the child cursors.
5963 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5964 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5967 Cursors[I] = cursor;
5970 // Attributes are annotated out-of-order, rewind TokIdx to when we first
5971 // encountered the attribute cursor.
5972 if (clang_isAttribute(cursor.kind))
5973 TokIdx = Info.BeforeReachingCursorIdx;
5975 PostChildrenInfos.pop_back();
5979 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5981 CXClientData client_data) {
5982 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5985 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5986 CXClientData client_data) {
5987 return static_cast<AnnotateTokensWorker*>(client_data)->
5988 postVisitChildren(cursor);
5993 /// \brief Uses the macro expansions in the preprocessing record to find
5994 /// and mark tokens that are macro arguments. This info is used by the
5995 /// AnnotateTokensWorker.
5996 class MarkMacroArgTokensVisitor {
6003 MarkMacroArgTokensVisitor(SourceManager &SM,
6004 CXToken *tokens, unsigned numTokens)
6005 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6007 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6008 if (cursor.kind != CXCursor_MacroExpansion)
6009 return CXChildVisit_Continue;
6011 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6012 if (macroRange.getBegin() == macroRange.getEnd())
6013 return CXChildVisit_Continue; // it's not a function macro.
6015 for (; CurIdx < NumTokens; ++CurIdx) {
6016 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6017 macroRange.getBegin()))
6021 if (CurIdx == NumTokens)
6022 return CXChildVisit_Break;
6024 for (; CurIdx < NumTokens; ++CurIdx) {
6025 SourceLocation tokLoc = getTokenLoc(CurIdx);
6026 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6029 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6032 if (CurIdx == NumTokens)
6033 return CXChildVisit_Break;
6035 return CXChildVisit_Continue;
6039 CXToken &getTok(unsigned Idx) {
6040 assert(Idx < NumTokens);
6043 const CXToken &getTok(unsigned Idx) const {
6044 assert(Idx < NumTokens);
6048 SourceLocation getTokenLoc(unsigned tokI) {
6049 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6052 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6053 // The third field is reserved and currently not used. Use it here
6054 // to mark macro arg expanded tokens with their expanded locations.
6055 getTok(tokI).int_data[3] = loc.getRawEncoding();
6059 } // end anonymous namespace
6061 static CXChildVisitResult
6062 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6063 CXClientData client_data) {
6064 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6068 /// \brief Used by \c annotatePreprocessorTokens.
6069 /// \returns true if lexing was finished, false otherwise.
6070 static bool lexNext(Lexer &Lex, Token &Tok,
6071 unsigned &NextIdx, unsigned NumTokens) {
6072 if (NextIdx >= NumTokens)
6076 Lex.LexFromRawLexer(Tok);
6077 if (Tok.is(tok::eof))
6083 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6084 SourceRange RegionOfInterest,
6087 unsigned NumTokens) {
6088 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6090 Preprocessor &PP = CXXUnit->getPreprocessor();
6091 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6092 std::pair<FileID, unsigned> BeginLocInfo
6093 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6094 std::pair<FileID, unsigned> EndLocInfo
6095 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6097 if (BeginLocInfo.first != EndLocInfo.first)
6101 bool Invalid = false;
6102 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6103 if (Buffer.empty() || Invalid)
6106 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6107 CXXUnit->getASTContext().getLangOpts(),
6108 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6110 Lex.SetCommentRetentionState(true);
6112 unsigned NextIdx = 0;
6113 // Lex tokens in raw mode until we hit the end of the range, to avoid
6114 // entering #includes or expanding macros.
6117 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6119 unsigned TokIdx = NextIdx-1;
6120 assert(Tok.getLocation() ==
6121 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6124 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6125 // We have found a preprocessing directive. Annotate the tokens
6128 // FIXME: Some simple tests here could identify macro definitions and
6129 // #undefs, to provide specific cursor kinds for those.
6131 SourceLocation BeginLoc = Tok.getLocation();
6132 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6135 MacroInfo *MI = nullptr;
6136 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6137 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6140 if (Tok.is(tok::raw_identifier)) {
6141 IdentifierInfo &II =
6142 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6143 SourceLocation MappedTokLoc =
6144 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6145 MI = getMacroInfo(II, MappedTokLoc, TU);
6149 bool finished = false;
6151 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6155 // If we are in a macro definition, check if the token was ever a
6156 // macro name and annotate it if that's the case.
6158 SourceLocation SaveLoc = Tok.getLocation();
6159 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6160 MacroDefinitionRecord *MacroDef =
6161 checkForMacroInMacroDefinition(MI, Tok, TU);
6162 Tok.setLocation(SaveLoc);
6164 Cursors[NextIdx - 1] =
6165 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6167 } while (!Tok.isAtStartOfLine());
6169 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6170 assert(TokIdx <= LastIdx);
6171 SourceLocation EndLoc =
6172 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6174 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6176 for (; TokIdx <= LastIdx; ++TokIdx)
6177 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6186 // This gets run a separate thread to avoid stack blowout.
6187 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6188 CXToken *Tokens, unsigned NumTokens,
6189 CXCursor *Cursors) {
6190 CIndexer *CXXIdx = TU->CIdx;
6191 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6192 setThreadBackgroundPriority();
6194 // Determine the region of interest, which contains all of the tokens.
6195 SourceRange RegionOfInterest;
6196 RegionOfInterest.setBegin(
6197 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6198 RegionOfInterest.setEnd(
6199 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6200 Tokens[NumTokens-1])));
6202 // Relex the tokens within the source range to look for preprocessing
6204 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6206 // If begin location points inside a macro argument, set it to the expansion
6207 // location so we can have the full context when annotating semantically.
6209 SourceManager &SM = CXXUnit->getSourceManager();
6210 SourceLocation Loc =
6211 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6212 if (Loc.isMacroID())
6213 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6216 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6217 // Search and mark tokens that are macro argument expansions.
6218 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6220 CursorVisitor MacroArgMarker(TU,
6221 MarkMacroArgTokensVisitorDelegate, &Visitor,
6222 /*VisitPreprocessorLast=*/true,
6223 /*VisitIncludedEntities=*/false,
6225 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6228 // Annotate all of the source locations in the region of interest that map to
6229 // a specific cursor.
6230 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6232 // FIXME: We use a ridiculous stack size here because the data-recursion
6233 // algorithm uses a large stack frame than the non-data recursive version,
6234 // and AnnotationTokensWorker currently transforms the data-recursion
6235 // algorithm back into a traditional recursion by explicitly calling
6236 // VisitChildren(). We will need to remove this explicit recursive call.
6239 // If we ran into any entities that involve context-sensitive keywords,
6240 // take another pass through the tokens to mark them as such.
6241 if (W.hasContextSensitiveKeywords()) {
6242 for (unsigned I = 0; I != NumTokens; ++I) {
6243 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6246 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6247 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6248 if (const ObjCPropertyDecl *Property
6249 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6250 if (Property->getPropertyAttributesAsWritten() != 0 &&
6251 llvm::StringSwitch<bool>(II->getName())
6252 .Case("readonly", true)
6253 .Case("assign", true)
6254 .Case("unsafe_unretained", true)
6255 .Case("readwrite", true)
6256 .Case("retain", true)
6258 .Case("nonatomic", true)
6259 .Case("atomic", true)
6260 .Case("getter", true)
6261 .Case("setter", true)
6262 .Case("strong", true)
6265 Tokens[I].int_data[0] = CXToken_Keyword;
6270 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6271 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6272 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6273 if (llvm::StringSwitch<bool>(II->getName())
6276 .Case("inout", true)
6277 .Case("oneway", true)
6278 .Case("bycopy", true)
6279 .Case("byref", true)
6281 Tokens[I].int_data[0] = CXToken_Keyword;
6285 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6286 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6287 Tokens[I].int_data[0] = CXToken_Keyword;
6296 void clang_annotateTokens(CXTranslationUnit TU,
6297 CXToken *Tokens, unsigned NumTokens,
6298 CXCursor *Cursors) {
6299 if (isNotUsableTU(TU)) {
6303 if (NumTokens == 0 || !Tokens || !Cursors) {
6304 LOG_FUNC_SECTION { *Log << "<null input>"; }
6310 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6311 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6312 *Log << clang_getRange(bloc, eloc);
6315 // Any token we don't specifically annotate will have a NULL cursor.
6316 CXCursor C = clang_getNullCursor();
6317 for (unsigned I = 0; I != NumTokens; ++I)
6320 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6324 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6326 auto AnnotateTokensImpl = [=]() {
6327 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6329 llvm::CrashRecoveryContext CRC;
6330 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6331 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6335 } // end: extern "C"
6337 //===----------------------------------------------------------------------===//
6338 // Operations for querying linkage of a cursor.
6339 //===----------------------------------------------------------------------===//
6342 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6343 if (!clang_isDeclaration(cursor.kind))
6344 return CXLinkage_Invalid;
6346 const Decl *D = cxcursor::getCursorDecl(cursor);
6347 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6348 switch (ND->getLinkageInternal()) {
6350 case VisibleNoLinkage: return CXLinkage_NoLinkage;
6351 case InternalLinkage: return CXLinkage_Internal;
6352 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6353 case ExternalLinkage: return CXLinkage_External;
6356 return CXLinkage_Invalid;
6358 } // end: extern "C"
6360 //===----------------------------------------------------------------------===//
6361 // Operations for querying language of a cursor.
6362 //===----------------------------------------------------------------------===//
6364 static CXLanguageKind getDeclLanguage(const Decl *D) {
6366 return CXLanguage_C;
6368 switch (D->getKind()) {
6371 case Decl::ImplicitParam:
6372 case Decl::ObjCAtDefsField:
6373 case Decl::ObjCCategory:
6374 case Decl::ObjCCategoryImpl:
6375 case Decl::ObjCCompatibleAlias:
6376 case Decl::ObjCImplementation:
6377 case Decl::ObjCInterface:
6378 case Decl::ObjCIvar:
6379 case Decl::ObjCMethod:
6380 case Decl::ObjCProperty:
6381 case Decl::ObjCPropertyImpl:
6382 case Decl::ObjCProtocol:
6383 case Decl::ObjCTypeParam:
6384 return CXLanguage_ObjC;
6385 case Decl::CXXConstructor:
6386 case Decl::CXXConversion:
6387 case Decl::CXXDestructor:
6388 case Decl::CXXMethod:
6389 case Decl::CXXRecord:
6390 case Decl::ClassTemplate:
6391 case Decl::ClassTemplatePartialSpecialization:
6392 case Decl::ClassTemplateSpecialization:
6394 case Decl::FriendTemplate:
6395 case Decl::FunctionTemplate:
6396 case Decl::LinkageSpec:
6397 case Decl::Namespace:
6398 case Decl::NamespaceAlias:
6399 case Decl::NonTypeTemplateParm:
6400 case Decl::StaticAssert:
6401 case Decl::TemplateTemplateParm:
6402 case Decl::TemplateTypeParm:
6403 case Decl::UnresolvedUsingTypename:
6404 case Decl::UnresolvedUsingValue:
6406 case Decl::UsingDirective:
6407 case Decl::UsingShadow:
6408 return CXLanguage_CPlusPlus;
6411 return CXLanguage_C;
6416 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6417 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6418 return CXAvailability_NotAvailable;
6420 switch (D->getAvailability()) {
6422 case AR_NotYetIntroduced:
6423 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6424 return getCursorAvailabilityForDecl(
6425 cast<Decl>(EnumConst->getDeclContext()));
6426 return CXAvailability_Available;
6429 return CXAvailability_Deprecated;
6431 case AR_Unavailable:
6432 return CXAvailability_NotAvailable;
6435 llvm_unreachable("Unknown availability kind!");
6438 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6439 if (clang_isDeclaration(cursor.kind))
6440 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6441 return getCursorAvailabilityForDecl(D);
6443 return CXAvailability_Available;
6446 static CXVersion convertVersion(VersionTuple In) {
6447 CXVersion Out = { -1, -1, -1 };
6451 Out.Major = In.getMajor();
6453 Optional<unsigned> Minor = In.getMinor();
6454 if (Minor.hasValue())
6459 Optional<unsigned> Subminor = In.getSubminor();
6460 if (Subminor.hasValue())
6461 Out.Subminor = *Subminor;
6466 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6467 int *always_deprecated,
6468 CXString *deprecated_message,
6469 int *always_unavailable,
6470 CXString *unavailable_message,
6471 CXPlatformAvailability *availability,
6472 int availability_size) {
6473 bool HadAvailAttr = false;
6475 for (auto A : D->attrs()) {
6476 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6477 HadAvailAttr = true;
6478 if (always_deprecated)
6479 *always_deprecated = 1;
6480 if (deprecated_message) {
6481 clang_disposeString(*deprecated_message);
6482 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6487 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6488 HadAvailAttr = true;
6489 if (always_unavailable)
6490 *always_unavailable = 1;
6491 if (unavailable_message) {
6492 clang_disposeString(*unavailable_message);
6493 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6498 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6499 HadAvailAttr = true;
6500 if (N < availability_size) {
6501 availability[N].Platform
6502 = cxstring::createDup(Avail->getPlatform()->getName());
6503 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6504 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6505 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6506 availability[N].Unavailable = Avail->getUnavailable();
6507 availability[N].Message = cxstring::createDup(Avail->getMessage());
6514 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6515 return getCursorPlatformAvailabilityForDecl(
6516 cast<Decl>(EnumConst->getDeclContext()),
6520 unavailable_message,
6527 int clang_getCursorPlatformAvailability(CXCursor cursor,
6528 int *always_deprecated,
6529 CXString *deprecated_message,
6530 int *always_unavailable,
6531 CXString *unavailable_message,
6532 CXPlatformAvailability *availability,
6533 int availability_size) {
6534 if (always_deprecated)
6535 *always_deprecated = 0;
6536 if (deprecated_message)
6537 *deprecated_message = cxstring::createEmpty();
6538 if (always_unavailable)
6539 *always_unavailable = 0;
6540 if (unavailable_message)
6541 *unavailable_message = cxstring::createEmpty();
6543 if (!clang_isDeclaration(cursor.kind))
6546 const Decl *D = cxcursor::getCursorDecl(cursor);
6550 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
6553 unavailable_message,
6558 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
6559 clang_disposeString(availability->Platform);
6560 clang_disposeString(availability->Message);
6563 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
6564 if (clang_isDeclaration(cursor.kind))
6565 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
6567 return CXLanguage_Invalid;
6570 /// \brief If the given cursor is the "templated" declaration
6571 /// descibing a class or function template, return the class or
6572 /// function template.
6573 static const Decl *maybeGetTemplateCursor(const Decl *D) {
6577 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6578 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
6581 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6582 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
6589 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
6590 StorageClass sc = SC_None;
6591 const Decl *D = getCursorDecl(C);
6593 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6594 sc = FD->getStorageClass();
6595 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6596 sc = VD->getStorageClass();
6598 return CX_SC_Invalid;
6601 return CX_SC_Invalid;
6607 return CX_SC_Extern;
6609 return CX_SC_Static;
6610 case SC_PrivateExtern:
6611 return CX_SC_PrivateExtern;
6615 return CX_SC_Register;
6617 llvm_unreachable("Unhandled storage class!");
6620 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
6621 if (clang_isDeclaration(cursor.kind)) {
6622 if (const Decl *D = getCursorDecl(cursor)) {
6623 const DeclContext *DC = D->getDeclContext();
6625 return clang_getNullCursor();
6627 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6628 getCursorTU(cursor));
6632 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
6633 if (const Decl *D = getCursorDecl(cursor))
6634 return MakeCXCursor(D, getCursorTU(cursor));
6637 return clang_getNullCursor();
6640 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
6641 if (clang_isDeclaration(cursor.kind)) {
6642 if (const Decl *D = getCursorDecl(cursor)) {
6643 const DeclContext *DC = D->getLexicalDeclContext();
6645 return clang_getNullCursor();
6647 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
6648 getCursorTU(cursor));
6652 // FIXME: Note that we can't easily compute the lexical context of a
6653 // statement or expression, so we return nothing.
6654 return clang_getNullCursor();
6657 CXFile clang_getIncludedFile(CXCursor cursor) {
6658 if (cursor.kind != CXCursor_InclusionDirective)
6661 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
6662 return const_cast<FileEntry *>(ID->getFile());
6665 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
6666 if (C.kind != CXCursor_ObjCPropertyDecl)
6667 return CXObjCPropertyAttr_noattr;
6669 unsigned Result = CXObjCPropertyAttr_noattr;
6670 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
6671 ObjCPropertyDecl::PropertyAttributeKind Attr =
6672 PD->getPropertyAttributesAsWritten();
6674 #define SET_CXOBJCPROP_ATTR(A) \
6675 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
6676 Result |= CXObjCPropertyAttr_##A
6677 SET_CXOBJCPROP_ATTR(readonly);
6678 SET_CXOBJCPROP_ATTR(getter);
6679 SET_CXOBJCPROP_ATTR(assign);
6680 SET_CXOBJCPROP_ATTR(readwrite);
6681 SET_CXOBJCPROP_ATTR(retain);
6682 SET_CXOBJCPROP_ATTR(copy);
6683 SET_CXOBJCPROP_ATTR(nonatomic);
6684 SET_CXOBJCPROP_ATTR(setter);
6685 SET_CXOBJCPROP_ATTR(atomic);
6686 SET_CXOBJCPROP_ATTR(weak);
6687 SET_CXOBJCPROP_ATTR(strong);
6688 SET_CXOBJCPROP_ATTR(unsafe_unretained);
6689 #undef SET_CXOBJCPROP_ATTR
6694 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
6695 if (!clang_isDeclaration(C.kind))
6696 return CXObjCDeclQualifier_None;
6698 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
6699 const Decl *D = getCursorDecl(C);
6700 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6701 QT = MD->getObjCDeclQualifier();
6702 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
6703 QT = PD->getObjCDeclQualifier();
6704 if (QT == Decl::OBJC_TQ_None)
6705 return CXObjCDeclQualifier_None;
6707 unsigned Result = CXObjCDeclQualifier_None;
6708 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
6709 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
6710 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
6711 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
6712 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
6713 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
6718 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
6719 if (!clang_isDeclaration(C.kind))
6722 const Decl *D = getCursorDecl(C);
6723 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
6724 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
6725 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6726 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
6731 unsigned clang_Cursor_isVariadic(CXCursor C) {
6732 if (!clang_isDeclaration(C.kind))
6735 const Decl *D = getCursorDecl(C);
6736 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6737 return FD->isVariadic();
6738 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6739 return MD->isVariadic();
6744 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
6745 if (!clang_isDeclaration(C.kind))
6746 return clang_getNullRange();
6748 const Decl *D = getCursorDecl(C);
6749 ASTContext &Context = getCursorContext(C);
6750 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6752 return clang_getNullRange();
6754 return cxloc::translateSourceRange(Context, RC->getSourceRange());
6757 CXString clang_Cursor_getRawCommentText(CXCursor C) {
6758 if (!clang_isDeclaration(C.kind))
6759 return cxstring::createNull();
6761 const Decl *D = getCursorDecl(C);
6762 ASTContext &Context = getCursorContext(C);
6763 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6764 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
6767 // Don't duplicate the string because RawText points directly into source
6769 return cxstring::createRef(RawText);
6772 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
6773 if (!clang_isDeclaration(C.kind))
6774 return cxstring::createNull();
6776 const Decl *D = getCursorDecl(C);
6777 const ASTContext &Context = getCursorContext(C);
6778 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6781 StringRef BriefText = RC->getBriefText(Context);
6783 // Don't duplicate the string because RawComment ensures that this memory
6784 // will not go away.
6785 return cxstring::createRef(BriefText);
6788 return cxstring::createNull();
6791 CXModule clang_Cursor_getModule(CXCursor C) {
6792 if (C.kind == CXCursor_ModuleImportDecl) {
6793 if (const ImportDecl *ImportD =
6794 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
6795 return ImportD->getImportedModule();
6801 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
6802 if (isNotUsableTU(TU)) {
6808 FileEntry *FE = static_cast<FileEntry *>(File);
6810 ASTUnit &Unit = *cxtu::getASTUnit(TU);
6811 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
6812 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
6814 return Header.getModule();
6817 CXFile clang_Module_getASTFile(CXModule CXMod) {
6820 Module *Mod = static_cast<Module*>(CXMod);
6821 return const_cast<FileEntry *>(Mod->getASTFile());
6824 CXModule clang_Module_getParent(CXModule CXMod) {
6827 Module *Mod = static_cast<Module*>(CXMod);
6831 CXString clang_Module_getName(CXModule CXMod) {
6833 return cxstring::createEmpty();
6834 Module *Mod = static_cast<Module*>(CXMod);
6835 return cxstring::createDup(Mod->Name);
6838 CXString clang_Module_getFullName(CXModule CXMod) {
6840 return cxstring::createEmpty();
6841 Module *Mod = static_cast<Module*>(CXMod);
6842 return cxstring::createDup(Mod->getFullModuleName());
6845 int clang_Module_isSystem(CXModule CXMod) {
6848 Module *Mod = static_cast<Module*>(CXMod);
6849 return Mod->IsSystem;
6852 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
6854 if (isNotUsableTU(TU)) {
6860 Module *Mod = static_cast<Module*>(CXMod);
6861 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6862 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6863 return TopHeaders.size();
6866 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
6867 CXModule CXMod, unsigned Index) {
6868 if (isNotUsableTU(TU)) {
6874 Module *Mod = static_cast<Module*>(CXMod);
6875 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6877 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6878 if (Index < TopHeaders.size())
6879 return const_cast<FileEntry *>(TopHeaders[Index]);
6884 } // end: extern "C"
6886 //===----------------------------------------------------------------------===//
6887 // C++ AST instrospection.
6888 //===----------------------------------------------------------------------===//
6891 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
6892 if (!clang_isDeclaration(C.kind))
6895 const Decl *D = cxcursor::getCursorDecl(C);
6896 const CXXMethodDecl *Method =
6897 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6898 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
6901 unsigned clang_CXXMethod_isConst(CXCursor C) {
6902 if (!clang_isDeclaration(C.kind))
6905 const Decl *D = cxcursor::getCursorDecl(C);
6906 const CXXMethodDecl *Method =
6907 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6908 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
6911 unsigned clang_CXXMethod_isStatic(CXCursor C) {
6912 if (!clang_isDeclaration(C.kind))
6915 const Decl *D = cxcursor::getCursorDecl(C);
6916 const CXXMethodDecl *Method =
6917 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6918 return (Method && Method->isStatic()) ? 1 : 0;
6921 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
6922 if (!clang_isDeclaration(C.kind))
6925 const Decl *D = cxcursor::getCursorDecl(C);
6926 const CXXMethodDecl *Method =
6927 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6928 return (Method && Method->isVirtual()) ? 1 : 0;
6930 } // end: extern "C"
6932 //===----------------------------------------------------------------------===//
6933 // Attribute introspection.
6934 //===----------------------------------------------------------------------===//
6937 CXType clang_getIBOutletCollectionType(CXCursor C) {
6938 if (C.kind != CXCursor_IBOutletCollectionAttr)
6939 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
6941 const IBOutletCollectionAttr *A =
6942 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
6944 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
6946 } // end: extern "C"
6948 //===----------------------------------------------------------------------===//
6949 // Inspecting memory usage.
6950 //===----------------------------------------------------------------------===//
6952 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
6954 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
6955 enum CXTUResourceUsageKind k,
6956 unsigned long amount) {
6957 CXTUResourceUsageEntry entry = { k, amount };
6958 entries.push_back(entry);
6963 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
6964 const char *str = "";
6966 case CXTUResourceUsage_AST:
6967 str = "ASTContext: expressions, declarations, and types";
6969 case CXTUResourceUsage_Identifiers:
6970 str = "ASTContext: identifiers";
6972 case CXTUResourceUsage_Selectors:
6973 str = "ASTContext: selectors";
6975 case CXTUResourceUsage_GlobalCompletionResults:
6976 str = "Code completion: cached global results";
6978 case CXTUResourceUsage_SourceManagerContentCache:
6979 str = "SourceManager: content cache allocator";
6981 case CXTUResourceUsage_AST_SideTables:
6982 str = "ASTContext: side tables";
6984 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
6985 str = "SourceManager: malloc'ed memory buffers";
6987 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
6988 str = "SourceManager: mmap'ed memory buffers";
6990 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6991 str = "ExternalASTSource: malloc'ed memory buffers";
6993 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6994 str = "ExternalASTSource: mmap'ed memory buffers";
6996 case CXTUResourceUsage_Preprocessor:
6997 str = "Preprocessor: malloc'ed memory";
6999 case CXTUResourceUsage_PreprocessingRecord:
7000 str = "Preprocessor: PreprocessingRecord";
7002 case CXTUResourceUsage_SourceManager_DataStructures:
7003 str = "SourceManager: data structures and tables";
7005 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7006 str = "Preprocessor: header search tables";
7012 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7013 if (isNotUsableTU(TU)) {
7015 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7019 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7020 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7021 ASTContext &astContext = astUnit->getASTContext();
7023 // How much memory is used by AST nodes and types?
7024 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7025 (unsigned long) astContext.getASTAllocatedMemory());
7027 // How much memory is used by identifiers?
7028 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7029 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7031 // How much memory is used for selectors?
7032 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7033 (unsigned long) astContext.Selectors.getTotalMemory());
7035 // How much memory is used by ASTContext's side tables?
7036 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7037 (unsigned long) astContext.getSideTableAllocatedMemory());
7039 // How much memory is used for caching global code completion results?
7040 unsigned long completionBytes = 0;
7041 if (GlobalCodeCompletionAllocator *completionAllocator =
7042 astUnit->getCachedCompletionAllocator().get()) {
7043 completionBytes = completionAllocator->getTotalMemory();
7045 createCXTUResourceUsageEntry(*entries,
7046 CXTUResourceUsage_GlobalCompletionResults,
7049 // How much memory is being used by SourceManager's content cache?
7050 createCXTUResourceUsageEntry(*entries,
7051 CXTUResourceUsage_SourceManagerContentCache,
7052 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7054 // How much memory is being used by the MemoryBuffer's in SourceManager?
7055 const SourceManager::MemoryBufferSizes &srcBufs =
7056 astUnit->getSourceManager().getMemoryBufferSizes();
7058 createCXTUResourceUsageEntry(*entries,
7059 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7060 (unsigned long) srcBufs.malloc_bytes);
7061 createCXTUResourceUsageEntry(*entries,
7062 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7063 (unsigned long) srcBufs.mmap_bytes);
7064 createCXTUResourceUsageEntry(*entries,
7065 CXTUResourceUsage_SourceManager_DataStructures,
7066 (unsigned long) astContext.getSourceManager()
7067 .getDataStructureSizes());
7069 // How much memory is being used by the ExternalASTSource?
7070 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7071 const ExternalASTSource::MemoryBufferSizes &sizes =
7072 esrc->getMemoryBufferSizes();
7074 createCXTUResourceUsageEntry(*entries,
7075 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7076 (unsigned long) sizes.malloc_bytes);
7077 createCXTUResourceUsageEntry(*entries,
7078 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7079 (unsigned long) sizes.mmap_bytes);
7082 // How much memory is being used by the Preprocessor?
7083 Preprocessor &pp = astUnit->getPreprocessor();
7084 createCXTUResourceUsageEntry(*entries,
7085 CXTUResourceUsage_Preprocessor,
7086 pp.getTotalMemory());
7088 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7089 createCXTUResourceUsageEntry(*entries,
7090 CXTUResourceUsage_PreprocessingRecord,
7091 pRec->getTotalMemory());
7094 createCXTUResourceUsageEntry(*entries,
7095 CXTUResourceUsage_Preprocessor_HeaderSearch,
7096 pp.getHeaderSearchInfo().getTotalMemory());
7098 CXTUResourceUsage usage = { (void*) entries.get(),
7099 (unsigned) entries->size(),
7100 !entries->empty() ? &(*entries)[0] : nullptr };
7105 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7107 delete (MemUsageEntries*) usage.data;
7110 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7111 CXSourceRangeList *skipped = new CXSourceRangeList;
7113 skipped->ranges = nullptr;
7115 if (isNotUsableTU(TU)) {
7123 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7124 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7128 ASTContext &Ctx = astUnit->getASTContext();
7129 SourceManager &sm = Ctx.getSourceManager();
7130 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7131 FileID wantedFileID = sm.translateFile(fileEntry);
7133 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7134 std::vector<SourceRange> wantedRanges;
7135 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7137 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7138 wantedRanges.push_back(*i);
7141 skipped->count = wantedRanges.size();
7142 skipped->ranges = new CXSourceRange[skipped->count];
7143 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7144 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7149 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7151 delete[] ranges->ranges;
7158 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7159 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7160 for (unsigned I = 0; I != Usage.numEntries; ++I)
7161 fprintf(stderr, " %s: %lu\n",
7162 clang_getTUResourceUsageName(Usage.entries[I].kind),
7163 Usage.entries[I].amount);
7165 clang_disposeCXTUResourceUsage(Usage);
7168 //===----------------------------------------------------------------------===//
7169 // Misc. utility functions.
7170 //===----------------------------------------------------------------------===//
7172 /// Default to using an 8 MB stack size on "safety" threads.
7173 static unsigned SafetyStackThreadSize = 8 << 20;
7177 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7180 Size = GetSafetyThreadStackSize();
7182 return CRC.RunSafelyOnThread(Fn, Size);
7183 return CRC.RunSafely(Fn);
7186 unsigned GetSafetyThreadStackSize() {
7187 return SafetyStackThreadSize;
7190 void SetSafetyThreadStackSize(unsigned Value) {
7191 SafetyStackThreadSize = Value;
7196 void clang::setThreadBackgroundPriority() {
7197 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7200 #ifdef USE_DARWIN_THREADS
7201 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7205 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7209 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7210 DEnd = Unit->stored_diag_end();
7212 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7213 CXString Msg = clang_formatDiagnostic(&Diag,
7214 clang_defaultDiagnosticDisplayOptions());
7215 fprintf(stderr, "%s\n", clang_getCString(Msg));
7216 clang_disposeString(Msg);
7218 #ifdef LLVM_ON_WIN32
7219 // On Windows, force a flush, since there may be multiple copies of
7220 // stderr and stdout in the file system, all with different buffers
7221 // but writing to the same device.
7226 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7227 SourceLocation MacroDefLoc,
7228 CXTranslationUnit TU){
7229 if (MacroDefLoc.isInvalid() || !TU)
7231 if (!II.hadMacroDefinition())
7234 ASTUnit *Unit = cxtu::getASTUnit(TU);
7235 Preprocessor &PP = Unit->getPreprocessor();
7236 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7238 for (MacroDirective::DefInfo
7239 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7240 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7241 return Def.getMacroInfo();
7248 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7249 CXTranslationUnit TU) {
7250 if (!MacroDef || !TU)
7252 const IdentifierInfo *II = MacroDef->getName();
7256 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7259 MacroDefinitionRecord *
7260 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7261 CXTranslationUnit TU) {
7264 if (Tok.isNot(tok::raw_identifier))
7267 if (MI->getNumTokens() == 0)
7269 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7270 MI->getDefinitionEndLoc());
7271 ASTUnit *Unit = cxtu::getASTUnit(TU);
7273 // Check that the token is inside the definition and not its argument list.
7274 SourceManager &SM = Unit->getSourceManager();
7275 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7277 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7280 Preprocessor &PP = Unit->getPreprocessor();
7281 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7285 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7286 if (!II.hadMacroDefinition())
7289 // Check that the identifier is not one of the macro arguments.
7290 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7293 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7297 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7300 MacroDefinitionRecord *
7301 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7302 CXTranslationUnit TU) {
7303 if (Loc.isInvalid() || !MI || !TU)
7306 if (MI->getNumTokens() == 0)
7308 ASTUnit *Unit = cxtu::getASTUnit(TU);
7309 Preprocessor &PP = Unit->getPreprocessor();
7310 if (!PP.getPreprocessingRecord())
7312 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7314 if (PP.getRawToken(Loc, Tok))
7317 return checkForMacroInMacroDefinition(MI, Tok, TU);
7322 CXString clang_getClangVersion() {
7323 return cxstring::createDup(getClangFullVersion());
7326 } // end: extern "C"
7328 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7330 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7331 LogOS << '<' << Unit->getMainFileName() << '>';
7332 if (Unit->isMainFileAST())
7333 LogOS << " (" << Unit->getASTFileName() << ')';
7337 LogOS << "<NULL TU>";
7342 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7343 *this << FE->getName();
7347 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7348 CXString cursorName = clang_getCursorDisplayName(cursor);
7349 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7350 clang_disposeString(cursorName);
7354 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7356 unsigned Line, Column;
7357 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7358 CXString FileName = clang_getFileName(File);
7359 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7360 clang_disposeString(FileName);
7364 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7365 CXSourceLocation BLoc = clang_getRangeStart(range);
7366 CXSourceLocation ELoc = clang_getRangeEnd(range);
7369 unsigned BLine, BColumn;
7370 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7373 unsigned ELine, EColumn;
7374 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7376 CXString BFileName = clang_getFileName(BFile);
7377 if (BFile == EFile) {
7378 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7379 BLine, BColumn, ELine, EColumn);
7381 CXString EFileName = clang_getFileName(EFile);
7382 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7384 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7386 clang_disposeString(EFileName);
7388 clang_disposeString(BFileName);
7392 Logger &cxindex::Logger::operator<<(CXString Str) {
7393 *this << clang_getCString(Str);
7397 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7402 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7404 cxindex::Logger::~Logger() {
7405 llvm::sys::ScopedLock L(*LoggingMutex);
7407 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7409 raw_ostream &OS = llvm::errs();
7410 OS << "[libclang:" << Name << ':';
7412 #ifdef USE_DARWIN_THREADS
7413 // TODO: Portability.
7414 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7418 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7419 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7423 llvm::sys::PrintStackTrace(OS);
7424 OS << "--------------------------------------------------\n";