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/StmtVisitor.h"
26 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Basic/DiagnosticCategories.h"
28 #include "clang/Basic/DiagnosticIDs.h"
29 #include "clang/Basic/Version.h"
30 #include "clang/Frontend/ASTUnit.h"
31 #include "clang/Frontend/CompilerInstance.h"
32 #include "clang/Frontend/FrontendDiagnostic.h"
33 #include "clang/Index/CodegenNameGenerator.h"
34 #include "clang/Index/CommentToXML.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "clang/Lex/Lexer.h"
37 #include "clang/Lex/PreprocessingRecord.h"
38 #include "clang/Lex/Preprocessor.h"
39 #include "clang/Serialization/SerializationDiagnostic.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Config/llvm-config.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/CrashRecoveryContext.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Mutex.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/Threading.h"
55 #include "llvm/Support/Timer.h"
56 #include "llvm/Support/raw_ostream.h"
58 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59 #define USE_DARWIN_THREADS
62 #ifdef USE_DARWIN_THREADS
66 using namespace clang;
67 using namespace clang::cxcursor;
68 using namespace clang::cxtu;
69 using namespace clang::cxindex;
71 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
75 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->StringPool = new cxstring::CXStringPool();
79 D->Diagnostics = nullptr;
80 D->OverridenCursorsPool = createOverridenCXCursorsPool();
81 D->CommentToXML = nullptr;
85 bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
97 cxtu::CXTUOwner::~CXTUOwner() {
99 clang_disposeTranslationUnit(TU);
102 /// \brief Compare two source ranges to determine their relative position in
103 /// the translation unit.
104 static RangeComparisonResult RangeCompare(SourceManager &SM,
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118 /// \brief Determine if a source location falls within, before, or after a
119 /// a given source range.
120 static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133 /// \brief Translate a Clang source range into a CIndex source range.
135 /// Clang internally represents ranges where the end location points to the
136 /// start of the token at the end. However, for external clients it is more
137 /// useful to have a CXSourceRange be a proper half-open interval. This routine
138 /// does the appropriate translation.
139 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
147 if (R.isTokenRange() && EndLoc.isValid()) {
148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
150 EndLoc = EndLoc.getLocWithOffset(Length);
153 CXSourceRange Result = {
155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
161 //===----------------------------------------------------------------------===//
163 //===----------------------------------------------------------------------===//
165 static SourceRange getRawCursorExtent(CXCursor C);
166 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
169 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
173 /// \brief Visit the given cursor and, if requested by the visitor,
176 /// \param Cursor the cursor to visit.
178 /// \param CheckedRegionOfInterest if true, then the caller already checked
179 /// that this cursor is within the region of interest.
181 /// \returns true if the visitation should be aborted, false if it
183 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
187 if (clang_isDeclaration(Cursor.kind)) {
188 const Decl *D = getCursorDecl(Cursor);
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
200 // If we have a range of interest, and this cursor doesn't intersect with it,
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
212 case CXChildVisit_Continue:
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
224 llvm_unreachable("Invalid CXChildVisitResult!");
227 static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
246 bool CursorVisitor::visitFileRegion() {
247 if (RegionOfInterest.isInvalid())
250 ASTUnit *Unit = cxtu::getASTUnit(TU);
251 SourceManager &SM = Unit->getSourceManager();
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
274 return true; // visitation break.
276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
280 return visitPreprocessedEntitiesInRegion();
285 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
297 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
298 unsigned Offset, unsigned Length) {
299 ASTUnit *Unit = cxtu::getASTUnit(TU);
300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
327 assert(!Decls.empty());
329 bool VisitedAtLeastOnce = false;
330 DeclContext *CurDC = nullptr;
331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
334 if (D->getSourceRange().isInvalid())
337 if (isInLexicalContext(D, CurDC))
340 CurDC = dyn_cast<DeclContext>(D);
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
349 if (CompRes == RangeAfter)
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
359 FileDI_current = nullptr;
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
363 return true; // visitation break.
366 if (VisitedAtLeastOnce)
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
386 DC = D->getLexicalDeclContext();
392 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
439 template<typename InputIterator>
440 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
442 PreprocessingRecord &PPRec,
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
448 PreprocessedEntity *PPE = *First;
452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
477 /// \brief Visit the children of the given cursor.
479 /// \returns true if the visitation should be aborted, false if it
481 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
488 // Set the Parent field to Cursor, then back to its old value once we're
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
492 if (clang_isDeclaration(Cursor.kind)) {
493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
497 return VisitAttributes(D) || Visit(D);
500 if (clang_isStatement(Cursor.kind)) {
501 if (const Stmt *S = getCursorStmt(Cursor))
507 if (clang_isExpression(Cursor.kind)) {
508 if (const Expr *E = getCursorExpr(Cursor))
514 if (clang_isTranslationUnit(Cursor.kind)) {
515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
526 if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
529 } else if (VisitDeclContext(
530 CXXUnit->getASTContext().getTranslationUnitDecl()))
535 // Walk the preprocessing record.
536 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
537 visitPreprocessedEntitiesInRegion();
543 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
544 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
545 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
546 return Visit(BaseTSInfo->getTypeLoc());
551 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
552 const IBOutletCollectionAttr *A =
553 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
554 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
555 return Visit(cxcursor::MakeCursorObjCClassRef(
556 ObjT->getInterface(),
557 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
560 // If pointing inside a macro definition, check if the token is an identifier
561 // that was ever defined as a macro. In such a case, create a "pseudo" macro
562 // expansion cursor for that token.
563 SourceLocation BeginLoc = RegionOfInterest.getBegin();
564 if (Cursor.kind == CXCursor_MacroDefinition &&
565 BeginLoc == RegionOfInterest.getEnd()) {
566 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
567 const MacroInfo *MI =
568 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
569 if (MacroDefinitionRecord *MacroDef =
570 checkForMacroInMacroDefinition(MI, Loc, TU))
571 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
574 // Nothing to visit at the moment.
578 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
579 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
580 if (Visit(TSInfo->getTypeLoc()))
583 if (Stmt *Body = B->getBody())
584 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
589 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
590 if (RegionOfInterest.isValid()) {
591 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
592 if (Range.isInvalid())
595 switch (CompareRegionOfInterest(Range)) {
597 // This declaration comes before the region of interest; skip it.
601 // This declaration comes after the region of interest; we're done.
605 // This declaration overlaps the region of interest; visit it.
612 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
613 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
615 // FIXME: Eventually remove. This part of a hack to support proper
616 // iteration over all Decls contained lexically within an ObjC container.
617 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
618 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
620 for ( ; I != E; ++I) {
622 if (D->getLexicalDeclContext() != DC)
624 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
626 // Ignore synthesized ivars here, otherwise if we have something like:
627 // @synthesize prop = _prop;
628 // and '_prop' is not declared, we will encounter a '_prop' ivar before
629 // encountering the 'prop' synthesize declaration and we will think that
630 // we passed the region-of-interest.
631 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
632 if (ivarD->getSynthesize())
636 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
637 // declarations is a mismatch with the compiler semantics.
638 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
639 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
640 if (!ID->isThisDeclarationADefinition())
641 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
643 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
644 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
645 if (!PD->isThisDeclarationADefinition())
646 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
649 const Optional<bool> &V = shouldVisitCursor(Cursor);
654 if (Visit(Cursor, true))
660 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
661 llvm_unreachable("Translation units are visited directly by Visit()");
664 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
665 if (VisitTemplateParameters(D->getTemplateParameters()))
668 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
671 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
672 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
673 return Visit(TSInfo->getTypeLoc());
678 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
679 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
680 return Visit(TSInfo->getTypeLoc());
685 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
686 return VisitDeclContext(D);
689 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
690 ClassTemplateSpecializationDecl *D) {
691 bool ShouldVisitBody = false;
692 switch (D->getSpecializationKind()) {
694 case TSK_ImplicitInstantiation:
698 case TSK_ExplicitInstantiationDeclaration:
699 case TSK_ExplicitInstantiationDefinition:
702 case TSK_ExplicitSpecialization:
703 ShouldVisitBody = true;
707 // Visit the template arguments used in the specialization.
708 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
709 TypeLoc TL = SpecType->getTypeLoc();
710 if (TemplateSpecializationTypeLoc TSTLoc =
711 TL.getAs<TemplateSpecializationTypeLoc>()) {
712 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
713 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
718 return ShouldVisitBody && VisitCXXRecordDecl(D);
721 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
722 ClassTemplatePartialSpecializationDecl *D) {
723 // FIXME: Visit the "outer" template parameter lists on the TagDecl
724 // before visiting these template parameters.
725 if (VisitTemplateParameters(D->getTemplateParameters()))
728 // Visit the partial specialization arguments.
729 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
730 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
731 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
732 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
735 return VisitCXXRecordDecl(D);
738 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
739 // Visit the default argument.
740 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
741 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
742 if (Visit(DefArg->getTypeLoc()))
748 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
749 if (Expr *Init = D->getInitExpr())
750 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
754 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
755 unsigned NumParamList = DD->getNumTemplateParameterLists();
756 for (unsigned i = 0; i < NumParamList; i++) {
757 TemplateParameterList* Params = DD->getTemplateParameterList(i);
758 if (VisitTemplateParameters(Params))
762 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
763 if (Visit(TSInfo->getTypeLoc()))
766 // Visit the nested-name-specifier, if present.
767 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
768 if (VisitNestedNameSpecifierLoc(QualifierLoc))
774 /// \brief Compare two base or member initializers based on their source order.
775 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
776 CXXCtorInitializer *const *Y) {
777 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
780 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
781 unsigned NumParamList = ND->getNumTemplateParameterLists();
782 for (unsigned i = 0; i < NumParamList; i++) {
783 TemplateParameterList* Params = ND->getTemplateParameterList(i);
784 if (VisitTemplateParameters(Params))
788 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
789 // Visit the function declaration's syntactic components in the order
790 // written. This requires a bit of work.
791 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
792 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
794 // If we have a function declared directly (without the use of a typedef),
795 // visit just the return type. Otherwise, just visit the function's type
797 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
801 // Visit the nested-name-specifier, if present.
802 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
803 if (VisitNestedNameSpecifierLoc(QualifierLoc))
806 // Visit the declaration name.
807 if (!isa<CXXDestructorDecl>(ND))
808 if (VisitDeclarationNameInfo(ND->getNameInfo()))
811 // FIXME: Visit explicitly-specified template arguments!
813 // Visit the function parameters, if we have a function type.
814 if (FTL && VisitFunctionTypeLoc(FTL, true))
817 // FIXME: Attributes?
820 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
821 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
822 // Find the initializers that were written in the source.
823 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
824 for (auto *I : Constructor->inits()) {
828 WrittenInits.push_back(I);
831 // Sort the initializers in source order
832 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
833 &CompareCXXCtorInitializers);
835 // Visit the initializers in source order
836 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
837 CXXCtorInitializer *Init = WrittenInits[I];
838 if (Init->isAnyMemberInitializer()) {
839 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
840 Init->getMemberLocation(), TU)))
842 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
843 if (Visit(TInfo->getTypeLoc()))
847 // Visit the initializer value.
848 if (Expr *Initializer = Init->getInit())
849 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
854 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
861 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
862 if (VisitDeclaratorDecl(D))
865 if (Expr *BitWidth = D->getBitWidth())
866 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
871 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
872 if (VisitDeclaratorDecl(D))
875 if (Expr *Init = D->getInit())
876 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
881 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
882 if (VisitDeclaratorDecl(D))
885 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
886 if (Expr *DefArg = D->getDefaultArgument())
887 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
892 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
893 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
894 // before visiting these template parameters.
895 if (VisitTemplateParameters(D->getTemplateParameters()))
898 return VisitFunctionDecl(D->getTemplatedDecl());
901 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
902 // FIXME: Visit the "outer" template parameter lists on the TagDecl
903 // before visiting these template parameters.
904 if (VisitTemplateParameters(D->getTemplateParameters()))
907 return VisitCXXRecordDecl(D->getTemplatedDecl());
910 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
911 if (VisitTemplateParameters(D->getTemplateParameters()))
914 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
915 VisitTemplateArgumentLoc(D->getDefaultArgument()))
921 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
922 // Visit the bound, if it's explicit.
923 if (D->hasExplicitBound()) {
924 if (auto TInfo = D->getTypeSourceInfo()) {
925 if (Visit(TInfo->getTypeLoc()))
933 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
934 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
935 if (Visit(TSInfo->getTypeLoc()))
938 for (const auto *P : ND->params()) {
939 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
943 return ND->isThisDeclarationADefinition() &&
944 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
947 template <typename DeclIt>
948 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
949 SourceManager &SM, SourceLocation EndLoc,
950 SmallVectorImpl<Decl *> &Decls) {
951 DeclIt next = *DI_current;
952 while (++next != DE_current) {
953 Decl *D_next = *next;
956 SourceLocation L = D_next->getLocStart();
959 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
961 Decls.push_back(D_next);
968 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
969 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
970 // an @implementation can lexically contain Decls that are not properly
971 // nested in the AST. When we identify such cases, we need to retrofit
972 // this nesting here.
973 if (!DI_current && !FileDI_current)
974 return VisitDeclContext(D);
976 // Scan the Decls that immediately come after the container
977 // in the current DeclContext. If any fall within the
978 // container's lexical region, stash them into a vector
979 // for later processing.
980 SmallVector<Decl *, 24> DeclsInContainer;
981 SourceLocation EndLoc = D->getSourceRange().getEnd();
982 SourceManager &SM = AU->getSourceManager();
983 if (EndLoc.isValid()) {
985 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
988 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
994 if (DeclsInContainer.empty())
995 return VisitDeclContext(D);
997 // Get all the Decls in the DeclContext, and sort them with the
998 // additional ones we've collected. Then visit them.
999 for (auto *SubDecl : D->decls()) {
1000 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1001 SubDecl->getLocStart().isInvalid())
1003 DeclsInContainer.push_back(SubDecl);
1006 // Now sort the Decls so that they appear in lexical order.
1007 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1008 [&SM](Decl *A, Decl *B) {
1009 SourceLocation L_A = A->getLocStart();
1010 SourceLocation L_B = B->getLocStart();
1011 assert(L_A.isValid() && L_B.isValid());
1012 return SM.isBeforeInTranslationUnit(L_A, L_B);
1015 // Now visit the decls.
1016 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1017 E = DeclsInContainer.end(); I != E; ++I) {
1018 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1019 const Optional<bool> &V = shouldVisitCursor(Cursor);
1024 if (Visit(Cursor, true))
1030 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1031 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1035 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1038 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1039 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1040 E = ND->protocol_end(); I != E; ++I, ++PL)
1041 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1044 return VisitObjCContainerDecl(ND);
1047 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1048 if (!PID->isThisDeclarationADefinition())
1049 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1051 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1052 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1053 E = PID->protocol_end(); I != E; ++I, ++PL)
1054 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1057 return VisitObjCContainerDecl(PID);
1060 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1061 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1064 // FIXME: This implements a workaround with @property declarations also being
1065 // installed in the DeclContext for the @interface. Eventually this code
1066 // should be removed.
1067 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1068 if (!CDecl || !CDecl->IsClassExtension())
1071 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1075 IdentifierInfo *PropertyId = PD->getIdentifier();
1076 ObjCPropertyDecl *prevDecl =
1077 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1078 PD->getQueryKind());
1083 // Visit synthesized methods since they will be skipped when visiting
1085 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1086 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1087 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1090 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1091 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1092 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1102 for (auto *typeParam : *typeParamList) {
1103 // Visit the type parameter.
1104 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1111 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1112 if (!D->isThisDeclarationADefinition()) {
1113 // Forward declaration is treated like a reference.
1114 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1117 // Objective-C type parameters.
1118 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1121 // Issue callbacks for super class.
1122 if (D->getSuperClass() &&
1123 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1124 D->getSuperClassLoc(),
1128 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1129 if (Visit(SuperClassTInfo->getTypeLoc()))
1132 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1133 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1134 E = D->protocol_end(); I != E; ++I, ++PL)
1135 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1138 return VisitObjCContainerDecl(D);
1141 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1142 return VisitObjCContainerDecl(D);
1145 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1146 // 'ID' could be null when dealing with invalid code.
1147 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1148 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1151 return VisitObjCImplDecl(D);
1154 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1156 // Issue callbacks for super class.
1157 // FIXME: No source location information!
1158 if (D->getSuperClass() &&
1159 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1160 D->getSuperClassLoc(),
1165 return VisitObjCImplDecl(D);
1168 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1169 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1170 if (PD->isIvarNameSpecified())
1171 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1176 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1177 return VisitDeclContext(D);
1180 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1181 // Visit nested-name-specifier.
1182 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1183 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1186 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1187 D->getTargetNameLoc(), TU));
1190 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1197 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1200 return VisitDeclarationNameInfo(D->getNameInfo());
1203 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1204 // Visit nested-name-specifier.
1205 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1206 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1209 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1210 D->getIdentLocation(), TU));
1213 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1220 return VisitDeclarationNameInfo(D->getNameInfo());
1223 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1224 UnresolvedUsingTypenameDecl *D) {
1225 // Visit nested-name-specifier.
1226 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1227 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1233 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1234 switch (Name.getName().getNameKind()) {
1235 case clang::DeclarationName::Identifier:
1236 case clang::DeclarationName::CXXLiteralOperatorName:
1237 case clang::DeclarationName::CXXOperatorName:
1238 case clang::DeclarationName::CXXUsingDirective:
1241 case clang::DeclarationName::CXXConstructorName:
1242 case clang::DeclarationName::CXXDestructorName:
1243 case clang::DeclarationName::CXXConversionFunctionName:
1244 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1245 return Visit(TSInfo->getTypeLoc());
1248 case clang::DeclarationName::ObjCZeroArgSelector:
1249 case clang::DeclarationName::ObjCOneArgSelector:
1250 case clang::DeclarationName::ObjCMultiArgSelector:
1251 // FIXME: Per-identifier location info?
1255 llvm_unreachable("Invalid DeclarationName::Kind!");
1258 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1259 SourceRange Range) {
1260 // FIXME: This whole routine is a hack to work around the lack of proper
1261 // source information in nested-name-specifiers (PR5791). Since we do have
1262 // a beginning source location, we can visit the first component of the
1263 // nested-name-specifier, if it's a single-token component.
1267 // Get the first component in the nested-name-specifier.
1268 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1271 switch (NNS->getKind()) {
1272 case NestedNameSpecifier::Namespace:
1273 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1276 case NestedNameSpecifier::NamespaceAlias:
1277 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1278 Range.getBegin(), TU));
1280 case NestedNameSpecifier::TypeSpec: {
1281 // If the type has a form where we know that the beginning of the source
1282 // range matches up with a reference cursor. Visit the appropriate reference
1284 const Type *T = NNS->getAsType();
1285 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1286 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1287 if (const TagType *Tag = dyn_cast<TagType>(T))
1288 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1289 if (const TemplateSpecializationType *TST
1290 = dyn_cast<TemplateSpecializationType>(T))
1291 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1295 case NestedNameSpecifier::TypeSpecWithTemplate:
1296 case NestedNameSpecifier::Global:
1297 case NestedNameSpecifier::Identifier:
1298 case NestedNameSpecifier::Super:
1306 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1307 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1308 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1309 Qualifiers.push_back(Qualifier);
1311 while (!Qualifiers.empty()) {
1312 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1313 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1314 switch (NNS->getKind()) {
1315 case NestedNameSpecifier::Namespace:
1316 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1317 Q.getLocalBeginLoc(),
1323 case NestedNameSpecifier::NamespaceAlias:
1324 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1325 Q.getLocalBeginLoc(),
1331 case NestedNameSpecifier::TypeSpec:
1332 case NestedNameSpecifier::TypeSpecWithTemplate:
1333 if (Visit(Q.getTypeLoc()))
1338 case NestedNameSpecifier::Global:
1339 case NestedNameSpecifier::Identifier:
1340 case NestedNameSpecifier::Super:
1348 bool CursorVisitor::VisitTemplateParameters(
1349 const TemplateParameterList *Params) {
1353 for (TemplateParameterList::const_iterator P = Params->begin(),
1354 PEnd = Params->end();
1356 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1363 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1364 switch (Name.getKind()) {
1365 case TemplateName::Template:
1366 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1368 case TemplateName::OverloadedTemplate:
1369 // Visit the overloaded template set.
1370 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1375 case TemplateName::DependentTemplate:
1376 // FIXME: Visit nested-name-specifier.
1379 case TemplateName::QualifiedTemplate:
1380 // FIXME: Visit nested-name-specifier.
1381 return Visit(MakeCursorTemplateRef(
1382 Name.getAsQualifiedTemplateName()->getDecl(),
1385 case TemplateName::SubstTemplateTemplateParm:
1386 return Visit(MakeCursorTemplateRef(
1387 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1390 case TemplateName::SubstTemplateTemplateParmPack:
1391 return Visit(MakeCursorTemplateRef(
1392 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1396 llvm_unreachable("Invalid TemplateName::Kind!");
1399 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1400 switch (TAL.getArgument().getKind()) {
1401 case TemplateArgument::Null:
1402 case TemplateArgument::Integral:
1403 case TemplateArgument::Pack:
1406 case TemplateArgument::Type:
1407 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1408 return Visit(TSInfo->getTypeLoc());
1411 case TemplateArgument::Declaration:
1412 if (Expr *E = TAL.getSourceDeclExpression())
1413 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1416 case TemplateArgument::NullPtr:
1417 if (Expr *E = TAL.getSourceNullPtrExpression())
1418 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1421 case TemplateArgument::Expression:
1422 if (Expr *E = TAL.getSourceExpression())
1423 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1426 case TemplateArgument::Template:
1427 case TemplateArgument::TemplateExpansion:
1428 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1431 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1432 TAL.getTemplateNameLoc());
1435 llvm_unreachable("Invalid TemplateArgument::Kind!");
1438 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1439 return VisitDeclContext(D);
1442 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1443 return Visit(TL.getUnqualifiedLoc());
1446 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1447 ASTContext &Context = AU->getASTContext();
1449 // Some builtin types (such as Objective-C's "id", "sel", and
1450 // "Class") have associated declarations. Create cursors for those.
1452 switch (TL.getTypePtr()->getKind()) {
1454 case BuiltinType::Void:
1455 case BuiltinType::NullPtr:
1456 case BuiltinType::Dependent:
1457 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1458 case BuiltinType::Id:
1459 #include "clang/Basic/OpenCLImageTypes.def"
1460 case BuiltinType::OCLSampler:
1461 case BuiltinType::OCLEvent:
1462 case BuiltinType::OCLClkEvent:
1463 case BuiltinType::OCLQueue:
1464 case BuiltinType::OCLNDRange:
1465 case BuiltinType::OCLReserveID:
1466 #define BUILTIN_TYPE(Id, SingletonId)
1467 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1468 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1469 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1470 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1471 #include "clang/AST/BuiltinTypes.def"
1474 case BuiltinType::ObjCId:
1475 VisitType = Context.getObjCIdType();
1478 case BuiltinType::ObjCClass:
1479 VisitType = Context.getObjCClassType();
1482 case BuiltinType::ObjCSel:
1483 VisitType = Context.getObjCSelType();
1487 if (!VisitType.isNull()) {
1488 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1489 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1496 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1497 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1500 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1501 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1504 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1505 if (TL.isDefinition())
1506 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1508 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1511 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1512 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1515 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1516 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1519 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1520 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1523 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1524 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1528 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1529 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1537 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1538 return Visit(TL.getPointeeLoc());
1541 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1542 return Visit(TL.getInnerLoc());
1545 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1546 return Visit(TL.getPointeeLoc());
1549 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1550 return Visit(TL.getPointeeLoc());
1553 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1554 return Visit(TL.getPointeeLoc());
1557 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1558 return Visit(TL.getPointeeLoc());
1561 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1562 return Visit(TL.getPointeeLoc());
1565 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1566 return Visit(TL.getModifiedLoc());
1569 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1570 bool SkipResultType) {
1571 if (!SkipResultType && Visit(TL.getReturnLoc()))
1574 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1575 if (Decl *D = TL.getParam(I))
1576 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1582 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1583 if (Visit(TL.getElementLoc()))
1586 if (Expr *Size = TL.getSizeExpr())
1587 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1592 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1593 return Visit(TL.getOriginalLoc());
1596 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1597 return Visit(TL.getOriginalLoc());
1600 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1601 TemplateSpecializationTypeLoc TL) {
1602 // Visit the template name.
1603 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1604 TL.getTemplateNameLoc()))
1607 // Visit the template arguments.
1608 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1609 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1615 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1616 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1619 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1620 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1621 return Visit(TSInfo->getTypeLoc());
1626 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1627 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1628 return Visit(TSInfo->getTypeLoc());
1633 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1634 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1637 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1638 DependentTemplateSpecializationTypeLoc TL) {
1639 // Visit the nested-name-specifier, if there is one.
1640 if (TL.getQualifierLoc() &&
1641 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1644 // Visit the template arguments.
1645 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1646 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1652 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1653 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1656 return Visit(TL.getNamedTypeLoc());
1659 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1660 return Visit(TL.getPatternLoc());
1663 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1664 if (Expr *E = TL.getUnderlyingExpr())
1665 return Visit(MakeCXCursor(E, StmtParent, TU));
1670 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1671 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1674 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1675 return Visit(TL.getValueLoc());
1678 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1679 return Visit(TL.getValueLoc());
1682 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1683 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1684 return Visit##PARENT##Loc(TL); \
1687 DEFAULT_TYPELOC_IMPL(Complex, Type)
1688 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1689 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1690 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1691 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1692 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1693 DEFAULT_TYPELOC_IMPL(Vector, Type)
1694 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1695 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1696 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1697 DEFAULT_TYPELOC_IMPL(Record, TagType)
1698 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1699 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1700 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1701 DEFAULT_TYPELOC_IMPL(Auto, Type)
1703 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1704 // Visit the nested-name-specifier, if present.
1705 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1706 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1709 if (D->isCompleteDefinition()) {
1710 for (const auto &I : D->bases()) {
1711 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1716 return VisitTagDecl(D);
1719 bool CursorVisitor::VisitAttributes(Decl *D) {
1720 for (const auto *I : D->attrs())
1721 if (Visit(MakeCXCursor(I, D, TU)))
1727 //===----------------------------------------------------------------------===//
1728 // Data-recursive visitor methods.
1729 //===----------------------------------------------------------------------===//
1732 #define DEF_JOB(NAME, DATA, KIND)\
1733 class NAME : public VisitorJob {\
1735 NAME(const DATA *d, CXCursor parent) : \
1736 VisitorJob(parent, VisitorJob::KIND, d) {} \
1737 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1738 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1741 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1742 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1743 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1744 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1745 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1746 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1747 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1750 class ExplicitTemplateArgsVisit : public VisitorJob {
1752 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1753 const TemplateArgumentLoc *End, CXCursor parent)
1754 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1756 static bool classof(const VisitorJob *VJ) {
1757 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1759 const TemplateArgumentLoc *begin() const {
1760 return static_cast<const TemplateArgumentLoc *>(data[0]);
1762 const TemplateArgumentLoc *end() {
1763 return static_cast<const TemplateArgumentLoc *>(data[1]);
1766 class DeclVisit : public VisitorJob {
1768 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1769 VisitorJob(parent, VisitorJob::DeclVisitKind,
1770 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1771 static bool classof(const VisitorJob *VJ) {
1772 return VJ->getKind() == DeclVisitKind;
1774 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1775 bool isFirst() const { return data[1] != nullptr; }
1777 class TypeLocVisit : public VisitorJob {
1779 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1780 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1781 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1783 static bool classof(const VisitorJob *VJ) {
1784 return VJ->getKind() == TypeLocVisitKind;
1787 TypeLoc get() const {
1788 QualType T = QualType::getFromOpaquePtr(data[0]);
1789 return TypeLoc(T, const_cast<void *>(data[1]));
1793 class LabelRefVisit : public VisitorJob {
1795 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1796 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1797 labelLoc.getPtrEncoding()) {}
1799 static bool classof(const VisitorJob *VJ) {
1800 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1802 const LabelDecl *get() const {
1803 return static_cast<const LabelDecl *>(data[0]);
1805 SourceLocation getLoc() const {
1806 return SourceLocation::getFromPtrEncoding(data[1]); }
1809 class NestedNameSpecifierLocVisit : public VisitorJob {
1811 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1812 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1813 Qualifier.getNestedNameSpecifier(),
1814 Qualifier.getOpaqueData()) { }
1816 static bool classof(const VisitorJob *VJ) {
1817 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1820 NestedNameSpecifierLoc get() const {
1821 return NestedNameSpecifierLoc(
1822 const_cast<NestedNameSpecifier *>(
1823 static_cast<const NestedNameSpecifier *>(data[0])),
1824 const_cast<void *>(data[1]));
1828 class DeclarationNameInfoVisit : public VisitorJob {
1830 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1831 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1832 static bool classof(const VisitorJob *VJ) {
1833 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1835 DeclarationNameInfo get() const {
1836 const Stmt *S = static_cast<const Stmt *>(data[0]);
1837 switch (S->getStmtClass()) {
1839 llvm_unreachable("Unhandled Stmt");
1840 case clang::Stmt::MSDependentExistsStmtClass:
1841 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1842 case Stmt::CXXDependentScopeMemberExprClass:
1843 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1844 case Stmt::DependentScopeDeclRefExprClass:
1845 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1846 case Stmt::OMPCriticalDirectiveClass:
1847 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1851 class MemberRefVisit : public VisitorJob {
1853 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1854 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1855 L.getPtrEncoding()) {}
1856 static bool classof(const VisitorJob *VJ) {
1857 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1859 const FieldDecl *get() const {
1860 return static_cast<const FieldDecl *>(data[0]);
1862 SourceLocation getLoc() const {
1863 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1866 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1867 friend class OMPClauseEnqueue;
1868 VisitorWorkList &WL;
1871 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1872 : WL(wl), Parent(parent) {}
1874 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1875 void VisitBlockExpr(const BlockExpr *B);
1876 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1877 void VisitCompoundStmt(const CompoundStmt *S);
1878 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1879 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1880 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1881 void VisitCXXNewExpr(const CXXNewExpr *E);
1882 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1883 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1884 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1885 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1886 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1887 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1888 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1889 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1890 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1891 void VisitDeclRefExpr(const DeclRefExpr *D);
1892 void VisitDeclStmt(const DeclStmt *S);
1893 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1894 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1895 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1896 void VisitForStmt(const ForStmt *FS);
1897 void VisitGotoStmt(const GotoStmt *GS);
1898 void VisitIfStmt(const IfStmt *If);
1899 void VisitInitListExpr(const InitListExpr *IE);
1900 void VisitMemberExpr(const MemberExpr *M);
1901 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1902 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1903 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1904 void VisitOverloadExpr(const OverloadExpr *E);
1905 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1906 void VisitStmt(const Stmt *S);
1907 void VisitSwitchStmt(const SwitchStmt *S);
1908 void VisitWhileStmt(const WhileStmt *W);
1909 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1910 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1911 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1912 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1913 void VisitVAArgExpr(const VAArgExpr *E);
1914 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1915 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1916 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1917 void VisitLambdaExpr(const LambdaExpr *E);
1918 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1919 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1920 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1921 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1922 void VisitOMPForDirective(const OMPForDirective *D);
1923 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1924 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1925 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1926 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1927 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1928 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1929 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1930 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1931 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1932 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1933 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1934 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1935 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1936 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1938 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1939 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1940 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1941 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1942 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1943 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1944 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1945 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
1946 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
1947 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
1949 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
1950 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1951 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
1952 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
1953 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
1956 void AddDeclarationNameInfo(const Stmt *S);
1957 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1958 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1959 unsigned NumTemplateArgs);
1960 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1961 void AddStmt(const Stmt *S);
1962 void AddDecl(const Decl *D, bool isFirst = true);
1963 void AddTypeLoc(TypeSourceInfo *TI);
1964 void EnqueueChildren(const Stmt *S);
1965 void EnqueueChildren(const OMPClause *S);
1967 } // end anonyous namespace
1969 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1970 // 'S' should always be non-null, since it comes from the
1971 // statement we are visiting.
1972 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1976 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1978 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1981 void EnqueueVisitor::AddStmt(const Stmt *S) {
1983 WL.push_back(StmtVisit(S, Parent));
1985 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1987 WL.push_back(DeclVisit(D, Parent, isFirst));
1989 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1990 unsigned NumTemplateArgs) {
1991 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
1993 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
1995 WL.push_back(MemberRefVisit(D, L, Parent));
1997 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1999 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2001 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2002 unsigned size = WL.size();
2003 for (const Stmt *SubStmt : S->children()) {
2006 if (size == WL.size())
2008 // Now reverse the entries we just added. This will match the DFS
2009 // ordering performed by the worklist.
2010 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2014 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2015 EnqueueVisitor *Visitor;
2016 /// \brief Process clauses with list of variables.
2017 template <typename T>
2018 void VisitOMPClauseList(T *Node);
2020 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2021 #define OPENMP_CLAUSE(Name, Class) \
2022 void Visit##Class(const Class *C);
2023 #include "clang/Basic/OpenMPKinds.def"
2024 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2025 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2028 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2029 const OMPClauseWithPreInit *C) {
2030 Visitor->AddStmt(C->getPreInitStmt());
2033 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2034 const OMPClauseWithPostUpdate *C) {
2035 VisitOMPClauseWithPreInit(C);
2036 Visitor->AddStmt(C->getPostUpdateExpr());
2039 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2040 Visitor->AddStmt(C->getCondition());
2043 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2044 Visitor->AddStmt(C->getCondition());
2047 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2048 Visitor->AddStmt(C->getNumThreads());
2051 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2052 Visitor->AddStmt(C->getSafelen());
2055 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2056 Visitor->AddStmt(C->getSimdlen());
2059 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2060 Visitor->AddStmt(C->getNumForLoops());
2063 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2065 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2067 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2068 VisitOMPClauseWithPreInit(C);
2069 Visitor->AddStmt(C->getChunkSize());
2072 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2073 Visitor->AddStmt(C->getNumForLoops());
2076 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2078 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2080 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2082 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2084 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2086 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2088 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2090 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2092 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2094 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2096 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2098 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2099 Visitor->AddStmt(C->getDevice());
2102 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2103 Visitor->AddStmt(C->getNumTeams());
2106 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2107 Visitor->AddStmt(C->getThreadLimit());
2110 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2111 Visitor->AddStmt(C->getPriority());
2114 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2115 Visitor->AddStmt(C->getGrainsize());
2118 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2119 Visitor->AddStmt(C->getNumTasks());
2122 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2123 Visitor->AddStmt(C->getHint());
2126 template<typename T>
2127 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2128 for (const auto *I : Node->varlists()) {
2129 Visitor->AddStmt(I);
2133 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2134 VisitOMPClauseList(C);
2135 for (const auto *E : C->private_copies()) {
2136 Visitor->AddStmt(E);
2139 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2140 const OMPFirstprivateClause *C) {
2141 VisitOMPClauseList(C);
2142 VisitOMPClauseWithPreInit(C);
2143 for (const auto *E : C->private_copies()) {
2144 Visitor->AddStmt(E);
2146 for (const auto *E : C->inits()) {
2147 Visitor->AddStmt(E);
2150 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2151 const OMPLastprivateClause *C) {
2152 VisitOMPClauseList(C);
2153 VisitOMPClauseWithPostUpdate(C);
2154 for (auto *E : C->private_copies()) {
2155 Visitor->AddStmt(E);
2157 for (auto *E : C->source_exprs()) {
2158 Visitor->AddStmt(E);
2160 for (auto *E : C->destination_exprs()) {
2161 Visitor->AddStmt(E);
2163 for (auto *E : C->assignment_ops()) {
2164 Visitor->AddStmt(E);
2167 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2168 VisitOMPClauseList(C);
2170 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2171 VisitOMPClauseList(C);
2172 VisitOMPClauseWithPostUpdate(C);
2173 for (auto *E : C->privates()) {
2174 Visitor->AddStmt(E);
2176 for (auto *E : C->lhs_exprs()) {
2177 Visitor->AddStmt(E);
2179 for (auto *E : C->rhs_exprs()) {
2180 Visitor->AddStmt(E);
2182 for (auto *E : C->reduction_ops()) {
2183 Visitor->AddStmt(E);
2186 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2187 VisitOMPClauseList(C);
2188 VisitOMPClauseWithPostUpdate(C);
2189 for (const auto *E : C->privates()) {
2190 Visitor->AddStmt(E);
2192 for (const auto *E : C->inits()) {
2193 Visitor->AddStmt(E);
2195 for (const auto *E : C->updates()) {
2196 Visitor->AddStmt(E);
2198 for (const auto *E : C->finals()) {
2199 Visitor->AddStmt(E);
2201 Visitor->AddStmt(C->getStep());
2202 Visitor->AddStmt(C->getCalcStep());
2204 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2205 VisitOMPClauseList(C);
2206 Visitor->AddStmt(C->getAlignment());
2208 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2209 VisitOMPClauseList(C);
2210 for (auto *E : C->source_exprs()) {
2211 Visitor->AddStmt(E);
2213 for (auto *E : C->destination_exprs()) {
2214 Visitor->AddStmt(E);
2216 for (auto *E : C->assignment_ops()) {
2217 Visitor->AddStmt(E);
2221 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2222 VisitOMPClauseList(C);
2223 for (auto *E : C->source_exprs()) {
2224 Visitor->AddStmt(E);
2226 for (auto *E : C->destination_exprs()) {
2227 Visitor->AddStmt(E);
2229 for (auto *E : C->assignment_ops()) {
2230 Visitor->AddStmt(E);
2233 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2234 VisitOMPClauseList(C);
2236 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2237 VisitOMPClauseList(C);
2239 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2240 VisitOMPClauseList(C);
2242 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2243 const OMPDistScheduleClause *C) {
2244 VisitOMPClauseWithPreInit(C);
2245 Visitor->AddStmt(C->getChunkSize());
2247 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2248 const OMPDefaultmapClause * /*C*/) {}
2249 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2250 VisitOMPClauseList(C);
2252 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2253 VisitOMPClauseList(C);
2257 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2258 unsigned size = WL.size();
2259 OMPClauseEnqueue Visitor(this);
2261 if (size == WL.size())
2263 // Now reverse the entries we just added. This will match the DFS
2264 // ordering performed by the worklist.
2265 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2268 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2269 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2271 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2272 AddDecl(B->getBlockDecl());
2274 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2276 AddTypeLoc(E->getTypeSourceInfo());
2278 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2279 for (auto &I : llvm::reverse(S->body()))
2282 void EnqueueVisitor::
2283 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2284 AddStmt(S->getSubStmt());
2285 AddDeclarationNameInfo(S);
2286 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2287 AddNestedNameSpecifierLoc(QualifierLoc);
2290 void EnqueueVisitor::
2291 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2292 if (E->hasExplicitTemplateArgs())
2293 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2294 AddDeclarationNameInfo(E);
2295 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2296 AddNestedNameSpecifierLoc(QualifierLoc);
2297 if (!E->isImplicitAccess())
2298 AddStmt(E->getBase());
2300 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2301 // Enqueue the initializer , if any.
2302 AddStmt(E->getInitializer());
2303 // Enqueue the array size, if any.
2304 AddStmt(E->getArraySize());
2305 // Enqueue the allocated type.
2306 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2307 // Enqueue the placement arguments.
2308 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2309 AddStmt(E->getPlacementArg(I-1));
2311 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2312 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2313 AddStmt(CE->getArg(I-1));
2314 AddStmt(CE->getCallee());
2315 AddStmt(CE->getArg(0));
2317 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2318 const CXXPseudoDestructorExpr *E) {
2319 // Visit the name of the type being destroyed.
2320 AddTypeLoc(E->getDestroyedTypeInfo());
2321 // Visit the scope type that looks disturbingly like the nested-name-specifier
2323 AddTypeLoc(E->getScopeTypeInfo());
2324 // Visit the nested-name-specifier.
2325 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2326 AddNestedNameSpecifierLoc(QualifierLoc);
2327 // Visit base expression.
2328 AddStmt(E->getBase());
2330 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2331 const CXXScalarValueInitExpr *E) {
2332 AddTypeLoc(E->getTypeSourceInfo());
2334 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2335 const CXXTemporaryObjectExpr *E) {
2337 AddTypeLoc(E->getTypeSourceInfo());
2339 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2341 if (E->isTypeOperand())
2342 AddTypeLoc(E->getTypeOperandSourceInfo());
2345 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2346 const CXXUnresolvedConstructExpr *E) {
2348 AddTypeLoc(E->getTypeSourceInfo());
2350 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2352 if (E->isTypeOperand())
2353 AddTypeLoc(E->getTypeOperandSourceInfo());
2356 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2358 AddDecl(S->getExceptionDecl());
2361 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2362 AddStmt(S->getBody());
2363 AddStmt(S->getRangeInit());
2364 AddDecl(S->getLoopVariable());
2367 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2368 if (DR->hasExplicitTemplateArgs())
2369 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2370 WL.push_back(DeclRefExprParts(DR, Parent));
2372 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2373 const DependentScopeDeclRefExpr *E) {
2374 if (E->hasExplicitTemplateArgs())
2375 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2376 AddDeclarationNameInfo(E);
2377 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2379 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2380 unsigned size = WL.size();
2381 bool isFirst = true;
2382 for (const auto *D : S->decls()) {
2383 AddDecl(D, isFirst);
2386 if (size == WL.size())
2388 // Now reverse the entries we just added. This will match the DFS
2389 // ordering performed by the worklist.
2390 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2393 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2394 AddStmt(E->getInit());
2395 for (DesignatedInitExpr::const_reverse_designators_iterator
2396 D = E->designators_rbegin(), DEnd = E->designators_rend();
2398 if (D->isFieldDesignator()) {
2399 if (FieldDecl *Field = D->getField())
2400 AddMemberRef(Field, D->getFieldLoc());
2403 if (D->isArrayDesignator()) {
2404 AddStmt(E->getArrayIndex(*D));
2407 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2408 AddStmt(E->getArrayRangeEnd(*D));
2409 AddStmt(E->getArrayRangeStart(*D));
2412 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2414 AddTypeLoc(E->getTypeInfoAsWritten());
2416 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2417 AddStmt(FS->getBody());
2418 AddStmt(FS->getInc());
2419 AddStmt(FS->getCond());
2420 AddDecl(FS->getConditionVariable());
2421 AddStmt(FS->getInit());
2423 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2424 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2426 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2427 AddStmt(If->getElse());
2428 AddStmt(If->getThen());
2429 AddStmt(If->getCond());
2430 AddDecl(If->getConditionVariable());
2432 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2433 // We care about the syntactic form of the initializer list, only.
2434 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2436 EnqueueChildren(IE);
2438 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2439 WL.push_back(MemberExprParts(M, Parent));
2441 // If the base of the member access expression is an implicit 'this', don't
2443 // FIXME: If we ever want to show these implicit accesses, this will be
2444 // unfortunate. However, clang_getCursor() relies on this behavior.
2445 if (M->isImplicitAccess())
2448 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2449 // real field that that we are interested in.
2450 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2451 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2452 if (FD->isAnonymousStructOrUnion()) {
2453 AddStmt(SubME->getBase());
2459 AddStmt(M->getBase());
2461 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2462 AddTypeLoc(E->getEncodedTypeSourceInfo());
2464 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2466 AddTypeLoc(M->getClassReceiverTypeInfo());
2468 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2469 // Visit the components of the offsetof expression.
2470 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2471 const OffsetOfNode &Node = E->getComponent(I-1);
2472 switch (Node.getKind()) {
2473 case OffsetOfNode::Array:
2474 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2476 case OffsetOfNode::Field:
2477 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2479 case OffsetOfNode::Identifier:
2480 case OffsetOfNode::Base:
2484 // Visit the type into which we're computing the offset.
2485 AddTypeLoc(E->getTypeSourceInfo());
2487 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2488 if (E->hasExplicitTemplateArgs())
2489 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2490 WL.push_back(OverloadExprParts(E, Parent));
2492 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2493 const UnaryExprOrTypeTraitExpr *E) {
2495 if (E->isArgumentType())
2496 AddTypeLoc(E->getArgumentTypeInfo());
2498 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2501 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2502 AddStmt(S->getBody());
2503 AddStmt(S->getCond());
2504 AddDecl(S->getConditionVariable());
2507 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2508 AddStmt(W->getBody());
2509 AddStmt(W->getCond());
2510 AddDecl(W->getConditionVariable());
2513 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2514 for (unsigned I = E->getNumArgs(); I > 0; --I)
2515 AddTypeLoc(E->getArg(I-1));
2518 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2519 AddTypeLoc(E->getQueriedTypeSourceInfo());
2522 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2526 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2527 VisitOverloadExpr(U);
2528 if (!U->isImplicitAccess())
2529 AddStmt(U->getBase());
2531 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2532 AddStmt(E->getSubExpr());
2533 AddTypeLoc(E->getWrittenTypeInfo());
2535 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2536 WL.push_back(SizeOfPackExprParts(E, Parent));
2538 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2539 // If the opaque value has a source expression, just transparently
2540 // visit that. This is useful for (e.g.) pseudo-object expressions.
2541 if (Expr *SourceExpr = E->getSourceExpr())
2542 return Visit(SourceExpr);
2544 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2545 AddStmt(E->getBody());
2546 WL.push_back(LambdaExprParts(E, Parent));
2548 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2549 // Treat the expression like its syntactic form.
2550 Visit(E->getSyntacticForm());
2553 void EnqueueVisitor::VisitOMPExecutableDirective(
2554 const OMPExecutableDirective *D) {
2556 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2557 E = D->clauses().end();
2559 EnqueueChildren(*I);
2562 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2563 VisitOMPExecutableDirective(D);
2566 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2567 VisitOMPExecutableDirective(D);
2570 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2571 VisitOMPLoopDirective(D);
2574 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2575 VisitOMPLoopDirective(D);
2578 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2579 VisitOMPLoopDirective(D);
2582 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2583 VisitOMPExecutableDirective(D);
2586 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2587 VisitOMPExecutableDirective(D);
2590 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2591 VisitOMPExecutableDirective(D);
2594 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2595 VisitOMPExecutableDirective(D);
2598 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2599 VisitOMPExecutableDirective(D);
2600 AddDeclarationNameInfo(D);
2604 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2605 VisitOMPLoopDirective(D);
2608 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2609 const OMPParallelForSimdDirective *D) {
2610 VisitOMPLoopDirective(D);
2613 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2614 const OMPParallelSectionsDirective *D) {
2615 VisitOMPExecutableDirective(D);
2618 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2619 VisitOMPExecutableDirective(D);
2623 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2624 VisitOMPExecutableDirective(D);
2627 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2628 VisitOMPExecutableDirective(D);
2631 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2632 VisitOMPExecutableDirective(D);
2635 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2636 const OMPTaskgroupDirective *D) {
2637 VisitOMPExecutableDirective(D);
2640 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2641 VisitOMPExecutableDirective(D);
2644 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2645 VisitOMPExecutableDirective(D);
2648 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2649 VisitOMPExecutableDirective(D);
2652 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2653 VisitOMPExecutableDirective(D);
2656 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2657 OMPTargetDataDirective *D) {
2658 VisitOMPExecutableDirective(D);
2661 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2662 const OMPTargetEnterDataDirective *D) {
2663 VisitOMPExecutableDirective(D);
2666 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2667 const OMPTargetExitDataDirective *D) {
2668 VisitOMPExecutableDirective(D);
2671 void EnqueueVisitor::VisitOMPTargetParallelDirective(
2672 const OMPTargetParallelDirective *D) {
2673 VisitOMPExecutableDirective(D);
2676 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2677 const OMPTargetParallelForDirective *D) {
2678 VisitOMPLoopDirective(D);
2681 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2682 VisitOMPExecutableDirective(D);
2685 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2686 const OMPCancellationPointDirective *D) {
2687 VisitOMPExecutableDirective(D);
2690 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2691 VisitOMPExecutableDirective(D);
2694 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2695 VisitOMPLoopDirective(D);
2698 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2699 const OMPTaskLoopSimdDirective *D) {
2700 VisitOMPLoopDirective(D);
2703 void EnqueueVisitor::VisitOMPDistributeDirective(
2704 const OMPDistributeDirective *D) {
2705 VisitOMPLoopDirective(D);
2708 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2709 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2712 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2713 if (RegionOfInterest.isValid()) {
2714 SourceRange Range = getRawCursorExtent(C);
2715 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2721 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2722 while (!WL.empty()) {
2723 // Dequeue the worklist item.
2724 VisitorJob LI = WL.pop_back_val();
2726 // Set the Parent field, then back to its old value once we're done.
2727 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2729 switch (LI.getKind()) {
2730 case VisitorJob::DeclVisitKind: {
2731 const Decl *D = cast<DeclVisit>(&LI)->get();
2735 // For now, perform default visitation for Decls.
2736 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2737 cast<DeclVisit>(&LI)->isFirst())))
2742 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2743 for (const TemplateArgumentLoc &Arg :
2744 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2745 if (VisitTemplateArgumentLoc(Arg))
2750 case VisitorJob::TypeLocVisitKind: {
2751 // Perform default visitation for TypeLocs.
2752 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2756 case VisitorJob::LabelRefVisitKind: {
2757 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2758 if (LabelStmt *stmt = LS->getStmt()) {
2759 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2767 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2768 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2769 if (VisitNestedNameSpecifierLoc(V->get()))
2774 case VisitorJob::DeclarationNameInfoVisitKind: {
2775 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2780 case VisitorJob::MemberRefVisitKind: {
2781 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2782 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2786 case VisitorJob::StmtVisitKind: {
2787 const Stmt *S = cast<StmtVisit>(&LI)->get();
2791 // Update the current cursor.
2792 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2793 if (!IsInRegionOfInterest(Cursor))
2795 switch (Visitor(Cursor, Parent, ClientData)) {
2796 case CXChildVisit_Break: return true;
2797 case CXChildVisit_Continue: break;
2798 case CXChildVisit_Recurse:
2799 if (PostChildrenVisitor)
2800 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2801 EnqueueWorkList(WL, S);
2806 case VisitorJob::MemberExprPartsKind: {
2807 // Handle the other pieces in the MemberExpr besides the base.
2808 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2810 // Visit the nested-name-specifier
2811 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2812 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2815 // Visit the declaration name.
2816 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2819 // Visit the explicitly-specified template arguments, if any.
2820 if (M->hasExplicitTemplateArgs()) {
2821 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2822 *ArgEnd = Arg + M->getNumTemplateArgs();
2823 Arg != ArgEnd; ++Arg) {
2824 if (VisitTemplateArgumentLoc(*Arg))
2830 case VisitorJob::DeclRefExprPartsKind: {
2831 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2832 // Visit nested-name-specifier, if present.
2833 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2834 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2836 // Visit declaration name.
2837 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2841 case VisitorJob::OverloadExprPartsKind: {
2842 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2843 // Visit the nested-name-specifier.
2844 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2845 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2847 // Visit the declaration name.
2848 if (VisitDeclarationNameInfo(O->getNameInfo()))
2850 // Visit the overloaded declaration reference.
2851 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2855 case VisitorJob::SizeOfPackExprPartsKind: {
2856 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2857 NamedDecl *Pack = E->getPack();
2858 if (isa<TemplateTypeParmDecl>(Pack)) {
2859 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2860 E->getPackLoc(), TU)))
2866 if (isa<TemplateTemplateParmDecl>(Pack)) {
2867 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2868 E->getPackLoc(), TU)))
2874 // Non-type template parameter packs and function parameter packs are
2875 // treated like DeclRefExpr cursors.
2879 case VisitorJob::LambdaExprPartsKind: {
2881 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2882 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2883 CEnd = E->explicit_capture_end();
2885 // FIXME: Lambda init-captures.
2886 if (!C->capturesVariable())
2889 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2895 // Visit parameters and return type, if present.
2896 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2897 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2898 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2899 // Visit the whole type.
2902 } else if (FunctionProtoTypeLoc Proto =
2903 TL.getAs<FunctionProtoTypeLoc>()) {
2904 if (E->hasExplicitParameters()) {
2905 // Visit parameters.
2906 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2907 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2910 // Visit result type.
2911 if (Visit(Proto.getReturnLoc()))
2919 case VisitorJob::PostChildrenVisitKind:
2920 if (PostChildrenVisitor(Parent, ClientData))
2928 bool CursorVisitor::Visit(const Stmt *S) {
2929 VisitorWorkList *WL = nullptr;
2930 if (!WorkListFreeList.empty()) {
2931 WL = WorkListFreeList.back();
2933 WorkListFreeList.pop_back();
2936 WL = new VisitorWorkList();
2937 WorkListCache.push_back(WL);
2939 EnqueueWorkList(*WL, S);
2940 bool result = RunVisitorWorkList(*WL);
2941 WorkListFreeList.push_back(WL);
2946 typedef SmallVector<SourceRange, 4> RefNamePieces;
2947 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2948 const DeclarationNameInfo &NI, SourceRange QLoc,
2949 const SourceRange *TemplateArgsLoc = nullptr) {
2950 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2951 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2952 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2954 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2956 RefNamePieces Pieces;
2958 if (WantQualifier && QLoc.isValid())
2959 Pieces.push_back(QLoc);
2961 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2962 Pieces.push_back(NI.getLoc());
2964 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
2965 Pieces.push_back(*TemplateArgsLoc);
2967 if (Kind == DeclarationName::CXXOperatorName) {
2968 Pieces.push_back(SourceLocation::getFromRawEncoding(
2969 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2970 Pieces.push_back(SourceLocation::getFromRawEncoding(
2971 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2974 if (WantSinglePiece) {
2975 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2977 Pieces.push_back(R);
2984 //===----------------------------------------------------------------------===//
2986 //===----------------------------------------------------------------------===//
2988 static void fatal_error_handler(void *user_data, const std::string& reason,
2989 bool gen_crash_diag) {
2990 // Write the result out to stderr avoiding errs() because raw_ostreams can
2991 // call report_fatal_error.
2992 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2997 struct RegisterFatalErrorHandler {
2998 RegisterFatalErrorHandler() {
2999 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3004 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3007 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3008 int displayDiagnostics) {
3009 // We use crash recovery to make some of our APIs more reliable, implicitly
3011 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3012 llvm::CrashRecoveryContext::Enable();
3014 // Look through the managed static to trigger construction of the managed
3015 // static which registers our fatal error handler. This ensures it is only
3017 (void)*RegisterFatalErrorHandlerOnce;
3019 // Initialize targets for clang module support.
3020 llvm::InitializeAllTargets();
3021 llvm::InitializeAllTargetMCs();
3022 llvm::InitializeAllAsmPrinters();
3023 llvm::InitializeAllAsmParsers();
3025 CIndexer *CIdxr = new CIndexer();
3027 if (excludeDeclarationsFromPCH)
3028 CIdxr->setOnlyLocalDecls();
3029 if (displayDiagnostics)
3030 CIdxr->setDisplayDiagnostics();
3032 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3033 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3034 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3035 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3036 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3037 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3042 void clang_disposeIndex(CXIndex CIdx) {
3044 delete static_cast<CIndexer *>(CIdx);
3047 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3049 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3052 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3054 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3058 void clang_toggleCrashRecovery(unsigned isEnabled) {
3060 llvm::CrashRecoveryContext::Enable();
3062 llvm::CrashRecoveryContext::Disable();
3065 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3066 const char *ast_filename) {
3067 CXTranslationUnit TU;
3068 enum CXErrorCode Result =
3069 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3071 assert((TU && Result == CXError_Success) ||
3072 (!TU && Result != CXError_Success));
3076 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3077 const char *ast_filename,
3078 CXTranslationUnit *out_TU) {
3082 if (!CIdx || !ast_filename || !out_TU)
3083 return CXError_InvalidArguments;
3086 *Log << ast_filename;
3089 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3090 FileSystemOptions FileSystemOpts;
3092 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3093 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3094 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3095 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
3096 FileSystemOpts, /*UseDebugInfo=*/false,
3097 CXXIdx->getOnlyLocalDecls(), None,
3098 /*CaptureDiagnostics=*/true,
3099 /*AllowPCHWithCompilerErrors=*/true,
3100 /*UserFilesAreVolatile=*/true);
3101 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
3102 return *out_TU ? CXError_Success : CXError_Failure;
3105 unsigned clang_defaultEditingTranslationUnitOptions() {
3106 return CXTranslationUnit_PrecompiledPreamble |
3107 CXTranslationUnit_CacheCompletionResults;
3111 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3112 const char *source_filename,
3113 int num_command_line_args,
3114 const char * const *command_line_args,
3115 unsigned num_unsaved_files,
3116 struct CXUnsavedFile *unsaved_files) {
3117 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3118 return clang_parseTranslationUnit(CIdx, source_filename,
3119 command_line_args, num_command_line_args,
3120 unsaved_files, num_unsaved_files,
3125 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3126 const char *const *command_line_args,
3127 int num_command_line_args,
3128 ArrayRef<CXUnsavedFile> unsaved_files,
3129 unsigned options, CXTranslationUnit *out_TU) {
3130 // Set up the initial return values.
3135 if (!CIdx || !out_TU)
3136 return CXError_InvalidArguments;
3138 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3140 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3141 setThreadBackgroundPriority();
3143 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3144 bool CreatePreambleOnFirstParse =
3145 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3146 // FIXME: Add a flag for modules.
3147 TranslationUnitKind TUKind
3148 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3149 bool CacheCodeCompletionResults
3150 = options & CXTranslationUnit_CacheCompletionResults;
3151 bool IncludeBriefCommentsInCodeCompletion
3152 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3153 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3154 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3156 // Configure the diagnostics.
3157 IntrusiveRefCntPtr<DiagnosticsEngine>
3158 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3160 if (options & CXTranslationUnit_KeepGoing)
3161 Diags->setFatalsAsError(true);
3163 // Recover resources if we crash before exiting this function.
3164 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3165 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3166 DiagCleanup(Diags.get());
3168 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3169 new std::vector<ASTUnit::RemappedFile>());
3171 // Recover resources if we crash before exiting this function.
3172 llvm::CrashRecoveryContextCleanupRegistrar<
3173 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3175 for (auto &UF : unsaved_files) {
3176 std::unique_ptr<llvm::MemoryBuffer> MB =
3177 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3178 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3181 std::unique_ptr<std::vector<const char *>> Args(
3182 new std::vector<const char *>());
3184 // Recover resources if we crash before exiting this method.
3185 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3186 ArgsCleanup(Args.get());
3188 // Since the Clang C library is primarily used by batch tools dealing with
3189 // (often very broken) source code, where spell-checking can have a
3190 // significant negative impact on performance (particularly when
3191 // precompiled headers are involved), we disable it by default.
3192 // Only do this if we haven't found a spell-checking-related argument.
3193 bool FoundSpellCheckingArgument = false;
3194 for (int I = 0; I != num_command_line_args; ++I) {
3195 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3196 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3197 FoundSpellCheckingArgument = true;
3201 Args->insert(Args->end(), command_line_args,
3202 command_line_args + num_command_line_args);
3204 if (!FoundSpellCheckingArgument)
3205 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3207 // The 'source_filename' argument is optional. If the caller does not
3208 // specify it then it is assumed that the source file is specified
3209 // in the actual argument list.
3210 // Put the source file after command_line_args otherwise if '-x' flag is
3211 // present it will be unused.
3212 if (source_filename)
3213 Args->push_back(source_filename);
3215 // Do we need the detailed preprocessing record?
3216 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3217 Args->push_back("-Xclang");
3218 Args->push_back("-detailed-preprocessing-record");
3221 unsigned NumErrors = Diags->getClient()->getNumErrors();
3222 std::unique_ptr<ASTUnit> ErrUnit;
3223 // Unless the user specified that they want the preamble on the first parse
3224 // set it up to be created on the first reparse. This makes the first parse
3225 // faster, trading for a slower (first) reparse.
3226 unsigned PrecompilePreambleAfterNParses =
3227 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3228 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3229 Args->data(), Args->data() + Args->size(),
3230 CXXIdx->getPCHContainerOperations(), Diags,
3231 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3232 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3233 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3234 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3235 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3236 /*UserFilesAreVolatile=*/true, ForSerialization,
3237 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3240 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3241 if (!Unit && !ErrUnit)
3242 return CXError_ASTReadError;
3244 if (NumErrors != Diags->getClient()->getNumErrors()) {
3245 // Make sure to check that 'Unit' is non-NULL.
3246 if (CXXIdx->getDisplayDiagnostics())
3247 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3250 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3251 return CXError_ASTReadError;
3253 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3254 return *out_TU ? CXError_Success : CXError_Failure;
3258 clang_parseTranslationUnit(CXIndex CIdx,
3259 const char *source_filename,
3260 const char *const *command_line_args,
3261 int num_command_line_args,
3262 struct CXUnsavedFile *unsaved_files,
3263 unsigned num_unsaved_files,
3265 CXTranslationUnit TU;
3266 enum CXErrorCode Result = clang_parseTranslationUnit2(
3267 CIdx, source_filename, command_line_args, num_command_line_args,
3268 unsaved_files, num_unsaved_files, options, &TU);
3270 assert((TU && Result == CXError_Success) ||
3271 (!TU && Result != CXError_Success));
3275 enum CXErrorCode clang_parseTranslationUnit2(
3276 CXIndex CIdx, const char *source_filename,
3277 const char *const *command_line_args, int num_command_line_args,
3278 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3279 unsigned options, CXTranslationUnit *out_TU) {
3280 SmallVector<const char *, 4> Args;
3281 Args.push_back("clang");
3282 Args.append(command_line_args, command_line_args + num_command_line_args);
3283 return clang_parseTranslationUnit2FullArgv(
3284 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3285 num_unsaved_files, options, out_TU);
3288 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3289 CXIndex CIdx, const char *source_filename,
3290 const char *const *command_line_args, int num_command_line_args,
3291 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3292 unsigned options, CXTranslationUnit *out_TU) {
3294 *Log << source_filename << ": ";
3295 for (int i = 0; i != num_command_line_args; ++i)
3296 *Log << command_line_args[i] << " ";
3299 if (num_unsaved_files && !unsaved_files)
3300 return CXError_InvalidArguments;
3302 CXErrorCode result = CXError_Failure;
3303 auto ParseTranslationUnitImpl = [=, &result] {
3304 result = clang_parseTranslationUnit_Impl(
3305 CIdx, source_filename, command_line_args, num_command_line_args,
3306 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3308 llvm::CrashRecoveryContext CRC;
3310 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3311 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3312 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3313 fprintf(stderr, " 'command_line_args' : [");
3314 for (int i = 0; i != num_command_line_args; ++i) {
3316 fprintf(stderr, ", ");
3317 fprintf(stderr, "'%s'", command_line_args[i]);
3319 fprintf(stderr, "],\n");
3320 fprintf(stderr, " 'unsaved_files' : [");
3321 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3323 fprintf(stderr, ", ");
3324 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3325 unsaved_files[i].Length);
3327 fprintf(stderr, "],\n");
3328 fprintf(stderr, " 'options' : %d,\n", options);
3329 fprintf(stderr, "}\n");
3331 return CXError_Crashed;
3332 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3333 if (CXTranslationUnit *TU = out_TU)
3334 PrintLibclangResourceUsage(*TU);
3340 CXString clang_Type_getObjCEncoding(CXType CT) {
3341 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3342 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3343 std::string encoding;
3344 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3347 return cxstring::createDup(encoding);
3350 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3351 if (C.kind == CXCursor_MacroDefinition) {
3352 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3353 return MDR->getName();
3354 } else if (C.kind == CXCursor_MacroExpansion) {
3355 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3356 return ME.getName();
3361 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3362 const IdentifierInfo *II = getMacroIdentifier(C);
3366 ASTUnit *ASTU = getCursorASTUnit(C);
3367 Preprocessor &PP = ASTU->getPreprocessor();
3368 if (const MacroInfo *MI = PP.getMacroInfo(II))
3369 return MI->isFunctionLike();
3373 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3374 const IdentifierInfo *II = getMacroIdentifier(C);
3378 ASTUnit *ASTU = getCursorASTUnit(C);
3379 Preprocessor &PP = ASTU->getPreprocessor();
3380 if (const MacroInfo *MI = PP.getMacroInfo(II))
3381 return MI->isBuiltinMacro();
3385 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3386 const Decl *D = getCursorDecl(C);
3387 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3391 return FD->isInlined();
3394 static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3395 if (callExpr->getNumArgs() != 1) {
3399 StringLiteral *S = nullptr;
3400 auto *arg = callExpr->getArg(0);
3401 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3402 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3403 auto *subExpr = I->getSubExprAsWritten();
3405 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3409 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3410 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3411 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3418 struct ExprEvalResult {
3419 CXEvalResultKind EvalType;
3426 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3427 EvalType != CXEval_Int) {
3428 delete EvalData.stringVal;
3433 void clang_EvalResult_dispose(CXEvalResult E) {
3434 delete static_cast<ExprEvalResult *>(E);
3437 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3439 return CXEval_UnExposed;
3441 return ((ExprEvalResult *)E)->EvalType;
3444 int clang_EvalResult_getAsInt(CXEvalResult E) {
3448 return ((ExprEvalResult *)E)->EvalData.intVal;
3451 double clang_EvalResult_getAsDouble(CXEvalResult E) {
3455 return ((ExprEvalResult *)E)->EvalData.floatVal;
3458 const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3462 return ((ExprEvalResult *)E)->EvalData.stringVal;
3465 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3466 Expr::EvalResult ER;
3467 ASTContext &ctx = getCursorContext(C);
3471 expr = expr->IgnoreParens();
3472 if (!expr->EvaluateAsRValue(ER, ctx))
3477 auto result = llvm::make_unique<ExprEvalResult>();
3478 result->EvalType = CXEval_UnExposed;
3480 if (ER.Val.isInt()) {
3481 result->EvalType = CXEval_Int;
3482 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3483 return result.release();
3486 if (ER.Val.isFloat()) {
3487 llvm::SmallVector<char, 100> Buffer;
3488 ER.Val.getFloat().toString(Buffer);
3489 std::string floatStr(Buffer.data(), Buffer.size());
3490 result->EvalType = CXEval_Float;
3492 llvm::APFloat apFloat = ER.Val.getFloat();
3493 apFloat.convert(llvm::APFloat::IEEEdouble,
3494 llvm::APFloat::rmNearestTiesToEven, &ignored);
3495 result->EvalData.floatVal = apFloat.convertToDouble();
3496 return result.release();
3499 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3500 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3501 auto *subExpr = I->getSubExprAsWritten();
3502 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3503 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3504 const StringLiteral *StrE = nullptr;
3505 const ObjCStringLiteral *ObjCExpr;
3506 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3509 StrE = ObjCExpr->getString();
3510 result->EvalType = CXEval_ObjCStrLiteral;
3512 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3513 result->EvalType = CXEval_StrLiteral;
3516 std::string strRef(StrE->getString().str());
3517 result->EvalData.stringVal = new char[strRef.size() + 1];
3518 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3520 result->EvalData.stringVal[strRef.size()] = '\0';
3521 return result.release();
3523 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3524 expr->getStmtClass() == Stmt::StringLiteralClass) {
3525 const StringLiteral *StrE = nullptr;
3526 const ObjCStringLiteral *ObjCExpr;
3527 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3530 StrE = ObjCExpr->getString();
3531 result->EvalType = CXEval_ObjCStrLiteral;
3533 StrE = cast<StringLiteral>(expr);
3534 result->EvalType = CXEval_StrLiteral;
3537 std::string strRef(StrE->getString().str());
3538 result->EvalData.stringVal = new char[strRef.size() + 1];
3539 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3540 result->EvalData.stringVal[strRef.size()] = '\0';
3541 return result.release();
3544 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3545 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3547 rettype = CC->getType();
3548 if (rettype.getAsString() == "CFStringRef" &&
3549 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3551 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3552 StringLiteral *S = getCFSTR_value(callExpr);
3554 std::string strLiteral(S->getString().str());
3555 result->EvalType = CXEval_CFStr;
3557 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3558 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3560 result->EvalData.stringVal[strLiteral.size()] = '\0';
3561 return result.release();
3565 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3566 callExpr = static_cast<CallExpr *>(expr);
3567 rettype = callExpr->getCallReturnType(ctx);
3569 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3572 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3573 if (callExpr->getNumArgs() == 1 &&
3574 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3576 } else if (rettype.getAsString() == "CFStringRef") {
3578 StringLiteral *S = getCFSTR_value(callExpr);
3580 std::string strLiteral(S->getString().str());
3581 result->EvalType = CXEval_CFStr;
3582 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3583 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3585 result->EvalData.stringVal[strLiteral.size()] = '\0';
3586 return result.release();
3589 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3590 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3591 ValueDecl *V = D->getDecl();
3592 if (V->getKind() == Decl::Function) {
3593 std::string strName = V->getNameAsString();
3594 result->EvalType = CXEval_Other;
3595 result->EvalData.stringVal = new char[strName.size() + 1];
3596 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3597 result->EvalData.stringVal[strName.size()] = '\0';
3598 return result.release();
3605 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3606 const Decl *D = getCursorDecl(C);
3608 const Expr *expr = nullptr;
3609 if (auto *Var = dyn_cast<VarDecl>(D)) {
3610 expr = Var->getInit();
3611 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3612 expr = Field->getInClassInitializer();
3615 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3616 evaluateExpr(const_cast<Expr *>(expr), C)));
3620 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3622 Expr *expr = nullptr;
3623 for (auto *bodyIterator : compoundStmt->body()) {
3624 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3629 return const_cast<CXEvalResult>(
3630 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3635 unsigned clang_Cursor_hasAttrs(CXCursor C) {
3636 const Decl *D = getCursorDecl(C);
3641 if (D->hasAttrs()) {
3647 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3648 return CXSaveTranslationUnit_None;
3651 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3652 const char *FileName,
3654 CIndexer *CXXIdx = TU->CIdx;
3655 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3656 setThreadBackgroundPriority();
3658 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3659 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3662 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3665 *Log << TU << ' ' << FileName;
3668 if (isNotUsableTU(TU)) {
3670 return CXSaveError_InvalidTU;
3673 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3674 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3675 if (!CXXUnit->hasSema())
3676 return CXSaveError_InvalidTU;
3679 auto SaveTranslationUnitImpl = [=, &result]() {
3680 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3683 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3684 getenv("LIBCLANG_NOTHREADS")) {
3685 SaveTranslationUnitImpl();
3687 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3688 PrintLibclangResourceUsage(TU);
3693 // We have an AST that has invalid nodes due to compiler errors.
3694 // Use a crash recovery thread for protection.
3696 llvm::CrashRecoveryContext CRC;
3698 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3699 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3700 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3701 fprintf(stderr, " 'options' : %d,\n", options);
3702 fprintf(stderr, "}\n");
3704 return CXSaveError_Unknown;
3706 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3707 PrintLibclangResourceUsage(TU);
3713 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3715 // If the translation unit has been marked as unsafe to free, just discard
3717 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3718 if (Unit && Unit->isUnsafeToFree())
3721 delete cxtu::getASTUnit(CTUnit);
3722 delete CTUnit->StringPool;
3723 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3724 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3725 delete CTUnit->CommentToXML;
3730 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3731 return CXReparse_None;
3735 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3736 ArrayRef<CXUnsavedFile> unsaved_files,
3739 if (isNotUsableTU(TU)) {
3741 return CXError_InvalidArguments;
3744 // Reset the associated diagnostics.
3745 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3746 TU->Diagnostics = nullptr;
3748 CIndexer *CXXIdx = TU->CIdx;
3749 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3750 setThreadBackgroundPriority();
3752 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3753 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3755 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3756 new std::vector<ASTUnit::RemappedFile>());
3758 // Recover resources if we crash before exiting this function.
3759 llvm::CrashRecoveryContextCleanupRegistrar<
3760 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3762 for (auto &UF : unsaved_files) {
3763 std::unique_ptr<llvm::MemoryBuffer> MB =
3764 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3765 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3768 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3769 *RemappedFiles.get()))
3770 return CXError_Success;
3771 if (isASTReadError(CXXUnit))
3772 return CXError_ASTReadError;
3773 return CXError_Failure;
3776 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3777 unsigned num_unsaved_files,
3778 struct CXUnsavedFile *unsaved_files,
3784 if (num_unsaved_files && !unsaved_files)
3785 return CXError_InvalidArguments;
3788 auto ReparseTranslationUnitImpl = [=, &result]() {
3789 result = clang_reparseTranslationUnit_Impl(
3790 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3793 if (getenv("LIBCLANG_NOTHREADS")) {
3794 ReparseTranslationUnitImpl();
3798 llvm::CrashRecoveryContext CRC;
3800 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3801 fprintf(stderr, "libclang: crash detected during reparsing\n");
3802 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3803 return CXError_Crashed;
3804 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3805 PrintLibclangResourceUsage(TU);
3811 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3812 if (isNotUsableTU(CTUnit)) {
3814 return cxstring::createEmpty();
3817 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3818 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3821 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3822 if (isNotUsableTU(TU)) {
3824 return clang_getNullCursor();
3827 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3828 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3831 } // end: extern "C"
3833 //===----------------------------------------------------------------------===//
3834 // CXFile Operations.
3835 //===----------------------------------------------------------------------===//
3838 CXString clang_getFileName(CXFile SFile) {
3840 return cxstring::createNull();
3842 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3843 return cxstring::createRef(FEnt->getName());
3846 time_t clang_getFileTime(CXFile SFile) {
3850 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3851 return FEnt->getModificationTime();
3854 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3855 if (isNotUsableTU(TU)) {
3860 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3862 FileManager &FMgr = CXXUnit->getFileManager();
3863 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3866 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3868 if (isNotUsableTU(TU)) {
3876 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3877 FileEntry *FEnt = static_cast<FileEntry *>(file);
3878 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3879 .isFileMultipleIncludeGuarded(FEnt);
3882 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3883 if (!file || !outID)
3886 FileEntry *FEnt = static_cast<FileEntry *>(file);
3887 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3888 outID->data[0] = ID.getDevice();
3889 outID->data[1] = ID.getFile();
3890 outID->data[2] = FEnt->getModificationTime();
3894 int clang_File_isEqual(CXFile file1, CXFile file2) {
3898 if (!file1 || !file2)
3901 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3902 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3903 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3906 } // end: extern "C"
3908 //===----------------------------------------------------------------------===//
3909 // CXCursor Operations.
3910 //===----------------------------------------------------------------------===//
3912 static const Decl *getDeclFromExpr(const Stmt *E) {
3913 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3914 return getDeclFromExpr(CE->getSubExpr());
3916 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3917 return RefExpr->getDecl();
3918 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3919 return ME->getMemberDecl();
3920 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3921 return RE->getDecl();
3922 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3923 if (PRE->isExplicitProperty())
3924 return PRE->getExplicitProperty();
3925 // It could be messaging both getter and setter as in:
3927 // in which case prefer to associate the setter since it is less obvious
3928 // from inspecting the source that the setter is going to get called.
3929 if (PRE->isMessagingSetter())
3930 return PRE->getImplicitPropertySetter();
3931 return PRE->getImplicitPropertyGetter();
3933 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3934 return getDeclFromExpr(POE->getSyntacticForm());
3935 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3936 if (Expr *Src = OVE->getSourceExpr())
3937 return getDeclFromExpr(Src);
3939 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3940 return getDeclFromExpr(CE->getCallee());
3941 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3942 if (!CE->isElidable())
3943 return CE->getConstructor();
3944 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3945 return OME->getMethodDecl();
3947 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3948 return PE->getProtocol();
3949 if (const SubstNonTypeTemplateParmPackExpr *NTTP
3950 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3951 return NTTP->getParameterPack();
3952 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3953 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3954 isa<ParmVarDecl>(SizeOfPack->getPack()))
3955 return SizeOfPack->getPack();
3960 static SourceLocation getLocationFromExpr(const Expr *E) {
3961 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3962 return getLocationFromExpr(CE->getSubExpr());
3964 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3965 return /*FIXME:*/Msg->getLeftLoc();
3966 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3967 return DRE->getLocation();
3968 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3969 return Member->getMemberLoc();
3970 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3971 return Ivar->getLocation();
3972 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3973 return SizeOfPack->getPackLoc();
3974 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3975 return PropRef->getLocation();
3977 return E->getLocStart();
3982 unsigned clang_visitChildren(CXCursor parent,
3983 CXCursorVisitor visitor,
3984 CXClientData client_data) {
3985 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3986 /*VisitPreprocessorLast=*/false);
3987 return CursorVis.VisitChildren(parent);
3990 #ifndef __has_feature
3991 #define __has_feature(x) 0
3993 #if __has_feature(blocks)
3994 typedef enum CXChildVisitResult
3995 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3997 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3998 CXClientData client_data) {
3999 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4000 return block(cursor, parent);
4003 // If we are compiled with a compiler that doesn't have native blocks support,
4004 // define and call the block manually, so the
4005 typedef struct _CXChildVisitResult
4010 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4012 } *CXCursorVisitorBlock;
4014 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4015 CXClientData client_data) {
4016 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4017 return block->invoke(block, cursor, parent);
4022 unsigned clang_visitChildrenWithBlock(CXCursor parent,
4023 CXCursorVisitorBlock block) {
4024 return clang_visitChildren(parent, visitWithBlock, block);
4027 static CXString getDeclSpelling(const Decl *D) {
4029 return cxstring::createEmpty();
4031 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4033 if (const ObjCPropertyImplDecl *PropImpl =
4034 dyn_cast<ObjCPropertyImplDecl>(D))
4035 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4036 return cxstring::createDup(Property->getIdentifier()->getName());
4038 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4039 if (Module *Mod = ImportD->getImportedModule())
4040 return cxstring::createDup(Mod->getFullModuleName());
4042 return cxstring::createEmpty();
4045 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4046 return cxstring::createDup(OMD->getSelector().getAsString());
4048 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4049 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4050 // and returns different names. NamedDecl returns the class name and
4051 // ObjCCategoryImplDecl returns the category name.
4052 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4054 if (isa<UsingDirectiveDecl>(D))
4055 return cxstring::createEmpty();
4057 SmallString<1024> S;
4058 llvm::raw_svector_ostream os(S);
4061 return cxstring::createDup(os.str());
4064 CXString clang_getCursorSpelling(CXCursor C) {
4065 if (clang_isTranslationUnit(C.kind))
4066 return clang_getTranslationUnitSpelling(getCursorTU(C));
4068 if (clang_isReference(C.kind)) {
4070 case CXCursor_ObjCSuperClassRef: {
4071 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4072 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4074 case CXCursor_ObjCClassRef: {
4075 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4076 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4078 case CXCursor_ObjCProtocolRef: {
4079 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4080 assert(OID && "getCursorSpelling(): Missing protocol decl");
4081 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4083 case CXCursor_CXXBaseSpecifier: {
4084 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4085 return cxstring::createDup(B->getType().getAsString());
4087 case CXCursor_TypeRef: {
4088 const TypeDecl *Type = getCursorTypeRef(C).first;
4089 assert(Type && "Missing type decl");
4091 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4094 case CXCursor_TemplateRef: {
4095 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4096 assert(Template && "Missing template decl");
4098 return cxstring::createDup(Template->getNameAsString());
4101 case CXCursor_NamespaceRef: {
4102 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4103 assert(NS && "Missing namespace decl");
4105 return cxstring::createDup(NS->getNameAsString());
4108 case CXCursor_MemberRef: {
4109 const FieldDecl *Field = getCursorMemberRef(C).first;
4110 assert(Field && "Missing member decl");
4112 return cxstring::createDup(Field->getNameAsString());
4115 case CXCursor_LabelRef: {
4116 const LabelStmt *Label = getCursorLabelRef(C).first;
4117 assert(Label && "Missing label");
4119 return cxstring::createRef(Label->getName());
4122 case CXCursor_OverloadedDeclRef: {
4123 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4124 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4125 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4126 return cxstring::createDup(ND->getNameAsString());
4127 return cxstring::createEmpty();
4129 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4130 return cxstring::createDup(E->getName().getAsString());
4131 OverloadedTemplateStorage *Ovl
4132 = Storage.get<OverloadedTemplateStorage*>();
4133 if (Ovl->size() == 0)
4134 return cxstring::createEmpty();
4135 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4138 case CXCursor_VariableRef: {
4139 const VarDecl *Var = getCursorVariableRef(C).first;
4140 assert(Var && "Missing variable decl");
4142 return cxstring::createDup(Var->getNameAsString());
4146 return cxstring::createRef("<not implemented>");
4150 if (clang_isExpression(C.kind)) {
4151 const Expr *E = getCursorExpr(C);
4153 if (C.kind == CXCursor_ObjCStringLiteral ||
4154 C.kind == CXCursor_StringLiteral) {
4155 const StringLiteral *SLit;
4156 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4157 SLit = OSL->getString();
4159 SLit = cast<StringLiteral>(E);
4161 SmallString<256> Buf;
4162 llvm::raw_svector_ostream OS(Buf);
4163 SLit->outputString(OS);
4164 return cxstring::createDup(OS.str());
4167 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4169 return getDeclSpelling(D);
4170 return cxstring::createEmpty();
4173 if (clang_isStatement(C.kind)) {
4174 const Stmt *S = getCursorStmt(C);
4175 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4176 return cxstring::createRef(Label->getName());
4178 return cxstring::createEmpty();
4181 if (C.kind == CXCursor_MacroExpansion)
4182 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4185 if (C.kind == CXCursor_MacroDefinition)
4186 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4189 if (C.kind == CXCursor_InclusionDirective)
4190 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4192 if (clang_isDeclaration(C.kind))
4193 return getDeclSpelling(getCursorDecl(C));
4195 if (C.kind == CXCursor_AnnotateAttr) {
4196 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4197 return cxstring::createDup(AA->getAnnotation());
4200 if (C.kind == CXCursor_AsmLabelAttr) {
4201 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4202 return cxstring::createDup(AA->getLabel());
4205 if (C.kind == CXCursor_PackedAttr) {
4206 return cxstring::createRef("packed");
4209 if (C.kind == CXCursor_VisibilityAttr) {
4210 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4211 switch (AA->getVisibility()) {
4212 case VisibilityAttr::VisibilityType::Default:
4213 return cxstring::createRef("default");
4214 case VisibilityAttr::VisibilityType::Hidden:
4215 return cxstring::createRef("hidden");
4216 case VisibilityAttr::VisibilityType::Protected:
4217 return cxstring::createRef("protected");
4219 llvm_unreachable("unknown visibility type");
4222 return cxstring::createEmpty();
4225 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4226 unsigned pieceIndex,
4228 if (clang_Cursor_isNull(C))
4229 return clang_getNullRange();
4231 ASTContext &Ctx = getCursorContext(C);
4233 if (clang_isStatement(C.kind)) {
4234 const Stmt *S = getCursorStmt(C);
4235 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4237 return clang_getNullRange();
4238 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4241 return clang_getNullRange();
4244 if (C.kind == CXCursor_ObjCMessageExpr) {
4245 if (const ObjCMessageExpr *
4246 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4247 if (pieceIndex >= ME->getNumSelectorLocs())
4248 return clang_getNullRange();
4249 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4253 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4254 C.kind == CXCursor_ObjCClassMethodDecl) {
4255 if (const ObjCMethodDecl *
4256 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4257 if (pieceIndex >= MD->getNumSelectorLocs())
4258 return clang_getNullRange();
4259 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4263 if (C.kind == CXCursor_ObjCCategoryDecl ||
4264 C.kind == CXCursor_ObjCCategoryImplDecl) {
4266 return clang_getNullRange();
4267 if (const ObjCCategoryDecl *
4268 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4269 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4270 if (const ObjCCategoryImplDecl *
4271 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4272 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4275 if (C.kind == CXCursor_ModuleImportDecl) {
4277 return clang_getNullRange();
4278 if (const ImportDecl *ImportD =
4279 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4280 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4282 return cxloc::translateSourceRange(Ctx,
4283 SourceRange(Locs.front(), Locs.back()));
4285 return clang_getNullRange();
4288 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4289 C.kind == CXCursor_ConversionFunction) {
4291 return clang_getNullRange();
4292 if (const FunctionDecl *FD =
4293 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4294 DeclarationNameInfo FunctionName = FD->getNameInfo();
4295 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4297 return clang_getNullRange();
4300 // FIXME: A CXCursor_InclusionDirective should give the location of the
4301 // filename, but we don't keep track of this.
4303 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4304 // but we don't keep track of this.
4306 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4307 // but we don't keep track of this.
4309 // Default handling, give the location of the cursor.
4312 return clang_getNullRange();
4314 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4315 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4316 return cxloc::translateSourceRange(Ctx, Loc);
4319 CXString clang_Cursor_getMangling(CXCursor C) {
4320 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4321 return cxstring::createEmpty();
4323 // Mangling only works for functions and variables.
4324 const Decl *D = getCursorDecl(C);
4325 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4326 return cxstring::createEmpty();
4328 ASTContext &Ctx = D->getASTContext();
4329 index::CodegenNameGenerator CGNameGen(Ctx);
4330 return cxstring::createDup(CGNameGen.getName(D));
4333 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4334 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4337 const Decl *D = getCursorDecl(C);
4338 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4341 ASTContext &Ctx = D->getASTContext();
4342 index::CodegenNameGenerator CGNameGen(Ctx);
4343 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4344 return cxstring::createSet(Manglings);
4347 CXString clang_getCursorDisplayName(CXCursor C) {
4348 if (!clang_isDeclaration(C.kind))
4349 return clang_getCursorSpelling(C);
4351 const Decl *D = getCursorDecl(C);
4353 return cxstring::createEmpty();
4355 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4356 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4357 D = FunTmpl->getTemplatedDecl();
4359 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4360 SmallString<64> Str;
4361 llvm::raw_svector_ostream OS(Str);
4363 if (Function->getPrimaryTemplate())
4366 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4369 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4372 if (Function->isVariadic()) {
4373 if (Function->getNumParams())
4378 return cxstring::createDup(OS.str());
4381 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4382 SmallString<64> Str;
4383 llvm::raw_svector_ostream OS(Str);
4384 OS << *ClassTemplate;
4386 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4387 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4391 NamedDecl *Param = Params->getParam(I);
4392 if (Param->getIdentifier()) {
4393 OS << Param->getIdentifier()->getName();
4397 // There is no parameter name, which makes this tricky. Try to come up
4398 // with something useful that isn't too long.
4399 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4400 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4401 else if (NonTypeTemplateParmDecl *NTTP
4402 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4403 OS << NTTP->getType().getAsString(Policy);
4405 OS << "template<...> class";
4409 return cxstring::createDup(OS.str());
4412 if (const ClassTemplateSpecializationDecl *ClassSpec
4413 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4414 // If the type was explicitly written, use that.
4415 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4416 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
4418 SmallString<128> Str;
4419 llvm::raw_svector_ostream OS(Str);
4421 TemplateSpecializationType::PrintTemplateArgumentList(OS,
4422 ClassSpec->getTemplateArgs().data(),
4423 ClassSpec->getTemplateArgs().size(),
4425 return cxstring::createDup(OS.str());
4428 return clang_getCursorSpelling(C);
4431 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4433 case CXCursor_FunctionDecl:
4434 return cxstring::createRef("FunctionDecl");
4435 case CXCursor_TypedefDecl:
4436 return cxstring::createRef("TypedefDecl");
4437 case CXCursor_EnumDecl:
4438 return cxstring::createRef("EnumDecl");
4439 case CXCursor_EnumConstantDecl:
4440 return cxstring::createRef("EnumConstantDecl");
4441 case CXCursor_StructDecl:
4442 return cxstring::createRef("StructDecl");
4443 case CXCursor_UnionDecl:
4444 return cxstring::createRef("UnionDecl");
4445 case CXCursor_ClassDecl:
4446 return cxstring::createRef("ClassDecl");
4447 case CXCursor_FieldDecl:
4448 return cxstring::createRef("FieldDecl");
4449 case CXCursor_VarDecl:
4450 return cxstring::createRef("VarDecl");
4451 case CXCursor_ParmDecl:
4452 return cxstring::createRef("ParmDecl");
4453 case CXCursor_ObjCInterfaceDecl:
4454 return cxstring::createRef("ObjCInterfaceDecl");
4455 case CXCursor_ObjCCategoryDecl:
4456 return cxstring::createRef("ObjCCategoryDecl");
4457 case CXCursor_ObjCProtocolDecl:
4458 return cxstring::createRef("ObjCProtocolDecl");
4459 case CXCursor_ObjCPropertyDecl:
4460 return cxstring::createRef("ObjCPropertyDecl");
4461 case CXCursor_ObjCIvarDecl:
4462 return cxstring::createRef("ObjCIvarDecl");
4463 case CXCursor_ObjCInstanceMethodDecl:
4464 return cxstring::createRef("ObjCInstanceMethodDecl");
4465 case CXCursor_ObjCClassMethodDecl:
4466 return cxstring::createRef("ObjCClassMethodDecl");
4467 case CXCursor_ObjCImplementationDecl:
4468 return cxstring::createRef("ObjCImplementationDecl");
4469 case CXCursor_ObjCCategoryImplDecl:
4470 return cxstring::createRef("ObjCCategoryImplDecl");
4471 case CXCursor_CXXMethod:
4472 return cxstring::createRef("CXXMethod");
4473 case CXCursor_UnexposedDecl:
4474 return cxstring::createRef("UnexposedDecl");
4475 case CXCursor_ObjCSuperClassRef:
4476 return cxstring::createRef("ObjCSuperClassRef");
4477 case CXCursor_ObjCProtocolRef:
4478 return cxstring::createRef("ObjCProtocolRef");
4479 case CXCursor_ObjCClassRef:
4480 return cxstring::createRef("ObjCClassRef");
4481 case CXCursor_TypeRef:
4482 return cxstring::createRef("TypeRef");
4483 case CXCursor_TemplateRef:
4484 return cxstring::createRef("TemplateRef");
4485 case CXCursor_NamespaceRef:
4486 return cxstring::createRef("NamespaceRef");
4487 case CXCursor_MemberRef:
4488 return cxstring::createRef("MemberRef");
4489 case CXCursor_LabelRef:
4490 return cxstring::createRef("LabelRef");
4491 case CXCursor_OverloadedDeclRef:
4492 return cxstring::createRef("OverloadedDeclRef");
4493 case CXCursor_VariableRef:
4494 return cxstring::createRef("VariableRef");
4495 case CXCursor_IntegerLiteral:
4496 return cxstring::createRef("IntegerLiteral");
4497 case CXCursor_FloatingLiteral:
4498 return cxstring::createRef("FloatingLiteral");
4499 case CXCursor_ImaginaryLiteral:
4500 return cxstring::createRef("ImaginaryLiteral");
4501 case CXCursor_StringLiteral:
4502 return cxstring::createRef("StringLiteral");
4503 case CXCursor_CharacterLiteral:
4504 return cxstring::createRef("CharacterLiteral");
4505 case CXCursor_ParenExpr:
4506 return cxstring::createRef("ParenExpr");
4507 case CXCursor_UnaryOperator:
4508 return cxstring::createRef("UnaryOperator");
4509 case CXCursor_ArraySubscriptExpr:
4510 return cxstring::createRef("ArraySubscriptExpr");
4511 case CXCursor_OMPArraySectionExpr:
4512 return cxstring::createRef("OMPArraySectionExpr");
4513 case CXCursor_BinaryOperator:
4514 return cxstring::createRef("BinaryOperator");
4515 case CXCursor_CompoundAssignOperator:
4516 return cxstring::createRef("CompoundAssignOperator");
4517 case CXCursor_ConditionalOperator:
4518 return cxstring::createRef("ConditionalOperator");
4519 case CXCursor_CStyleCastExpr:
4520 return cxstring::createRef("CStyleCastExpr");
4521 case CXCursor_CompoundLiteralExpr:
4522 return cxstring::createRef("CompoundLiteralExpr");
4523 case CXCursor_InitListExpr:
4524 return cxstring::createRef("InitListExpr");
4525 case CXCursor_AddrLabelExpr:
4526 return cxstring::createRef("AddrLabelExpr");
4527 case CXCursor_StmtExpr:
4528 return cxstring::createRef("StmtExpr");
4529 case CXCursor_GenericSelectionExpr:
4530 return cxstring::createRef("GenericSelectionExpr");
4531 case CXCursor_GNUNullExpr:
4532 return cxstring::createRef("GNUNullExpr");
4533 case CXCursor_CXXStaticCastExpr:
4534 return cxstring::createRef("CXXStaticCastExpr");
4535 case CXCursor_CXXDynamicCastExpr:
4536 return cxstring::createRef("CXXDynamicCastExpr");
4537 case CXCursor_CXXReinterpretCastExpr:
4538 return cxstring::createRef("CXXReinterpretCastExpr");
4539 case CXCursor_CXXConstCastExpr:
4540 return cxstring::createRef("CXXConstCastExpr");
4541 case CXCursor_CXXFunctionalCastExpr:
4542 return cxstring::createRef("CXXFunctionalCastExpr");
4543 case CXCursor_CXXTypeidExpr:
4544 return cxstring::createRef("CXXTypeidExpr");
4545 case CXCursor_CXXBoolLiteralExpr:
4546 return cxstring::createRef("CXXBoolLiteralExpr");
4547 case CXCursor_CXXNullPtrLiteralExpr:
4548 return cxstring::createRef("CXXNullPtrLiteralExpr");
4549 case CXCursor_CXXThisExpr:
4550 return cxstring::createRef("CXXThisExpr");
4551 case CXCursor_CXXThrowExpr:
4552 return cxstring::createRef("CXXThrowExpr");
4553 case CXCursor_CXXNewExpr:
4554 return cxstring::createRef("CXXNewExpr");
4555 case CXCursor_CXXDeleteExpr:
4556 return cxstring::createRef("CXXDeleteExpr");
4557 case CXCursor_UnaryExpr:
4558 return cxstring::createRef("UnaryExpr");
4559 case CXCursor_ObjCStringLiteral:
4560 return cxstring::createRef("ObjCStringLiteral");
4561 case CXCursor_ObjCBoolLiteralExpr:
4562 return cxstring::createRef("ObjCBoolLiteralExpr");
4563 case CXCursor_ObjCSelfExpr:
4564 return cxstring::createRef("ObjCSelfExpr");
4565 case CXCursor_ObjCEncodeExpr:
4566 return cxstring::createRef("ObjCEncodeExpr");
4567 case CXCursor_ObjCSelectorExpr:
4568 return cxstring::createRef("ObjCSelectorExpr");
4569 case CXCursor_ObjCProtocolExpr:
4570 return cxstring::createRef("ObjCProtocolExpr");
4571 case CXCursor_ObjCBridgedCastExpr:
4572 return cxstring::createRef("ObjCBridgedCastExpr");
4573 case CXCursor_BlockExpr:
4574 return cxstring::createRef("BlockExpr");
4575 case CXCursor_PackExpansionExpr:
4576 return cxstring::createRef("PackExpansionExpr");
4577 case CXCursor_SizeOfPackExpr:
4578 return cxstring::createRef("SizeOfPackExpr");
4579 case CXCursor_LambdaExpr:
4580 return cxstring::createRef("LambdaExpr");
4581 case CXCursor_UnexposedExpr:
4582 return cxstring::createRef("UnexposedExpr");
4583 case CXCursor_DeclRefExpr:
4584 return cxstring::createRef("DeclRefExpr");
4585 case CXCursor_MemberRefExpr:
4586 return cxstring::createRef("MemberRefExpr");
4587 case CXCursor_CallExpr:
4588 return cxstring::createRef("CallExpr");
4589 case CXCursor_ObjCMessageExpr:
4590 return cxstring::createRef("ObjCMessageExpr");
4591 case CXCursor_UnexposedStmt:
4592 return cxstring::createRef("UnexposedStmt");
4593 case CXCursor_DeclStmt:
4594 return cxstring::createRef("DeclStmt");
4595 case CXCursor_LabelStmt:
4596 return cxstring::createRef("LabelStmt");
4597 case CXCursor_CompoundStmt:
4598 return cxstring::createRef("CompoundStmt");
4599 case CXCursor_CaseStmt:
4600 return cxstring::createRef("CaseStmt");
4601 case CXCursor_DefaultStmt:
4602 return cxstring::createRef("DefaultStmt");
4603 case CXCursor_IfStmt:
4604 return cxstring::createRef("IfStmt");
4605 case CXCursor_SwitchStmt:
4606 return cxstring::createRef("SwitchStmt");
4607 case CXCursor_WhileStmt:
4608 return cxstring::createRef("WhileStmt");
4609 case CXCursor_DoStmt:
4610 return cxstring::createRef("DoStmt");
4611 case CXCursor_ForStmt:
4612 return cxstring::createRef("ForStmt");
4613 case CXCursor_GotoStmt:
4614 return cxstring::createRef("GotoStmt");
4615 case CXCursor_IndirectGotoStmt:
4616 return cxstring::createRef("IndirectGotoStmt");
4617 case CXCursor_ContinueStmt:
4618 return cxstring::createRef("ContinueStmt");
4619 case CXCursor_BreakStmt:
4620 return cxstring::createRef("BreakStmt");
4621 case CXCursor_ReturnStmt:
4622 return cxstring::createRef("ReturnStmt");
4623 case CXCursor_GCCAsmStmt:
4624 return cxstring::createRef("GCCAsmStmt");
4625 case CXCursor_MSAsmStmt:
4626 return cxstring::createRef("MSAsmStmt");
4627 case CXCursor_ObjCAtTryStmt:
4628 return cxstring::createRef("ObjCAtTryStmt");
4629 case CXCursor_ObjCAtCatchStmt:
4630 return cxstring::createRef("ObjCAtCatchStmt");
4631 case CXCursor_ObjCAtFinallyStmt:
4632 return cxstring::createRef("ObjCAtFinallyStmt");
4633 case CXCursor_ObjCAtThrowStmt:
4634 return cxstring::createRef("ObjCAtThrowStmt");
4635 case CXCursor_ObjCAtSynchronizedStmt:
4636 return cxstring::createRef("ObjCAtSynchronizedStmt");
4637 case CXCursor_ObjCAutoreleasePoolStmt:
4638 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4639 case CXCursor_ObjCForCollectionStmt:
4640 return cxstring::createRef("ObjCForCollectionStmt");
4641 case CXCursor_CXXCatchStmt:
4642 return cxstring::createRef("CXXCatchStmt");
4643 case CXCursor_CXXTryStmt:
4644 return cxstring::createRef("CXXTryStmt");
4645 case CXCursor_CXXForRangeStmt:
4646 return cxstring::createRef("CXXForRangeStmt");
4647 case CXCursor_SEHTryStmt:
4648 return cxstring::createRef("SEHTryStmt");
4649 case CXCursor_SEHExceptStmt:
4650 return cxstring::createRef("SEHExceptStmt");
4651 case CXCursor_SEHFinallyStmt:
4652 return cxstring::createRef("SEHFinallyStmt");
4653 case CXCursor_SEHLeaveStmt:
4654 return cxstring::createRef("SEHLeaveStmt");
4655 case CXCursor_NullStmt:
4656 return cxstring::createRef("NullStmt");
4657 case CXCursor_InvalidFile:
4658 return cxstring::createRef("InvalidFile");
4659 case CXCursor_InvalidCode:
4660 return cxstring::createRef("InvalidCode");
4661 case CXCursor_NoDeclFound:
4662 return cxstring::createRef("NoDeclFound");
4663 case CXCursor_NotImplemented:
4664 return cxstring::createRef("NotImplemented");
4665 case CXCursor_TranslationUnit:
4666 return cxstring::createRef("TranslationUnit");
4667 case CXCursor_UnexposedAttr:
4668 return cxstring::createRef("UnexposedAttr");
4669 case CXCursor_IBActionAttr:
4670 return cxstring::createRef("attribute(ibaction)");
4671 case CXCursor_IBOutletAttr:
4672 return cxstring::createRef("attribute(iboutlet)");
4673 case CXCursor_IBOutletCollectionAttr:
4674 return cxstring::createRef("attribute(iboutletcollection)");
4675 case CXCursor_CXXFinalAttr:
4676 return cxstring::createRef("attribute(final)");
4677 case CXCursor_CXXOverrideAttr:
4678 return cxstring::createRef("attribute(override)");
4679 case CXCursor_AnnotateAttr:
4680 return cxstring::createRef("attribute(annotate)");
4681 case CXCursor_AsmLabelAttr:
4682 return cxstring::createRef("asm label");
4683 case CXCursor_PackedAttr:
4684 return cxstring::createRef("attribute(packed)");
4685 case CXCursor_PureAttr:
4686 return cxstring::createRef("attribute(pure)");
4687 case CXCursor_ConstAttr:
4688 return cxstring::createRef("attribute(const)");
4689 case CXCursor_NoDuplicateAttr:
4690 return cxstring::createRef("attribute(noduplicate)");
4691 case CXCursor_CUDAConstantAttr:
4692 return cxstring::createRef("attribute(constant)");
4693 case CXCursor_CUDADeviceAttr:
4694 return cxstring::createRef("attribute(device)");
4695 case CXCursor_CUDAGlobalAttr:
4696 return cxstring::createRef("attribute(global)");
4697 case CXCursor_CUDAHostAttr:
4698 return cxstring::createRef("attribute(host)");
4699 case CXCursor_CUDASharedAttr:
4700 return cxstring::createRef("attribute(shared)");
4701 case CXCursor_VisibilityAttr:
4702 return cxstring::createRef("attribute(visibility)");
4703 case CXCursor_DLLExport:
4704 return cxstring::createRef("attribute(dllexport)");
4705 case CXCursor_DLLImport:
4706 return cxstring::createRef("attribute(dllimport)");
4707 case CXCursor_PreprocessingDirective:
4708 return cxstring::createRef("preprocessing directive");
4709 case CXCursor_MacroDefinition:
4710 return cxstring::createRef("macro definition");
4711 case CXCursor_MacroExpansion:
4712 return cxstring::createRef("macro expansion");
4713 case CXCursor_InclusionDirective:
4714 return cxstring::createRef("inclusion directive");
4715 case CXCursor_Namespace:
4716 return cxstring::createRef("Namespace");
4717 case CXCursor_LinkageSpec:
4718 return cxstring::createRef("LinkageSpec");
4719 case CXCursor_CXXBaseSpecifier:
4720 return cxstring::createRef("C++ base class specifier");
4721 case CXCursor_Constructor:
4722 return cxstring::createRef("CXXConstructor");
4723 case CXCursor_Destructor:
4724 return cxstring::createRef("CXXDestructor");
4725 case CXCursor_ConversionFunction:
4726 return cxstring::createRef("CXXConversion");
4727 case CXCursor_TemplateTypeParameter:
4728 return cxstring::createRef("TemplateTypeParameter");
4729 case CXCursor_NonTypeTemplateParameter:
4730 return cxstring::createRef("NonTypeTemplateParameter");
4731 case CXCursor_TemplateTemplateParameter:
4732 return cxstring::createRef("TemplateTemplateParameter");
4733 case CXCursor_FunctionTemplate:
4734 return cxstring::createRef("FunctionTemplate");
4735 case CXCursor_ClassTemplate:
4736 return cxstring::createRef("ClassTemplate");
4737 case CXCursor_ClassTemplatePartialSpecialization:
4738 return cxstring::createRef("ClassTemplatePartialSpecialization");
4739 case CXCursor_NamespaceAlias:
4740 return cxstring::createRef("NamespaceAlias");
4741 case CXCursor_UsingDirective:
4742 return cxstring::createRef("UsingDirective");
4743 case CXCursor_UsingDeclaration:
4744 return cxstring::createRef("UsingDeclaration");
4745 case CXCursor_TypeAliasDecl:
4746 return cxstring::createRef("TypeAliasDecl");
4747 case CXCursor_ObjCSynthesizeDecl:
4748 return cxstring::createRef("ObjCSynthesizeDecl");
4749 case CXCursor_ObjCDynamicDecl:
4750 return cxstring::createRef("ObjCDynamicDecl");
4751 case CXCursor_CXXAccessSpecifier:
4752 return cxstring::createRef("CXXAccessSpecifier");
4753 case CXCursor_ModuleImportDecl:
4754 return cxstring::createRef("ModuleImport");
4755 case CXCursor_OMPParallelDirective:
4756 return cxstring::createRef("OMPParallelDirective");
4757 case CXCursor_OMPSimdDirective:
4758 return cxstring::createRef("OMPSimdDirective");
4759 case CXCursor_OMPForDirective:
4760 return cxstring::createRef("OMPForDirective");
4761 case CXCursor_OMPForSimdDirective:
4762 return cxstring::createRef("OMPForSimdDirective");
4763 case CXCursor_OMPSectionsDirective:
4764 return cxstring::createRef("OMPSectionsDirective");
4765 case CXCursor_OMPSectionDirective:
4766 return cxstring::createRef("OMPSectionDirective");
4767 case CXCursor_OMPSingleDirective:
4768 return cxstring::createRef("OMPSingleDirective");
4769 case CXCursor_OMPMasterDirective:
4770 return cxstring::createRef("OMPMasterDirective");
4771 case CXCursor_OMPCriticalDirective:
4772 return cxstring::createRef("OMPCriticalDirective");
4773 case CXCursor_OMPParallelForDirective:
4774 return cxstring::createRef("OMPParallelForDirective");
4775 case CXCursor_OMPParallelForSimdDirective:
4776 return cxstring::createRef("OMPParallelForSimdDirective");
4777 case CXCursor_OMPParallelSectionsDirective:
4778 return cxstring::createRef("OMPParallelSectionsDirective");
4779 case CXCursor_OMPTaskDirective:
4780 return cxstring::createRef("OMPTaskDirective");
4781 case CXCursor_OMPTaskyieldDirective:
4782 return cxstring::createRef("OMPTaskyieldDirective");
4783 case CXCursor_OMPBarrierDirective:
4784 return cxstring::createRef("OMPBarrierDirective");
4785 case CXCursor_OMPTaskwaitDirective:
4786 return cxstring::createRef("OMPTaskwaitDirective");
4787 case CXCursor_OMPTaskgroupDirective:
4788 return cxstring::createRef("OMPTaskgroupDirective");
4789 case CXCursor_OMPFlushDirective:
4790 return cxstring::createRef("OMPFlushDirective");
4791 case CXCursor_OMPOrderedDirective:
4792 return cxstring::createRef("OMPOrderedDirective");
4793 case CXCursor_OMPAtomicDirective:
4794 return cxstring::createRef("OMPAtomicDirective");
4795 case CXCursor_OMPTargetDirective:
4796 return cxstring::createRef("OMPTargetDirective");
4797 case CXCursor_OMPTargetDataDirective:
4798 return cxstring::createRef("OMPTargetDataDirective");
4799 case CXCursor_OMPTargetEnterDataDirective:
4800 return cxstring::createRef("OMPTargetEnterDataDirective");
4801 case CXCursor_OMPTargetExitDataDirective:
4802 return cxstring::createRef("OMPTargetExitDataDirective");
4803 case CXCursor_OMPTargetParallelDirective:
4804 return cxstring::createRef("OMPTargetParallelDirective");
4805 case CXCursor_OMPTargetParallelForDirective:
4806 return cxstring::createRef("OMPTargetParallelForDirective");
4807 case CXCursor_OMPTargetUpdateDirective:
4808 return cxstring::createRef("OMPTargetUpdateDirective");
4809 case CXCursor_OMPTeamsDirective:
4810 return cxstring::createRef("OMPTeamsDirective");
4811 case CXCursor_OMPCancellationPointDirective:
4812 return cxstring::createRef("OMPCancellationPointDirective");
4813 case CXCursor_OMPCancelDirective:
4814 return cxstring::createRef("OMPCancelDirective");
4815 case CXCursor_OMPTaskLoopDirective:
4816 return cxstring::createRef("OMPTaskLoopDirective");
4817 case CXCursor_OMPTaskLoopSimdDirective:
4818 return cxstring::createRef("OMPTaskLoopSimdDirective");
4819 case CXCursor_OMPDistributeDirective:
4820 return cxstring::createRef("OMPDistributeDirective");
4821 case CXCursor_OverloadCandidate:
4822 return cxstring::createRef("OverloadCandidate");
4823 case CXCursor_TypeAliasTemplateDecl:
4824 return cxstring::createRef("TypeAliasTemplateDecl");
4827 llvm_unreachable("Unhandled CXCursorKind");
4830 struct GetCursorData {
4831 SourceLocation TokenBeginLoc;
4832 bool PointsAtMacroArgExpansion;
4833 bool VisitedObjCPropertyImplDecl;
4834 SourceLocation VisitedDeclaratorDeclStartLoc;
4835 CXCursor &BestCursor;
4837 GetCursorData(SourceManager &SM,
4838 SourceLocation tokenBegin, CXCursor &outputCursor)
4839 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4840 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4841 VisitedObjCPropertyImplDecl = false;
4845 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4847 CXClientData client_data) {
4848 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4849 CXCursor *BestCursor = &Data->BestCursor;
4851 // If we point inside a macro argument we should provide info of what the
4852 // token is so use the actual cursor, don't replace it with a macro expansion
4854 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4855 return CXChildVisit_Recurse;
4857 if (clang_isDeclaration(cursor.kind)) {
4858 // Avoid having the implicit methods override the property decls.
4859 if (const ObjCMethodDecl *MD
4860 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4861 if (MD->isImplicit())
4862 return CXChildVisit_Break;
4864 } else if (const ObjCInterfaceDecl *ID
4865 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4866 // Check that when we have multiple @class references in the same line,
4867 // that later ones do not override the previous ones.
4870 // source ranges for both start at '@', so 'Bar' will end up overriding
4871 // 'Foo' even though the cursor location was at 'Foo'.
4872 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4873 BestCursor->kind == CXCursor_ObjCClassRef)
4874 if (const ObjCInterfaceDecl *PrevID
4875 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4877 !PrevID->isThisDeclarationADefinition() &&
4878 !ID->isThisDeclarationADefinition())
4879 return CXChildVisit_Break;
4882 } else if (const DeclaratorDecl *DD
4883 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4884 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4885 // Check that when we have multiple declarators in the same line,
4886 // that later ones do not override the previous ones.
4889 // source ranges for both start at 'int', so 'Bar' will end up overriding
4890 // 'Foo' even though the cursor location was at 'Foo'.
4891 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4892 return CXChildVisit_Break;
4893 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4895 } else if (const ObjCPropertyImplDecl *PropImp
4896 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4898 // Check that when we have multiple @synthesize in the same line,
4899 // that later ones do not override the previous ones.
4901 // @synthesize Foo, Bar;
4902 // source ranges for both start at '@', so 'Bar' will end up overriding
4903 // 'Foo' even though the cursor location was at 'Foo'.
4904 if (Data->VisitedObjCPropertyImplDecl)
4905 return CXChildVisit_Break;
4906 Data->VisitedObjCPropertyImplDecl = true;
4910 if (clang_isExpression(cursor.kind) &&
4911 clang_isDeclaration(BestCursor->kind)) {
4912 if (const Decl *D = getCursorDecl(*BestCursor)) {
4913 // Avoid having the cursor of an expression replace the declaration cursor
4914 // when the expression source range overlaps the declaration range.
4915 // This can happen for C++ constructor expressions whose range generally
4916 // include the variable declaration, e.g.:
4917 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4918 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4919 D->getLocation() == Data->TokenBeginLoc)
4920 return CXChildVisit_Break;
4924 // If our current best cursor is the construction of a temporary object,
4925 // don't replace that cursor with a type reference, because we want
4926 // clang_getCursor() to point at the constructor.
4927 if (clang_isExpression(BestCursor->kind) &&
4928 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4929 cursor.kind == CXCursor_TypeRef) {
4930 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4931 // as having the actual point on the type reference.
4932 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4933 return CXChildVisit_Recurse;
4936 // If we already have an Objective-C superclass reference, don't
4937 // update it further.
4938 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4939 return CXChildVisit_Break;
4941 *BestCursor = cursor;
4942 return CXChildVisit_Recurse;
4945 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4946 if (isNotUsableTU(TU)) {
4948 return clang_getNullCursor();
4951 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4952 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4954 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4955 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4959 unsigned SearchLine, SearchColumn;
4961 unsigned ResultLine, ResultColumn;
4962 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4963 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4964 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4966 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4968 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4969 &ResultColumn, nullptr);
4970 SearchFileName = clang_getFileName(SearchFile);
4971 ResultFileName = clang_getFileName(ResultFile);
4972 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4973 USR = clang_getCursorUSR(Result);
4974 *Log << llvm::format("(%s:%d:%d) = %s",
4975 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4976 clang_getCString(KindSpelling))
4977 << llvm::format("(%s:%d:%d):%s%s",
4978 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4979 clang_getCString(USR), IsDef);
4980 clang_disposeString(SearchFileName);
4981 clang_disposeString(ResultFileName);
4982 clang_disposeString(KindSpelling);
4983 clang_disposeString(USR);
4985 CXCursor Definition = clang_getCursorDefinition(Result);
4986 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4987 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4988 CXString DefinitionKindSpelling
4989 = clang_getCursorKindSpelling(Definition.kind);
4990 CXFile DefinitionFile;
4991 unsigned DefinitionLine, DefinitionColumn;
4992 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
4993 &DefinitionLine, &DefinitionColumn, nullptr);
4994 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
4995 *Log << llvm::format(" -> %s(%s:%d:%d)",
4996 clang_getCString(DefinitionKindSpelling),
4997 clang_getCString(DefinitionFileName),
4998 DefinitionLine, DefinitionColumn);
4999 clang_disposeString(DefinitionFileName);
5000 clang_disposeString(DefinitionKindSpelling);
5007 CXCursor clang_getNullCursor(void) {
5008 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5011 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5012 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5013 // can't set consistently. For example, when visiting a DeclStmt we will set
5014 // it but we don't set it on the result of clang_getCursorDefinition for
5015 // a reference of the same declaration.
5016 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5017 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5018 // to provide that kind of info.
5019 if (clang_isDeclaration(X.kind))
5020 X.data[1] = nullptr;
5021 if (clang_isDeclaration(Y.kind))
5022 Y.data[1] = nullptr;
5027 unsigned clang_hashCursor(CXCursor C) {
5029 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5032 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5033 std::make_pair(C.kind, C.data[Index]));
5036 unsigned clang_isInvalid(enum CXCursorKind K) {
5037 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5040 unsigned clang_isDeclaration(enum CXCursorKind K) {
5041 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5042 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5045 unsigned clang_isReference(enum CXCursorKind K) {
5046 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5049 unsigned clang_isExpression(enum CXCursorKind K) {
5050 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5053 unsigned clang_isStatement(enum CXCursorKind K) {
5054 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5057 unsigned clang_isAttribute(enum CXCursorKind K) {
5058 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5061 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5062 return K == CXCursor_TranslationUnit;
5065 unsigned clang_isPreprocessing(enum CXCursorKind K) {
5066 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5069 unsigned clang_isUnexposed(enum CXCursorKind K) {
5071 case CXCursor_UnexposedDecl:
5072 case CXCursor_UnexposedExpr:
5073 case CXCursor_UnexposedStmt:
5074 case CXCursor_UnexposedAttr:
5081 CXCursorKind clang_getCursorKind(CXCursor C) {
5085 CXSourceLocation clang_getCursorLocation(CXCursor C) {
5086 if (clang_isReference(C.kind)) {
5088 case CXCursor_ObjCSuperClassRef: {
5089 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5090 = getCursorObjCSuperClassRef(C);
5091 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5094 case CXCursor_ObjCProtocolRef: {
5095 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5096 = getCursorObjCProtocolRef(C);
5097 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5100 case CXCursor_ObjCClassRef: {
5101 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5102 = getCursorObjCClassRef(C);
5103 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5106 case CXCursor_TypeRef: {
5107 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5108 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5111 case CXCursor_TemplateRef: {
5112 std::pair<const TemplateDecl *, SourceLocation> P =
5113 getCursorTemplateRef(C);
5114 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5117 case CXCursor_NamespaceRef: {
5118 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5119 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5122 case CXCursor_MemberRef: {
5123 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5124 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5127 case CXCursor_VariableRef: {
5128 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5129 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5132 case CXCursor_CXXBaseSpecifier: {
5133 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5135 return clang_getNullLocation();
5137 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5138 return cxloc::translateSourceLocation(getCursorContext(C),
5139 TSInfo->getTypeLoc().getBeginLoc());
5141 return cxloc::translateSourceLocation(getCursorContext(C),
5142 BaseSpec->getLocStart());
5145 case CXCursor_LabelRef: {
5146 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5147 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5150 case CXCursor_OverloadedDeclRef:
5151 return cxloc::translateSourceLocation(getCursorContext(C),
5152 getCursorOverloadedDeclRef(C).second);
5155 // FIXME: Need a way to enumerate all non-reference cases.
5156 llvm_unreachable("Missed a reference kind");
5160 if (clang_isExpression(C.kind))
5161 return cxloc::translateSourceLocation(getCursorContext(C),
5162 getLocationFromExpr(getCursorExpr(C)));
5164 if (clang_isStatement(C.kind))
5165 return cxloc::translateSourceLocation(getCursorContext(C),
5166 getCursorStmt(C)->getLocStart());
5168 if (C.kind == CXCursor_PreprocessingDirective) {
5169 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5170 return cxloc::translateSourceLocation(getCursorContext(C), L);
5173 if (C.kind == CXCursor_MacroExpansion) {
5175 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5176 return cxloc::translateSourceLocation(getCursorContext(C), L);
5179 if (C.kind == CXCursor_MacroDefinition) {
5180 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5181 return cxloc::translateSourceLocation(getCursorContext(C), L);
5184 if (C.kind == CXCursor_InclusionDirective) {
5186 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5187 return cxloc::translateSourceLocation(getCursorContext(C), L);
5190 if (clang_isAttribute(C.kind)) {
5192 = cxcursor::getCursorAttr(C)->getLocation();
5193 return cxloc::translateSourceLocation(getCursorContext(C), L);
5196 if (!clang_isDeclaration(C.kind))
5197 return clang_getNullLocation();
5199 const Decl *D = getCursorDecl(C);
5201 return clang_getNullLocation();
5203 SourceLocation Loc = D->getLocation();
5204 // FIXME: Multiple variables declared in a single declaration
5205 // currently lack the information needed to correctly determine their
5206 // ranges when accounting for the type-specifier. We use context
5207 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5208 // and if so, whether it is the first decl.
5209 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5210 if (!cxcursor::isFirstInDeclGroup(C))
5211 Loc = VD->getLocation();
5214 // For ObjC methods, give the start location of the method name.
5215 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5216 Loc = MD->getSelectorStartLoc();
5218 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5223 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5226 // Guard against an invalid SourceLocation, or we may assert in one
5227 // of the following calls.
5228 if (SLoc.isInvalid())
5229 return clang_getNullCursor();
5231 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5233 // Translate the given source location to make it point at the beginning of
5234 // the token under the cursor.
5235 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5236 CXXUnit->getASTContext().getLangOpts());
5238 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5239 if (SLoc.isValid()) {
5240 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5241 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5242 /*VisitPreprocessorLast=*/true,
5243 /*VisitIncludedEntities=*/false,
5244 SourceLocation(SLoc));
5245 CursorVis.visitFileRegion();
5251 static SourceRange getRawCursorExtent(CXCursor C) {
5252 if (clang_isReference(C.kind)) {
5254 case CXCursor_ObjCSuperClassRef:
5255 return getCursorObjCSuperClassRef(C).second;
5257 case CXCursor_ObjCProtocolRef:
5258 return getCursorObjCProtocolRef(C).second;
5260 case CXCursor_ObjCClassRef:
5261 return getCursorObjCClassRef(C).second;
5263 case CXCursor_TypeRef:
5264 return getCursorTypeRef(C).second;
5266 case CXCursor_TemplateRef:
5267 return getCursorTemplateRef(C).second;
5269 case CXCursor_NamespaceRef:
5270 return getCursorNamespaceRef(C).second;
5272 case CXCursor_MemberRef:
5273 return getCursorMemberRef(C).second;
5275 case CXCursor_CXXBaseSpecifier:
5276 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5278 case CXCursor_LabelRef:
5279 return getCursorLabelRef(C).second;
5281 case CXCursor_OverloadedDeclRef:
5282 return getCursorOverloadedDeclRef(C).second;
5284 case CXCursor_VariableRef:
5285 return getCursorVariableRef(C).second;
5288 // FIXME: Need a way to enumerate all non-reference cases.
5289 llvm_unreachable("Missed a reference kind");
5293 if (clang_isExpression(C.kind))
5294 return getCursorExpr(C)->getSourceRange();
5296 if (clang_isStatement(C.kind))
5297 return getCursorStmt(C)->getSourceRange();
5299 if (clang_isAttribute(C.kind))
5300 return getCursorAttr(C)->getRange();
5302 if (C.kind == CXCursor_PreprocessingDirective)
5303 return cxcursor::getCursorPreprocessingDirective(C);
5305 if (C.kind == CXCursor_MacroExpansion) {
5306 ASTUnit *TU = getCursorASTUnit(C);
5307 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5308 return TU->mapRangeFromPreamble(Range);
5311 if (C.kind == CXCursor_MacroDefinition) {
5312 ASTUnit *TU = getCursorASTUnit(C);
5313 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5314 return TU->mapRangeFromPreamble(Range);
5317 if (C.kind == CXCursor_InclusionDirective) {
5318 ASTUnit *TU = getCursorASTUnit(C);
5319 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5320 return TU->mapRangeFromPreamble(Range);
5323 if (C.kind == CXCursor_TranslationUnit) {
5324 ASTUnit *TU = getCursorASTUnit(C);
5325 FileID MainID = TU->getSourceManager().getMainFileID();
5326 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5327 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5328 return SourceRange(Start, End);
5331 if (clang_isDeclaration(C.kind)) {
5332 const Decl *D = cxcursor::getCursorDecl(C);
5334 return SourceRange();
5336 SourceRange R = D->getSourceRange();
5337 // FIXME: Multiple variables declared in a single declaration
5338 // currently lack the information needed to correctly determine their
5339 // ranges when accounting for the type-specifier. We use context
5340 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5341 // and if so, whether it is the first decl.
5342 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5343 if (!cxcursor::isFirstInDeclGroup(C))
5344 R.setBegin(VD->getLocation());
5348 return SourceRange();
5351 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
5352 /// the decl-specifier-seq for declarations.
5353 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5354 if (clang_isDeclaration(C.kind)) {
5355 const Decl *D = cxcursor::getCursorDecl(C);
5357 return SourceRange();
5359 SourceRange R = D->getSourceRange();
5361 // Adjust the start of the location for declarations preceded by
5362 // declaration specifiers.
5363 SourceLocation StartLoc;
5364 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5365 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5366 StartLoc = TI->getTypeLoc().getLocStart();
5367 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
5368 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5369 StartLoc = TI->getTypeLoc().getLocStart();
5372 if (StartLoc.isValid() && R.getBegin().isValid() &&
5373 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5374 R.setBegin(StartLoc);
5376 // FIXME: Multiple variables declared in a single declaration
5377 // currently lack the information needed to correctly determine their
5378 // ranges when accounting for the type-specifier. We use context
5379 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5380 // and if so, whether it is the first decl.
5381 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5382 if (!cxcursor::isFirstInDeclGroup(C))
5383 R.setBegin(VD->getLocation());
5389 return getRawCursorExtent(C);
5394 CXSourceRange clang_getCursorExtent(CXCursor C) {
5395 SourceRange R = getRawCursorExtent(C);
5397 return clang_getNullRange();
5399 return cxloc::translateSourceRange(getCursorContext(C), R);
5402 CXCursor clang_getCursorReferenced(CXCursor C) {
5403 if (clang_isInvalid(C.kind))
5404 return clang_getNullCursor();
5406 CXTranslationUnit tu = getCursorTU(C);
5407 if (clang_isDeclaration(C.kind)) {
5408 const Decl *D = getCursorDecl(C);
5410 return clang_getNullCursor();
5411 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5412 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
5413 if (const ObjCPropertyImplDecl *PropImpl =
5414 dyn_cast<ObjCPropertyImplDecl>(D))
5415 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5416 return MakeCXCursor(Property, tu);
5421 if (clang_isExpression(C.kind)) {
5422 const Expr *E = getCursorExpr(C);
5423 const Decl *D = getDeclFromExpr(E);
5425 CXCursor declCursor = MakeCXCursor(D, tu);
5426 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5431 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
5432 return MakeCursorOverloadedDeclRef(Ovl, tu);
5434 return clang_getNullCursor();
5437 if (clang_isStatement(C.kind)) {
5438 const Stmt *S = getCursorStmt(C);
5439 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
5440 if (LabelDecl *label = Goto->getLabel())
5441 if (LabelStmt *labelS = label->getStmt())
5442 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5444 return clang_getNullCursor();
5447 if (C.kind == CXCursor_MacroExpansion) {
5448 if (const MacroDefinitionRecord *Def =
5449 getCursorMacroExpansion(C).getDefinition())
5450 return MakeMacroDefinitionCursor(Def, tu);
5453 if (!clang_isReference(C.kind))
5454 return clang_getNullCursor();
5457 case CXCursor_ObjCSuperClassRef:
5458 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5460 case CXCursor_ObjCProtocolRef: {
5461 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5462 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5463 return MakeCXCursor(Def, tu);
5465 return MakeCXCursor(Prot, tu);
5468 case CXCursor_ObjCClassRef: {
5469 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5470 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5471 return MakeCXCursor(Def, tu);
5473 return MakeCXCursor(Class, tu);
5476 case CXCursor_TypeRef:
5477 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5479 case CXCursor_TemplateRef:
5480 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5482 case CXCursor_NamespaceRef:
5483 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5485 case CXCursor_MemberRef:
5486 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5488 case CXCursor_CXXBaseSpecifier: {
5489 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5490 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5494 case CXCursor_LabelRef:
5495 // FIXME: We end up faking the "parent" declaration here because we
5496 // don't want to make CXCursor larger.
5497 return MakeCXCursor(getCursorLabelRef(C).first,
5498 cxtu::getASTUnit(tu)->getASTContext()
5499 .getTranslationUnitDecl(),
5502 case CXCursor_OverloadedDeclRef:
5505 case CXCursor_VariableRef:
5506 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5509 // We would prefer to enumerate all non-reference cursor kinds here.
5510 llvm_unreachable("Unhandled reference cursor kind");
5514 CXCursor clang_getCursorDefinition(CXCursor C) {
5515 if (clang_isInvalid(C.kind))
5516 return clang_getNullCursor();
5518 CXTranslationUnit TU = getCursorTU(C);
5520 bool WasReference = false;
5521 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5522 C = clang_getCursorReferenced(C);
5523 WasReference = true;
5526 if (C.kind == CXCursor_MacroExpansion)
5527 return clang_getCursorReferenced(C);
5529 if (!clang_isDeclaration(C.kind))
5530 return clang_getNullCursor();
5532 const Decl *D = getCursorDecl(C);
5534 return clang_getNullCursor();
5536 switch (D->getKind()) {
5537 // Declaration kinds that don't really separate the notions of
5538 // declaration and definition.
5539 case Decl::Namespace:
5541 case Decl::TypeAlias:
5542 case Decl::TypeAliasTemplate:
5543 case Decl::TemplateTypeParm:
5544 case Decl::EnumConstant:
5546 case Decl::MSProperty:
5547 case Decl::IndirectField:
5548 case Decl::ObjCIvar:
5549 case Decl::ObjCAtDefsField:
5550 case Decl::ImplicitParam:
5552 case Decl::NonTypeTemplateParm:
5553 case Decl::TemplateTemplateParm:
5554 case Decl::ObjCCategoryImpl:
5555 case Decl::ObjCImplementation:
5556 case Decl::AccessSpec:
5557 case Decl::LinkageSpec:
5558 case Decl::ObjCPropertyImpl:
5559 case Decl::FileScopeAsm:
5560 case Decl::StaticAssert:
5562 case Decl::Captured:
5563 case Decl::OMPCapturedExpr:
5564 case Decl::Label: // FIXME: Is this right??
5565 case Decl::ClassScopeFunctionSpecialization:
5567 case Decl::OMPThreadPrivate:
5568 case Decl::OMPDeclareReduction:
5569 case Decl::ObjCTypeParam:
5570 case Decl::BuiltinTemplate:
5571 case Decl::PragmaComment:
5572 case Decl::PragmaDetectMismatch:
5575 // Declaration kinds that don't make any sense here, but are
5576 // nonetheless harmless.
5578 case Decl::TranslationUnit:
5579 case Decl::ExternCContext:
5582 // Declaration kinds for which the definition is not resolvable.
5583 case Decl::UnresolvedUsingTypename:
5584 case Decl::UnresolvedUsingValue:
5587 case Decl::UsingDirective:
5588 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5591 case Decl::NamespaceAlias:
5592 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5596 case Decl::CXXRecord:
5597 case Decl::ClassTemplateSpecialization:
5598 case Decl::ClassTemplatePartialSpecialization:
5599 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5600 return MakeCXCursor(Def, TU);
5601 return clang_getNullCursor();
5603 case Decl::Function:
5604 case Decl::CXXMethod:
5605 case Decl::CXXConstructor:
5606 case Decl::CXXDestructor:
5607 case Decl::CXXConversion: {
5608 const FunctionDecl *Def = nullptr;
5609 if (cast<FunctionDecl>(D)->getBody(Def))
5610 return MakeCXCursor(Def, TU);
5611 return clang_getNullCursor();
5615 case Decl::VarTemplateSpecialization:
5616 case Decl::VarTemplatePartialSpecialization: {
5617 // Ask the variable if it has a definition.
5618 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5619 return MakeCXCursor(Def, TU);
5620 return clang_getNullCursor();
5623 case Decl::FunctionTemplate: {
5624 const FunctionDecl *Def = nullptr;
5625 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5626 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5627 return clang_getNullCursor();
5630 case Decl::ClassTemplate: {
5631 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5633 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5635 return clang_getNullCursor();
5638 case Decl::VarTemplate: {
5640 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5641 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5642 return clang_getNullCursor();
5646 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5647 D->getLocation(), TU);
5649 case Decl::UsingShadow:
5650 return clang_getCursorDefinition(
5651 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5654 case Decl::ObjCMethod: {
5655 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5656 if (Method->isThisDeclarationADefinition())
5659 // Dig out the method definition in the associated
5660 // @implementation, if we have it.
5661 // FIXME: The ASTs should make finding the definition easier.
5662 if (const ObjCInterfaceDecl *Class
5663 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5664 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5665 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5666 Method->isInstanceMethod()))
5667 if (Def->isThisDeclarationADefinition())
5668 return MakeCXCursor(Def, TU);
5670 return clang_getNullCursor();
5673 case Decl::ObjCCategory:
5674 if (ObjCCategoryImplDecl *Impl
5675 = cast<ObjCCategoryDecl>(D)->getImplementation())
5676 return MakeCXCursor(Impl, TU);
5677 return clang_getNullCursor();
5679 case Decl::ObjCProtocol:
5680 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5681 return MakeCXCursor(Def, TU);
5682 return clang_getNullCursor();
5684 case Decl::ObjCInterface: {
5685 // There are two notions of a "definition" for an Objective-C
5686 // class: the interface and its implementation. When we resolved a
5687 // reference to an Objective-C class, produce the @interface as
5688 // the definition; when we were provided with the interface,
5689 // produce the @implementation as the definition.
5690 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5692 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5693 return MakeCXCursor(Def, TU);
5694 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5695 return MakeCXCursor(Impl, TU);
5696 return clang_getNullCursor();
5699 case Decl::ObjCProperty:
5700 // FIXME: We don't really know where to find the
5701 // ObjCPropertyImplDecls that implement this property.
5702 return clang_getNullCursor();
5704 case Decl::ObjCCompatibleAlias:
5705 if (const ObjCInterfaceDecl *Class
5706 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5707 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5708 return MakeCXCursor(Def, TU);
5710 return clang_getNullCursor();
5713 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5714 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5715 return clang_getNullCursor();
5717 case Decl::FriendTemplate:
5718 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5719 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5720 return clang_getNullCursor();
5723 return clang_getNullCursor();
5726 unsigned clang_isCursorDefinition(CXCursor C) {
5727 if (!clang_isDeclaration(C.kind))
5730 return clang_getCursorDefinition(C) == C;
5733 CXCursor clang_getCanonicalCursor(CXCursor C) {
5734 if (!clang_isDeclaration(C.kind))
5737 if (const Decl *D = getCursorDecl(C)) {
5738 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5739 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5740 return MakeCXCursor(CatD, getCursorTU(C));
5742 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5743 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5744 return MakeCXCursor(IFD, getCursorTU(C));
5746 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5752 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5753 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5756 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5757 if (C.kind != CXCursor_OverloadedDeclRef)
5760 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5761 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5762 return E->getNumDecls();
5764 if (OverloadedTemplateStorage *S
5765 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5768 const Decl *D = Storage.get<const Decl *>();
5769 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5770 return Using->shadow_size();
5775 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5776 if (cursor.kind != CXCursor_OverloadedDeclRef)
5777 return clang_getNullCursor();
5779 if (index >= clang_getNumOverloadedDecls(cursor))
5780 return clang_getNullCursor();
5782 CXTranslationUnit TU = getCursorTU(cursor);
5783 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5784 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5785 return MakeCXCursor(E->decls_begin()[index], TU);
5787 if (OverloadedTemplateStorage *S
5788 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5789 return MakeCXCursor(S->begin()[index], TU);
5791 const Decl *D = Storage.get<const Decl *>();
5792 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5793 // FIXME: This is, unfortunately, linear time.
5794 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5795 std::advance(Pos, index);
5796 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5799 return clang_getNullCursor();
5802 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5803 const char **startBuf,
5804 const char **endBuf,
5805 unsigned *startLine,
5806 unsigned *startColumn,
5808 unsigned *endColumn) {
5809 assert(getCursorDecl(C) && "CXCursor has null decl");
5810 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5811 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5813 SourceManager &SM = FD->getASTContext().getSourceManager();
5814 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5815 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5816 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5817 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5818 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5819 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5823 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5824 unsigned PieceIndex) {
5825 RefNamePieces Pieces;
5828 case CXCursor_MemberRefExpr:
5829 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5830 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5831 E->getQualifierLoc().getSourceRange());
5834 case CXCursor_DeclRefExpr:
5835 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5836 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5838 buildPieces(NameFlags, false, E->getNameInfo(),
5839 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5843 case CXCursor_CallExpr:
5844 if (const CXXOperatorCallExpr *OCE =
5845 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5846 const Expr *Callee = OCE->getCallee();
5847 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5848 Callee = ICE->getSubExpr();
5850 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5851 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5852 DRE->getQualifierLoc().getSourceRange());
5860 if (Pieces.empty()) {
5861 if (PieceIndex == 0)
5862 return clang_getCursorExtent(C);
5863 } else if (PieceIndex < Pieces.size()) {
5864 SourceRange R = Pieces[PieceIndex];
5866 return cxloc::translateSourceRange(getCursorContext(C), R);
5869 return clang_getNullRange();
5872 void clang_enableStackTraces(void) {
5873 llvm::sys::PrintStackTraceOnErrorSignal();
5876 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5877 unsigned stack_size) {
5878 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5881 } // end: extern "C"
5883 //===----------------------------------------------------------------------===//
5884 // Token-based Operations.
5885 //===----------------------------------------------------------------------===//
5888 * int_data[0]: a CXTokenKind
5889 * int_data[1]: starting token location
5890 * int_data[2]: token length
5891 * int_data[3]: reserved
5892 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5897 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5898 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5901 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5902 switch (clang_getTokenKind(CXTok)) {
5903 case CXToken_Identifier:
5904 case CXToken_Keyword:
5905 // We know we have an IdentifierInfo*, so use that.
5906 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5909 case CXToken_Literal: {
5910 // We have stashed the starting pointer in the ptr_data field. Use it.
5911 const char *Text = static_cast<const char *>(CXTok.ptr_data);
5912 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5915 case CXToken_Punctuation:
5916 case CXToken_Comment:
5920 if (isNotUsableTU(TU)) {
5922 return cxstring::createEmpty();
5925 // We have to find the starting buffer pointer the hard way, by
5926 // deconstructing the source location.
5927 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5929 return cxstring::createEmpty();
5931 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5932 std::pair<FileID, unsigned> LocInfo
5933 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5934 bool Invalid = false;
5936 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5938 return cxstring::createEmpty();
5940 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5943 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5944 if (isNotUsableTU(TU)) {
5946 return clang_getNullLocation();
5949 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5951 return clang_getNullLocation();
5953 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5954 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5957 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5958 if (isNotUsableTU(TU)) {
5960 return clang_getNullRange();
5963 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5965 return clang_getNullRange();
5967 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5968 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5971 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5972 SmallVectorImpl<CXToken> &CXTokens) {
5973 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5974 std::pair<FileID, unsigned> BeginLocInfo
5975 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5976 std::pair<FileID, unsigned> EndLocInfo
5977 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5979 // Cannot tokenize across files.
5980 if (BeginLocInfo.first != EndLocInfo.first)
5984 bool Invalid = false;
5986 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5990 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5991 CXXUnit->getASTContext().getLangOpts(),
5992 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
5993 Lex.SetCommentRetentionState(true);
5995 // Lex tokens until we hit the end of the range.
5996 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
5998 bool previousWasAt = false;
6000 // Lex the next token
6001 Lex.LexFromRawLexer(Tok);
6002 if (Tok.is(tok::eof))
6005 // Initialize the CXToken.
6009 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6010 CXTok.int_data[2] = Tok.getLength();
6011 CXTok.int_data[3] = 0;
6013 // - Kind-specific fields
6014 if (Tok.isLiteral()) {
6015 CXTok.int_data[0] = CXToken_Literal;
6016 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6017 } else if (Tok.is(tok::raw_identifier)) {
6018 // Lookup the identifier to determine whether we have a keyword.
6020 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6022 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6023 CXTok.int_data[0] = CXToken_Keyword;
6026 CXTok.int_data[0] = Tok.is(tok::identifier)
6027 ? CXToken_Identifier
6030 CXTok.ptr_data = II;
6031 } else if (Tok.is(tok::comment)) {
6032 CXTok.int_data[0] = CXToken_Comment;
6033 CXTok.ptr_data = nullptr;
6035 CXTok.int_data[0] = CXToken_Punctuation;
6036 CXTok.ptr_data = nullptr;
6038 CXTokens.push_back(CXTok);
6039 previousWasAt = Tok.is(tok::at);
6040 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
6043 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6044 CXToken **Tokens, unsigned *NumTokens) {
6046 *Log << TU << ' ' << Range;
6054 if (isNotUsableTU(TU)) {
6059 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6060 if (!CXXUnit || !Tokens || !NumTokens)
6063 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6065 SourceRange R = cxloc::translateCXSourceRange(Range);
6069 SmallVector<CXToken, 32> CXTokens;
6070 getTokens(CXXUnit, R, CXTokens);
6072 if (CXTokens.empty())
6075 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6076 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6077 *NumTokens = CXTokens.size();
6080 void clang_disposeTokens(CXTranslationUnit TU,
6081 CXToken *Tokens, unsigned NumTokens) {
6085 } // end: extern "C"
6087 //===----------------------------------------------------------------------===//
6088 // Token annotation APIs.
6089 //===----------------------------------------------------------------------===//
6091 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6093 CXClientData client_data);
6094 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6095 CXClientData client_data);
6098 class AnnotateTokensWorker {
6103 unsigned PreprocessingTokIdx;
6104 CursorVisitor AnnotateVis;
6105 SourceManager &SrcMgr;
6106 bool HasContextSensitiveKeywords;
6108 struct PostChildrenInfo {
6110 SourceRange CursorRange;
6111 unsigned BeforeReachingCursorIdx;
6112 unsigned BeforeChildrenTokenIdx;
6114 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
6116 CXToken &getTok(unsigned Idx) {
6117 assert(Idx < NumTokens);
6120 const CXToken &getTok(unsigned Idx) const {
6121 assert(Idx < NumTokens);
6124 bool MoreTokens() const { return TokIdx < NumTokens; }
6125 unsigned NextToken() const { return TokIdx; }
6126 void AdvanceToken() { ++TokIdx; }
6127 SourceLocation GetTokenLoc(unsigned tokI) {
6128 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6130 bool isFunctionMacroToken(unsigned tokI) const {
6131 return getTok(tokI).int_data[3] != 0;
6133 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
6134 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6137 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
6138 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
6142 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
6143 CXTranslationUnit TU, SourceRange RegionOfInterest)
6144 : Tokens(tokens), Cursors(cursors),
6145 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6147 AnnotateTokensVisitor, this,
6148 /*VisitPreprocessorLast=*/true,
6149 /*VisitIncludedEntities=*/false,
6151 /*VisitDeclsOnly=*/false,
6152 AnnotateTokensPostChildrenVisitor),
6153 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6154 HasContextSensitiveKeywords(false) { }
6156 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6157 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6158 bool postVisitChildren(CXCursor cursor);
6159 void AnnotateTokens();
6161 /// \brief Determine whether the annotator saw any cursors that have
6162 /// context-sensitive keywords.
6163 bool hasContextSensitiveKeywords() const {
6164 return HasContextSensitiveKeywords;
6167 ~AnnotateTokensWorker() {
6168 assert(PostChildrenInfos.empty());
6173 void AnnotateTokensWorker::AnnotateTokens() {
6174 // Walk the AST within the region of interest, annotating tokens
6176 AnnotateVis.visitFileRegion();
6179 static inline void updateCursorAnnotation(CXCursor &Cursor,
6180 const CXCursor &updateC) {
6181 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6186 /// \brief It annotates and advances tokens with a cursor until the comparison
6187 //// between the cursor location and the source range is the same as
6188 /// \arg compResult.
6190 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6191 /// Pass RangeOverlap to annotate tokens inside a range.
6192 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6193 RangeComparisonResult compResult,
6194 SourceRange range) {
6195 while (MoreTokens()) {
6196 const unsigned I = NextToken();
6197 if (isFunctionMacroToken(I))
6198 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6201 SourceLocation TokLoc = GetTokenLoc(I);
6202 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6203 updateCursorAnnotation(Cursors[I], updateC);
6211 /// \brief Special annotation handling for macro argument tokens.
6212 /// \returns true if it advanced beyond all macro tokens, false otherwise.
6213 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
6215 RangeComparisonResult compResult,
6216 SourceRange range) {
6217 assert(MoreTokens());
6218 assert(isFunctionMacroToken(NextToken()) &&
6219 "Should be called only for macro arg tokens");
6221 // This works differently than annotateAndAdvanceTokens; because expanded
6222 // macro arguments can have arbitrary translation-unit source order, we do not
6223 // advance the token index one by one until a token fails the range test.
6224 // We only advance once past all of the macro arg tokens if all of them
6225 // pass the range test. If one of them fails we keep the token index pointing
6226 // at the start of the macro arg tokens so that the failing token will be
6227 // annotated by a subsequent annotation try.
6229 bool atLeastOneCompFail = false;
6231 unsigned I = NextToken();
6232 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6233 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6234 if (TokLoc.isFileID())
6235 continue; // not macro arg token, it's parens or comma.
6236 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6237 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6238 Cursors[I] = updateC;
6240 atLeastOneCompFail = true;
6243 if (atLeastOneCompFail)
6246 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6250 enum CXChildVisitResult
6251 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
6252 SourceRange cursorRange = getRawCursorExtent(cursor);
6253 if (cursorRange.isInvalid())
6254 return CXChildVisit_Recurse;
6256 if (!HasContextSensitiveKeywords) {
6257 // Objective-C properties can have context-sensitive keywords.
6258 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
6259 if (const ObjCPropertyDecl *Property
6260 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6261 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6263 // Objective-C methods can have context-sensitive keywords.
6264 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6265 cursor.kind == CXCursor_ObjCClassMethodDecl) {
6266 if (const ObjCMethodDecl *Method
6267 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6268 if (Method->getObjCDeclQualifier())
6269 HasContextSensitiveKeywords = true;
6271 for (const auto *P : Method->params()) {
6272 if (P->getObjCDeclQualifier()) {
6273 HasContextSensitiveKeywords = true;
6280 // C++ methods can have context-sensitive keywords.
6281 else if (cursor.kind == CXCursor_CXXMethod) {
6282 if (const CXXMethodDecl *Method
6283 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6284 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6285 HasContextSensitiveKeywords = true;
6288 // C++ classes can have context-sensitive keywords.
6289 else if (cursor.kind == CXCursor_StructDecl ||
6290 cursor.kind == CXCursor_ClassDecl ||
6291 cursor.kind == CXCursor_ClassTemplate ||
6292 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
6293 if (const Decl *D = getCursorDecl(cursor))
6294 if (D->hasAttr<FinalAttr>())
6295 HasContextSensitiveKeywords = true;
6299 // Don't override a property annotation with its getter/setter method.
6300 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6301 parent.kind == CXCursor_ObjCPropertyDecl)
6302 return CXChildVisit_Continue;
6304 if (clang_isPreprocessing(cursor.kind)) {
6305 // Items in the preprocessing record are kept separate from items in
6306 // declarations, so we keep a separate token index.
6307 unsigned SavedTokIdx = TokIdx;
6308 TokIdx = PreprocessingTokIdx;
6310 // Skip tokens up until we catch up to the beginning of the preprocessing
6312 while (MoreTokens()) {
6313 const unsigned I = NextToken();
6314 SourceLocation TokLoc = GetTokenLoc(I);
6315 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6326 // Look at all of the tokens within this range.
6327 while (MoreTokens()) {
6328 const unsigned I = NextToken();
6329 SourceLocation TokLoc = GetTokenLoc(I);
6330 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6332 llvm_unreachable("Infeasible");
6336 // For macro expansions, just note where the beginning of the macro
6337 // expansion occurs.
6338 if (cursor.kind == CXCursor_MacroExpansion) {
6339 if (TokLoc == cursorRange.getBegin())
6340 Cursors[I] = cursor;
6344 // We may have already annotated macro names inside macro definitions.
6345 if (Cursors[I].kind != CXCursor_MacroExpansion)
6346 Cursors[I] = cursor;
6353 // Save the preprocessing token index; restore the non-preprocessing
6355 PreprocessingTokIdx = TokIdx;
6356 TokIdx = SavedTokIdx;
6357 return CXChildVisit_Recurse;
6360 if (cursorRange.isInvalid())
6361 return CXChildVisit_Continue;
6363 unsigned BeforeReachingCursorIdx = NextToken();
6364 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
6365 const enum CXCursorKind K = clang_getCursorKind(parent);
6366 const CXCursor updateC =
6367 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6368 // Attributes are annotated out-of-order, skip tokens until we reach it.
6369 clang_isAttribute(cursor.kind))
6370 ? clang_getNullCursor() : parent;
6372 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6374 // Avoid having the cursor of an expression "overwrite" the annotation of the
6375 // variable declaration that it belongs to.
6376 // This can happen for C++ constructor expressions whose range generally
6377 // include the variable declaration, e.g.:
6378 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
6379 if (clang_isExpression(cursorK) && MoreTokens()) {
6380 const Expr *E = getCursorExpr(cursor);
6381 if (const Decl *D = getCursorParentDecl(cursor)) {
6382 const unsigned I = NextToken();
6383 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6384 E->getLocStart() == D->getLocation() &&
6385 E->getLocStart() == GetTokenLoc(I)) {
6386 updateCursorAnnotation(Cursors[I], updateC);
6392 // Before recursing into the children keep some state that we are going
6393 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6394 // extra work after the child nodes are visited.
6395 // Note that we don't call VisitChildren here to avoid traversing statements
6396 // code-recursively which can blow the stack.
6398 PostChildrenInfo Info;
6399 Info.Cursor = cursor;
6400 Info.CursorRange = cursorRange;
6401 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
6402 Info.BeforeChildrenTokenIdx = NextToken();
6403 PostChildrenInfos.push_back(Info);
6405 return CXChildVisit_Recurse;
6408 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6409 if (PostChildrenInfos.empty())
6411 const PostChildrenInfo &Info = PostChildrenInfos.back();
6412 if (!clang_equalCursors(Info.Cursor, cursor))
6415 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6416 const unsigned AfterChildren = NextToken();
6417 SourceRange cursorRange = Info.CursorRange;
6419 // Scan the tokens that are at the end of the cursor, but are not captured
6420 // but the child cursors.
6421 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6423 // Scan the tokens that are at the beginning of the cursor, but are not
6424 // capture by the child cursors.
6425 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6426 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6429 Cursors[I] = cursor;
6432 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6433 // encountered the attribute cursor.
6434 if (clang_isAttribute(cursor.kind))
6435 TokIdx = Info.BeforeReachingCursorIdx;
6437 PostChildrenInfos.pop_back();
6441 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6443 CXClientData client_data) {
6444 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6447 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6448 CXClientData client_data) {
6449 return static_cast<AnnotateTokensWorker*>(client_data)->
6450 postVisitChildren(cursor);
6455 /// \brief Uses the macro expansions in the preprocessing record to find
6456 /// and mark tokens that are macro arguments. This info is used by the
6457 /// AnnotateTokensWorker.
6458 class MarkMacroArgTokensVisitor {
6465 MarkMacroArgTokensVisitor(SourceManager &SM,
6466 CXToken *tokens, unsigned numTokens)
6467 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6469 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6470 if (cursor.kind != CXCursor_MacroExpansion)
6471 return CXChildVisit_Continue;
6473 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6474 if (macroRange.getBegin() == macroRange.getEnd())
6475 return CXChildVisit_Continue; // it's not a function macro.
6477 for (; CurIdx < NumTokens; ++CurIdx) {
6478 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6479 macroRange.getBegin()))
6483 if (CurIdx == NumTokens)
6484 return CXChildVisit_Break;
6486 for (; CurIdx < NumTokens; ++CurIdx) {
6487 SourceLocation tokLoc = getTokenLoc(CurIdx);
6488 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6491 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6494 if (CurIdx == NumTokens)
6495 return CXChildVisit_Break;
6497 return CXChildVisit_Continue;
6501 CXToken &getTok(unsigned Idx) {
6502 assert(Idx < NumTokens);
6505 const CXToken &getTok(unsigned Idx) const {
6506 assert(Idx < NumTokens);
6510 SourceLocation getTokenLoc(unsigned tokI) {
6511 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6514 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6515 // The third field is reserved and currently not used. Use it here
6516 // to mark macro arg expanded tokens with their expanded locations.
6517 getTok(tokI).int_data[3] = loc.getRawEncoding();
6521 } // end anonymous namespace
6523 static CXChildVisitResult
6524 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6525 CXClientData client_data) {
6526 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6530 /// \brief Used by \c annotatePreprocessorTokens.
6531 /// \returns true if lexing was finished, false otherwise.
6532 static bool lexNext(Lexer &Lex, Token &Tok,
6533 unsigned &NextIdx, unsigned NumTokens) {
6534 if (NextIdx >= NumTokens)
6538 Lex.LexFromRawLexer(Tok);
6539 return Tok.is(tok::eof);
6542 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6543 SourceRange RegionOfInterest,
6546 unsigned NumTokens) {
6547 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6549 Preprocessor &PP = CXXUnit->getPreprocessor();
6550 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6551 std::pair<FileID, unsigned> BeginLocInfo
6552 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6553 std::pair<FileID, unsigned> EndLocInfo
6554 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6556 if (BeginLocInfo.first != EndLocInfo.first)
6560 bool Invalid = false;
6561 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6562 if (Buffer.empty() || Invalid)
6565 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6566 CXXUnit->getASTContext().getLangOpts(),
6567 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6569 Lex.SetCommentRetentionState(true);
6571 unsigned NextIdx = 0;
6572 // Lex tokens in raw mode until we hit the end of the range, to avoid
6573 // entering #includes or expanding macros.
6576 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6578 unsigned TokIdx = NextIdx-1;
6579 assert(Tok.getLocation() ==
6580 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6583 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6584 // We have found a preprocessing directive. Annotate the tokens
6587 // FIXME: Some simple tests here could identify macro definitions and
6588 // #undefs, to provide specific cursor kinds for those.
6590 SourceLocation BeginLoc = Tok.getLocation();
6591 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6594 MacroInfo *MI = nullptr;
6595 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6596 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6599 if (Tok.is(tok::raw_identifier)) {
6600 IdentifierInfo &II =
6601 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6602 SourceLocation MappedTokLoc =
6603 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6604 MI = getMacroInfo(II, MappedTokLoc, TU);
6608 bool finished = false;
6610 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6614 // If we are in a macro definition, check if the token was ever a
6615 // macro name and annotate it if that's the case.
6617 SourceLocation SaveLoc = Tok.getLocation();
6618 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6619 MacroDefinitionRecord *MacroDef =
6620 checkForMacroInMacroDefinition(MI, Tok, TU);
6621 Tok.setLocation(SaveLoc);
6623 Cursors[NextIdx - 1] =
6624 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6626 } while (!Tok.isAtStartOfLine());
6628 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6629 assert(TokIdx <= LastIdx);
6630 SourceLocation EndLoc =
6631 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6633 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6635 for (; TokIdx <= LastIdx; ++TokIdx)
6636 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6645 // This gets run a separate thread to avoid stack blowout.
6646 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6647 CXToken *Tokens, unsigned NumTokens,
6648 CXCursor *Cursors) {
6649 CIndexer *CXXIdx = TU->CIdx;
6650 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6651 setThreadBackgroundPriority();
6653 // Determine the region of interest, which contains all of the tokens.
6654 SourceRange RegionOfInterest;
6655 RegionOfInterest.setBegin(
6656 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6657 RegionOfInterest.setEnd(
6658 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6659 Tokens[NumTokens-1])));
6661 // Relex the tokens within the source range to look for preprocessing
6663 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6665 // If begin location points inside a macro argument, set it to the expansion
6666 // location so we can have the full context when annotating semantically.
6668 SourceManager &SM = CXXUnit->getSourceManager();
6669 SourceLocation Loc =
6670 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6671 if (Loc.isMacroID())
6672 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6675 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6676 // Search and mark tokens that are macro argument expansions.
6677 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6679 CursorVisitor MacroArgMarker(TU,
6680 MarkMacroArgTokensVisitorDelegate, &Visitor,
6681 /*VisitPreprocessorLast=*/true,
6682 /*VisitIncludedEntities=*/false,
6684 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6687 // Annotate all of the source locations in the region of interest that map to
6688 // a specific cursor.
6689 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6691 // FIXME: We use a ridiculous stack size here because the data-recursion
6692 // algorithm uses a large stack frame than the non-data recursive version,
6693 // and AnnotationTokensWorker currently transforms the data-recursion
6694 // algorithm back into a traditional recursion by explicitly calling
6695 // VisitChildren(). We will need to remove this explicit recursive call.
6698 // If we ran into any entities that involve context-sensitive keywords,
6699 // take another pass through the tokens to mark them as such.
6700 if (W.hasContextSensitiveKeywords()) {
6701 for (unsigned I = 0; I != NumTokens; ++I) {
6702 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6705 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6706 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6707 if (const ObjCPropertyDecl *Property
6708 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6709 if (Property->getPropertyAttributesAsWritten() != 0 &&
6710 llvm::StringSwitch<bool>(II->getName())
6711 .Case("readonly", true)
6712 .Case("assign", true)
6713 .Case("unsafe_unretained", true)
6714 .Case("readwrite", true)
6715 .Case("retain", true)
6717 .Case("nonatomic", true)
6718 .Case("atomic", true)
6719 .Case("getter", true)
6720 .Case("setter", true)
6721 .Case("strong", true)
6724 Tokens[I].int_data[0] = CXToken_Keyword;
6729 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6730 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6731 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6732 if (llvm::StringSwitch<bool>(II->getName())
6735 .Case("inout", true)
6736 .Case("oneway", true)
6737 .Case("bycopy", true)
6738 .Case("byref", true)
6740 Tokens[I].int_data[0] = CXToken_Keyword;
6744 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6745 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6746 Tokens[I].int_data[0] = CXToken_Keyword;
6755 void clang_annotateTokens(CXTranslationUnit TU,
6756 CXToken *Tokens, unsigned NumTokens,
6757 CXCursor *Cursors) {
6758 if (isNotUsableTU(TU)) {
6762 if (NumTokens == 0 || !Tokens || !Cursors) {
6763 LOG_FUNC_SECTION { *Log << "<null input>"; }
6769 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6770 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6771 *Log << clang_getRange(bloc, eloc);
6774 // Any token we don't specifically annotate will have a NULL cursor.
6775 CXCursor C = clang_getNullCursor();
6776 for (unsigned I = 0; I != NumTokens; ++I)
6779 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6783 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6785 auto AnnotateTokensImpl = [=]() {
6786 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6788 llvm::CrashRecoveryContext CRC;
6789 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6790 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6794 } // end: extern "C"
6796 //===----------------------------------------------------------------------===//
6797 // Operations for querying linkage of a cursor.
6798 //===----------------------------------------------------------------------===//
6801 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6802 if (!clang_isDeclaration(cursor.kind))
6803 return CXLinkage_Invalid;
6805 const Decl *D = cxcursor::getCursorDecl(cursor);
6806 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6807 switch (ND->getLinkageInternal()) {
6809 case VisibleNoLinkage: return CXLinkage_NoLinkage;
6810 case InternalLinkage: return CXLinkage_Internal;
6811 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6812 case ExternalLinkage: return CXLinkage_External;
6815 return CXLinkage_Invalid;
6817 } // end: extern "C"
6819 //===----------------------------------------------------------------------===//
6820 // Operations for querying visibility of a cursor.
6821 //===----------------------------------------------------------------------===//
6824 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6825 if (!clang_isDeclaration(cursor.kind))
6826 return CXVisibility_Invalid;
6828 const Decl *D = cxcursor::getCursorDecl(cursor);
6829 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6830 switch (ND->getVisibility()) {
6831 case HiddenVisibility: return CXVisibility_Hidden;
6832 case ProtectedVisibility: return CXVisibility_Protected;
6833 case DefaultVisibility: return CXVisibility_Default;
6836 return CXVisibility_Invalid;
6838 } // end: extern "C"
6840 //===----------------------------------------------------------------------===//
6841 // Operations for querying language of a cursor.
6842 //===----------------------------------------------------------------------===//
6844 static CXLanguageKind getDeclLanguage(const Decl *D) {
6846 return CXLanguage_C;
6848 switch (D->getKind()) {
6851 case Decl::ImplicitParam:
6852 case Decl::ObjCAtDefsField:
6853 case Decl::ObjCCategory:
6854 case Decl::ObjCCategoryImpl:
6855 case Decl::ObjCCompatibleAlias:
6856 case Decl::ObjCImplementation:
6857 case Decl::ObjCInterface:
6858 case Decl::ObjCIvar:
6859 case Decl::ObjCMethod:
6860 case Decl::ObjCProperty:
6861 case Decl::ObjCPropertyImpl:
6862 case Decl::ObjCProtocol:
6863 case Decl::ObjCTypeParam:
6864 return CXLanguage_ObjC;
6865 case Decl::CXXConstructor:
6866 case Decl::CXXConversion:
6867 case Decl::CXXDestructor:
6868 case Decl::CXXMethod:
6869 case Decl::CXXRecord:
6870 case Decl::ClassTemplate:
6871 case Decl::ClassTemplatePartialSpecialization:
6872 case Decl::ClassTemplateSpecialization:
6874 case Decl::FriendTemplate:
6875 case Decl::FunctionTemplate:
6876 case Decl::LinkageSpec:
6877 case Decl::Namespace:
6878 case Decl::NamespaceAlias:
6879 case Decl::NonTypeTemplateParm:
6880 case Decl::StaticAssert:
6881 case Decl::TemplateTemplateParm:
6882 case Decl::TemplateTypeParm:
6883 case Decl::UnresolvedUsingTypename:
6884 case Decl::UnresolvedUsingValue:
6886 case Decl::UsingDirective:
6887 case Decl::UsingShadow:
6888 return CXLanguage_CPlusPlus;
6891 return CXLanguage_C;
6896 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6897 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6898 return CXAvailability_NotAvailable;
6900 switch (D->getAvailability()) {
6902 case AR_NotYetIntroduced:
6903 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6904 return getCursorAvailabilityForDecl(
6905 cast<Decl>(EnumConst->getDeclContext()));
6906 return CXAvailability_Available;
6909 return CXAvailability_Deprecated;
6911 case AR_Unavailable:
6912 return CXAvailability_NotAvailable;
6915 llvm_unreachable("Unknown availability kind!");
6918 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6919 if (clang_isDeclaration(cursor.kind))
6920 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6921 return getCursorAvailabilityForDecl(D);
6923 return CXAvailability_Available;
6926 static CXVersion convertVersion(VersionTuple In) {
6927 CXVersion Out = { -1, -1, -1 };
6931 Out.Major = In.getMajor();
6933 Optional<unsigned> Minor = In.getMinor();
6934 if (Minor.hasValue())
6939 Optional<unsigned> Subminor = In.getSubminor();
6940 if (Subminor.hasValue())
6941 Out.Subminor = *Subminor;
6946 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6947 int *always_deprecated,
6948 CXString *deprecated_message,
6949 int *always_unavailable,
6950 CXString *unavailable_message,
6951 CXPlatformAvailability *availability,
6952 int availability_size) {
6953 bool HadAvailAttr = false;
6955 for (auto A : D->attrs()) {
6956 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6957 HadAvailAttr = true;
6958 if (always_deprecated)
6959 *always_deprecated = 1;
6960 if (deprecated_message) {
6961 clang_disposeString(*deprecated_message);
6962 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6967 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6968 HadAvailAttr = true;
6969 if (always_unavailable)
6970 *always_unavailable = 1;
6971 if (unavailable_message) {
6972 clang_disposeString(*unavailable_message);
6973 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6978 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6979 HadAvailAttr = true;
6980 if (N < availability_size) {
6981 availability[N].Platform
6982 = cxstring::createDup(Avail->getPlatform()->getName());
6983 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6984 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6985 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6986 availability[N].Unavailable = Avail->getUnavailable();
6987 availability[N].Message = cxstring::createDup(Avail->getMessage());
6994 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6995 return getCursorPlatformAvailabilityForDecl(
6996 cast<Decl>(EnumConst->getDeclContext()),
7000 unavailable_message,
7007 int clang_getCursorPlatformAvailability(CXCursor cursor,
7008 int *always_deprecated,
7009 CXString *deprecated_message,
7010 int *always_unavailable,
7011 CXString *unavailable_message,
7012 CXPlatformAvailability *availability,
7013 int availability_size) {
7014 if (always_deprecated)
7015 *always_deprecated = 0;
7016 if (deprecated_message)
7017 *deprecated_message = cxstring::createEmpty();
7018 if (always_unavailable)
7019 *always_unavailable = 0;
7020 if (unavailable_message)
7021 *unavailable_message = cxstring::createEmpty();
7023 if (!clang_isDeclaration(cursor.kind))
7026 const Decl *D = cxcursor::getCursorDecl(cursor);
7030 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7033 unavailable_message,
7038 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7039 clang_disposeString(availability->Platform);
7040 clang_disposeString(availability->Message);
7043 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7044 if (clang_isDeclaration(cursor.kind))
7045 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7047 return CXLanguage_Invalid;
7050 /// \brief If the given cursor is the "templated" declaration
7051 /// descibing a class or function template, return the class or
7052 /// function template.
7053 static const Decl *maybeGetTemplateCursor(const Decl *D) {
7057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7058 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7061 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7062 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7069 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7070 StorageClass sc = SC_None;
7071 const Decl *D = getCursorDecl(C);
7073 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7074 sc = FD->getStorageClass();
7075 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7076 sc = VD->getStorageClass();
7078 return CX_SC_Invalid;
7081 return CX_SC_Invalid;
7087 return CX_SC_Extern;
7089 return CX_SC_Static;
7090 case SC_PrivateExtern:
7091 return CX_SC_PrivateExtern;
7095 return CX_SC_Register;
7097 llvm_unreachable("Unhandled storage class!");
7100 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7101 if (clang_isDeclaration(cursor.kind)) {
7102 if (const Decl *D = getCursorDecl(cursor)) {
7103 const DeclContext *DC = D->getDeclContext();
7105 return clang_getNullCursor();
7107 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7108 getCursorTU(cursor));
7112 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
7113 if (const Decl *D = getCursorDecl(cursor))
7114 return MakeCXCursor(D, getCursorTU(cursor));
7117 return clang_getNullCursor();
7120 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7121 if (clang_isDeclaration(cursor.kind)) {
7122 if (const Decl *D = getCursorDecl(cursor)) {
7123 const DeclContext *DC = D->getLexicalDeclContext();
7125 return clang_getNullCursor();
7127 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7128 getCursorTU(cursor));
7132 // FIXME: Note that we can't easily compute the lexical context of a
7133 // statement or expression, so we return nothing.
7134 return clang_getNullCursor();
7137 CXFile clang_getIncludedFile(CXCursor cursor) {
7138 if (cursor.kind != CXCursor_InclusionDirective)
7141 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
7142 return const_cast<FileEntry *>(ID->getFile());
7145 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7146 if (C.kind != CXCursor_ObjCPropertyDecl)
7147 return CXObjCPropertyAttr_noattr;
7149 unsigned Result = CXObjCPropertyAttr_noattr;
7150 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7151 ObjCPropertyDecl::PropertyAttributeKind Attr =
7152 PD->getPropertyAttributesAsWritten();
7154 #define SET_CXOBJCPROP_ATTR(A) \
7155 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7156 Result |= CXObjCPropertyAttr_##A
7157 SET_CXOBJCPROP_ATTR(readonly);
7158 SET_CXOBJCPROP_ATTR(getter);
7159 SET_CXOBJCPROP_ATTR(assign);
7160 SET_CXOBJCPROP_ATTR(readwrite);
7161 SET_CXOBJCPROP_ATTR(retain);
7162 SET_CXOBJCPROP_ATTR(copy);
7163 SET_CXOBJCPROP_ATTR(nonatomic);
7164 SET_CXOBJCPROP_ATTR(setter);
7165 SET_CXOBJCPROP_ATTR(atomic);
7166 SET_CXOBJCPROP_ATTR(weak);
7167 SET_CXOBJCPROP_ATTR(strong);
7168 SET_CXOBJCPROP_ATTR(unsafe_unretained);
7169 #undef SET_CXOBJCPROP_ATTR
7174 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7175 if (!clang_isDeclaration(C.kind))
7176 return CXObjCDeclQualifier_None;
7178 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7179 const Decl *D = getCursorDecl(C);
7180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7181 QT = MD->getObjCDeclQualifier();
7182 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7183 QT = PD->getObjCDeclQualifier();
7184 if (QT == Decl::OBJC_TQ_None)
7185 return CXObjCDeclQualifier_None;
7187 unsigned Result = CXObjCDeclQualifier_None;
7188 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7189 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7190 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7191 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7192 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7193 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7198 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7199 if (!clang_isDeclaration(C.kind))
7202 const Decl *D = getCursorDecl(C);
7203 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7204 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7205 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7206 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7211 unsigned clang_Cursor_isVariadic(CXCursor C) {
7212 if (!clang_isDeclaration(C.kind))
7215 const Decl *D = getCursorDecl(C);
7216 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7217 return FD->isVariadic();
7218 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7219 return MD->isVariadic();
7224 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7225 if (!clang_isDeclaration(C.kind))
7226 return clang_getNullRange();
7228 const Decl *D = getCursorDecl(C);
7229 ASTContext &Context = getCursorContext(C);
7230 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7232 return clang_getNullRange();
7234 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7237 CXString clang_Cursor_getRawCommentText(CXCursor C) {
7238 if (!clang_isDeclaration(C.kind))
7239 return cxstring::createNull();
7241 const Decl *D = getCursorDecl(C);
7242 ASTContext &Context = getCursorContext(C);
7243 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7244 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7247 // Don't duplicate the string because RawText points directly into source
7249 return cxstring::createRef(RawText);
7252 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7253 if (!clang_isDeclaration(C.kind))
7254 return cxstring::createNull();
7256 const Decl *D = getCursorDecl(C);
7257 const ASTContext &Context = getCursorContext(C);
7258 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7261 StringRef BriefText = RC->getBriefText(Context);
7263 // Don't duplicate the string because RawComment ensures that this memory
7264 // will not go away.
7265 return cxstring::createRef(BriefText);
7268 return cxstring::createNull();
7271 CXModule clang_Cursor_getModule(CXCursor C) {
7272 if (C.kind == CXCursor_ModuleImportDecl) {
7273 if (const ImportDecl *ImportD =
7274 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
7275 return ImportD->getImportedModule();
7281 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7282 if (isNotUsableTU(TU)) {
7288 FileEntry *FE = static_cast<FileEntry *>(File);
7290 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7291 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7292 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7294 return Header.getModule();
7297 CXFile clang_Module_getASTFile(CXModule CXMod) {
7300 Module *Mod = static_cast<Module*>(CXMod);
7301 return const_cast<FileEntry *>(Mod->getASTFile());
7304 CXModule clang_Module_getParent(CXModule CXMod) {
7307 Module *Mod = static_cast<Module*>(CXMod);
7311 CXString clang_Module_getName(CXModule CXMod) {
7313 return cxstring::createEmpty();
7314 Module *Mod = static_cast<Module*>(CXMod);
7315 return cxstring::createDup(Mod->Name);
7318 CXString clang_Module_getFullName(CXModule CXMod) {
7320 return cxstring::createEmpty();
7321 Module *Mod = static_cast<Module*>(CXMod);
7322 return cxstring::createDup(Mod->getFullModuleName());
7325 int clang_Module_isSystem(CXModule CXMod) {
7328 Module *Mod = static_cast<Module*>(CXMod);
7329 return Mod->IsSystem;
7332 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7334 if (isNotUsableTU(TU)) {
7340 Module *Mod = static_cast<Module*>(CXMod);
7341 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7342 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7343 return TopHeaders.size();
7346 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7347 CXModule CXMod, unsigned Index) {
7348 if (isNotUsableTU(TU)) {
7354 Module *Mod = static_cast<Module*>(CXMod);
7355 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7357 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7358 if (Index < TopHeaders.size())
7359 return const_cast<FileEntry *>(TopHeaders[Index]);
7364 } // end: extern "C"
7366 //===----------------------------------------------------------------------===//
7367 // C++ AST instrospection.
7368 //===----------------------------------------------------------------------===//
7372 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7373 if (!clang_isDeclaration(C.kind))
7376 const Decl *D = cxcursor::getCursorDecl(C);
7377 const CXXConstructorDecl *Constructor =
7378 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7379 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7382 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7383 if (!clang_isDeclaration(C.kind))
7386 const Decl *D = cxcursor::getCursorDecl(C);
7387 const CXXConstructorDecl *Constructor =
7388 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7389 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7392 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7393 if (!clang_isDeclaration(C.kind))
7396 const Decl *D = cxcursor::getCursorDecl(C);
7397 const CXXConstructorDecl *Constructor =
7398 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7399 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7402 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7403 if (!clang_isDeclaration(C.kind))
7406 const Decl *D = cxcursor::getCursorDecl(C);
7407 const CXXConstructorDecl *Constructor =
7408 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7409 // Passing 'false' excludes constructors marked 'explicit'.
7410 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7413 unsigned clang_CXXField_isMutable(CXCursor C) {
7414 if (!clang_isDeclaration(C.kind))
7417 if (const auto D = cxcursor::getCursorDecl(C))
7418 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7419 return FD->isMutable() ? 1 : 0;
7423 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7424 if (!clang_isDeclaration(C.kind))
7427 const Decl *D = cxcursor::getCursorDecl(C);
7428 const CXXMethodDecl *Method =
7429 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7430 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7433 unsigned clang_CXXMethod_isConst(CXCursor C) {
7434 if (!clang_isDeclaration(C.kind))
7437 const Decl *D = cxcursor::getCursorDecl(C);
7438 const CXXMethodDecl *Method =
7439 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7440 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7443 unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7444 if (!clang_isDeclaration(C.kind))
7447 const Decl *D = cxcursor::getCursorDecl(C);
7448 const CXXMethodDecl *Method =
7449 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7450 return (Method && Method->isDefaulted()) ? 1 : 0;
7453 unsigned clang_CXXMethod_isStatic(CXCursor C) {
7454 if (!clang_isDeclaration(C.kind))
7457 const Decl *D = cxcursor::getCursorDecl(C);
7458 const CXXMethodDecl *Method =
7459 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7460 return (Method && Method->isStatic()) ? 1 : 0;
7463 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7464 if (!clang_isDeclaration(C.kind))
7467 const Decl *D = cxcursor::getCursorDecl(C);
7468 const CXXMethodDecl *Method =
7469 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7470 return (Method && Method->isVirtual()) ? 1 : 0;
7472 } // end: extern "C"
7474 //===----------------------------------------------------------------------===//
7475 // Attribute introspection.
7476 //===----------------------------------------------------------------------===//
7479 CXType clang_getIBOutletCollectionType(CXCursor C) {
7480 if (C.kind != CXCursor_IBOutletCollectionAttr)
7481 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7483 const IBOutletCollectionAttr *A =
7484 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7486 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7488 } // end: extern "C"
7490 //===----------------------------------------------------------------------===//
7491 // Inspecting memory usage.
7492 //===----------------------------------------------------------------------===//
7494 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7496 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7497 enum CXTUResourceUsageKind k,
7498 unsigned long amount) {
7499 CXTUResourceUsageEntry entry = { k, amount };
7500 entries.push_back(entry);
7505 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7506 const char *str = "";
7508 case CXTUResourceUsage_AST:
7509 str = "ASTContext: expressions, declarations, and types";
7511 case CXTUResourceUsage_Identifiers:
7512 str = "ASTContext: identifiers";
7514 case CXTUResourceUsage_Selectors:
7515 str = "ASTContext: selectors";
7517 case CXTUResourceUsage_GlobalCompletionResults:
7518 str = "Code completion: cached global results";
7520 case CXTUResourceUsage_SourceManagerContentCache:
7521 str = "SourceManager: content cache allocator";
7523 case CXTUResourceUsage_AST_SideTables:
7524 str = "ASTContext: side tables";
7526 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7527 str = "SourceManager: malloc'ed memory buffers";
7529 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7530 str = "SourceManager: mmap'ed memory buffers";
7532 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7533 str = "ExternalASTSource: malloc'ed memory buffers";
7535 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7536 str = "ExternalASTSource: mmap'ed memory buffers";
7538 case CXTUResourceUsage_Preprocessor:
7539 str = "Preprocessor: malloc'ed memory";
7541 case CXTUResourceUsage_PreprocessingRecord:
7542 str = "Preprocessor: PreprocessingRecord";
7544 case CXTUResourceUsage_SourceManager_DataStructures:
7545 str = "SourceManager: data structures and tables";
7547 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7548 str = "Preprocessor: header search tables";
7554 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7555 if (isNotUsableTU(TU)) {
7557 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7561 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7562 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7563 ASTContext &astContext = astUnit->getASTContext();
7565 // How much memory is used by AST nodes and types?
7566 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7567 (unsigned long) astContext.getASTAllocatedMemory());
7569 // How much memory is used by identifiers?
7570 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7571 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7573 // How much memory is used for selectors?
7574 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7575 (unsigned long) astContext.Selectors.getTotalMemory());
7577 // How much memory is used by ASTContext's side tables?
7578 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7579 (unsigned long) astContext.getSideTableAllocatedMemory());
7581 // How much memory is used for caching global code completion results?
7582 unsigned long completionBytes = 0;
7583 if (GlobalCodeCompletionAllocator *completionAllocator =
7584 astUnit->getCachedCompletionAllocator().get()) {
7585 completionBytes = completionAllocator->getTotalMemory();
7587 createCXTUResourceUsageEntry(*entries,
7588 CXTUResourceUsage_GlobalCompletionResults,
7591 // How much memory is being used by SourceManager's content cache?
7592 createCXTUResourceUsageEntry(*entries,
7593 CXTUResourceUsage_SourceManagerContentCache,
7594 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7596 // How much memory is being used by the MemoryBuffer's in SourceManager?
7597 const SourceManager::MemoryBufferSizes &srcBufs =
7598 astUnit->getSourceManager().getMemoryBufferSizes();
7600 createCXTUResourceUsageEntry(*entries,
7601 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7602 (unsigned long) srcBufs.malloc_bytes);
7603 createCXTUResourceUsageEntry(*entries,
7604 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7605 (unsigned long) srcBufs.mmap_bytes);
7606 createCXTUResourceUsageEntry(*entries,
7607 CXTUResourceUsage_SourceManager_DataStructures,
7608 (unsigned long) astContext.getSourceManager()
7609 .getDataStructureSizes());
7611 // How much memory is being used by the ExternalASTSource?
7612 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7613 const ExternalASTSource::MemoryBufferSizes &sizes =
7614 esrc->getMemoryBufferSizes();
7616 createCXTUResourceUsageEntry(*entries,
7617 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7618 (unsigned long) sizes.malloc_bytes);
7619 createCXTUResourceUsageEntry(*entries,
7620 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7621 (unsigned long) sizes.mmap_bytes);
7624 // How much memory is being used by the Preprocessor?
7625 Preprocessor &pp = astUnit->getPreprocessor();
7626 createCXTUResourceUsageEntry(*entries,
7627 CXTUResourceUsage_Preprocessor,
7628 pp.getTotalMemory());
7630 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7631 createCXTUResourceUsageEntry(*entries,
7632 CXTUResourceUsage_PreprocessingRecord,
7633 pRec->getTotalMemory());
7636 createCXTUResourceUsageEntry(*entries,
7637 CXTUResourceUsage_Preprocessor_HeaderSearch,
7638 pp.getHeaderSearchInfo().getTotalMemory());
7640 CXTUResourceUsage usage = { (void*) entries.get(),
7641 (unsigned) entries->size(),
7642 !entries->empty() ? &(*entries)[0] : nullptr };
7647 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7649 delete (MemUsageEntries*) usage.data;
7652 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7653 CXSourceRangeList *skipped = new CXSourceRangeList;
7655 skipped->ranges = nullptr;
7657 if (isNotUsableTU(TU)) {
7665 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7666 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7670 ASTContext &Ctx = astUnit->getASTContext();
7671 SourceManager &sm = Ctx.getSourceManager();
7672 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7673 FileID wantedFileID = sm.translateFile(fileEntry);
7675 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7676 std::vector<SourceRange> wantedRanges;
7677 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7679 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7680 wantedRanges.push_back(*i);
7683 skipped->count = wantedRanges.size();
7684 skipped->ranges = new CXSourceRange[skipped->count];
7685 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7686 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7691 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7693 delete[] ranges->ranges;
7700 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7701 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7702 for (unsigned I = 0; I != Usage.numEntries; ++I)
7703 fprintf(stderr, " %s: %lu\n",
7704 clang_getTUResourceUsageName(Usage.entries[I].kind),
7705 Usage.entries[I].amount);
7707 clang_disposeCXTUResourceUsage(Usage);
7710 //===----------------------------------------------------------------------===//
7711 // Misc. utility functions.
7712 //===----------------------------------------------------------------------===//
7714 /// Default to using an 8 MB stack size on "safety" threads.
7715 static unsigned SafetyStackThreadSize = 8 << 20;
7719 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7722 Size = GetSafetyThreadStackSize();
7724 return CRC.RunSafelyOnThread(Fn, Size);
7725 return CRC.RunSafely(Fn);
7728 unsigned GetSafetyThreadStackSize() {
7729 return SafetyStackThreadSize;
7732 void SetSafetyThreadStackSize(unsigned Value) {
7733 SafetyStackThreadSize = Value;
7738 void clang::setThreadBackgroundPriority() {
7739 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7742 #ifdef USE_DARWIN_THREADS
7743 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7747 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7751 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7752 DEnd = Unit->stored_diag_end();
7754 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7755 CXString Msg = clang_formatDiagnostic(&Diag,
7756 clang_defaultDiagnosticDisplayOptions());
7757 fprintf(stderr, "%s\n", clang_getCString(Msg));
7758 clang_disposeString(Msg);
7760 #ifdef LLVM_ON_WIN32
7761 // On Windows, force a flush, since there may be multiple copies of
7762 // stderr and stdout in the file system, all with different buffers
7763 // but writing to the same device.
7768 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7769 SourceLocation MacroDefLoc,
7770 CXTranslationUnit TU){
7771 if (MacroDefLoc.isInvalid() || !TU)
7773 if (!II.hadMacroDefinition())
7776 ASTUnit *Unit = cxtu::getASTUnit(TU);
7777 Preprocessor &PP = Unit->getPreprocessor();
7778 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7780 for (MacroDirective::DefInfo
7781 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7782 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7783 return Def.getMacroInfo();
7790 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7791 CXTranslationUnit TU) {
7792 if (!MacroDef || !TU)
7794 const IdentifierInfo *II = MacroDef->getName();
7798 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7801 MacroDefinitionRecord *
7802 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7803 CXTranslationUnit TU) {
7806 if (Tok.isNot(tok::raw_identifier))
7809 if (MI->getNumTokens() == 0)
7811 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7812 MI->getDefinitionEndLoc());
7813 ASTUnit *Unit = cxtu::getASTUnit(TU);
7815 // Check that the token is inside the definition and not its argument list.
7816 SourceManager &SM = Unit->getSourceManager();
7817 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7819 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7822 Preprocessor &PP = Unit->getPreprocessor();
7823 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7827 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7828 if (!II.hadMacroDefinition())
7831 // Check that the identifier is not one of the macro arguments.
7832 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7835 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7839 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7842 MacroDefinitionRecord *
7843 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7844 CXTranslationUnit TU) {
7845 if (Loc.isInvalid() || !MI || !TU)
7848 if (MI->getNumTokens() == 0)
7850 ASTUnit *Unit = cxtu::getASTUnit(TU);
7851 Preprocessor &PP = Unit->getPreprocessor();
7852 if (!PP.getPreprocessingRecord())
7854 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7856 if (PP.getRawToken(Loc, Tok))
7859 return checkForMacroInMacroDefinition(MI, Tok, TU);
7864 CXString clang_getClangVersion() {
7865 return cxstring::createDup(getClangFullVersion());
7868 } // end: extern "C"
7870 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7872 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7873 LogOS << '<' << Unit->getMainFileName() << '>';
7874 if (Unit->isMainFileAST())
7875 LogOS << " (" << Unit->getASTFileName() << ')';
7879 LogOS << "<NULL TU>";
7884 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7885 *this << FE->getName();
7889 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7890 CXString cursorName = clang_getCursorDisplayName(cursor);
7891 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7892 clang_disposeString(cursorName);
7896 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7898 unsigned Line, Column;
7899 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7900 CXString FileName = clang_getFileName(File);
7901 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7902 clang_disposeString(FileName);
7906 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7907 CXSourceLocation BLoc = clang_getRangeStart(range);
7908 CXSourceLocation ELoc = clang_getRangeEnd(range);
7911 unsigned BLine, BColumn;
7912 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7915 unsigned ELine, EColumn;
7916 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7918 CXString BFileName = clang_getFileName(BFile);
7919 if (BFile == EFile) {
7920 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7921 BLine, BColumn, ELine, EColumn);
7923 CXString EFileName = clang_getFileName(EFile);
7924 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7926 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7928 clang_disposeString(EFileName);
7930 clang_disposeString(BFileName);
7934 Logger &cxindex::Logger::operator<<(CXString Str) {
7935 *this << clang_getCString(Str);
7939 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7944 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7946 cxindex::Logger::~Logger() {
7947 llvm::sys::ScopedLock L(*LoggingMutex);
7949 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7951 raw_ostream &OS = llvm::errs();
7952 OS << "[libclang:" << Name << ':';
7954 #ifdef USE_DARWIN_THREADS
7955 // TODO: Portability.
7956 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7960 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7961 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7965 llvm::sys::PrintStackTrace(OS);
7966 OS << "--------------------------------------------------\n";
7970 #ifdef CLANG_TOOL_EXTRA_BUILD
7971 // This anchor is used to force the linker to link the clang-tidy plugin.
7972 extern volatile int ClangTidyPluginAnchorSource;
7973 static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
7974 ClangTidyPluginAnchorSource;