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 case BuiltinType::OCLImage1d:
1458 case BuiltinType::OCLImage1dArray:
1459 case BuiltinType::OCLImage1dBuffer:
1460 case BuiltinType::OCLImage2d:
1461 case BuiltinType::OCLImage2dArray:
1462 case BuiltinType::OCLImage2dDepth:
1463 case BuiltinType::OCLImage2dArrayDepth:
1464 case BuiltinType::OCLImage2dMSAA:
1465 case BuiltinType::OCLImage2dArrayMSAA:
1466 case BuiltinType::OCLImage2dMSAADepth:
1467 case BuiltinType::OCLImage2dArrayMSAADepth:
1468 case BuiltinType::OCLImage3d:
1469 case BuiltinType::OCLSampler:
1470 case BuiltinType::OCLEvent:
1471 case BuiltinType::OCLClkEvent:
1472 case BuiltinType::OCLQueue:
1473 case BuiltinType::OCLNDRange:
1474 case BuiltinType::OCLReserveID:
1475 #define BUILTIN_TYPE(Id, SingletonId)
1476 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1477 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1478 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1479 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1480 #include "clang/AST/BuiltinTypes.def"
1483 case BuiltinType::ObjCId:
1484 VisitType = Context.getObjCIdType();
1487 case BuiltinType::ObjCClass:
1488 VisitType = Context.getObjCClassType();
1491 case BuiltinType::ObjCSel:
1492 VisitType = Context.getObjCSelType();
1496 if (!VisitType.isNull()) {
1497 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1498 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1505 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1506 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1509 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1510 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1513 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1514 if (TL.isDefinition())
1515 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1517 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1520 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1521 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1524 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1525 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1528 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1529 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1532 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1533 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1537 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1538 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1546 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1547 return Visit(TL.getPointeeLoc());
1550 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1551 return Visit(TL.getInnerLoc());
1554 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1555 return Visit(TL.getPointeeLoc());
1558 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1559 return Visit(TL.getPointeeLoc());
1562 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1563 return Visit(TL.getPointeeLoc());
1566 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1567 return Visit(TL.getPointeeLoc());
1570 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1571 return Visit(TL.getPointeeLoc());
1574 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1575 return Visit(TL.getModifiedLoc());
1578 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1579 bool SkipResultType) {
1580 if (!SkipResultType && Visit(TL.getReturnLoc()))
1583 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1584 if (Decl *D = TL.getParam(I))
1585 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1591 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1592 if (Visit(TL.getElementLoc()))
1595 if (Expr *Size = TL.getSizeExpr())
1596 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1601 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1602 return Visit(TL.getOriginalLoc());
1605 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1606 return Visit(TL.getOriginalLoc());
1609 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1610 TemplateSpecializationTypeLoc TL) {
1611 // Visit the template name.
1612 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1613 TL.getTemplateNameLoc()))
1616 // Visit the template arguments.
1617 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1618 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1624 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1625 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1628 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1629 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1630 return Visit(TSInfo->getTypeLoc());
1635 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1636 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1637 return Visit(TSInfo->getTypeLoc());
1642 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1643 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1646 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1647 DependentTemplateSpecializationTypeLoc TL) {
1648 // Visit the nested-name-specifier, if there is one.
1649 if (TL.getQualifierLoc() &&
1650 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1653 // Visit the template arguments.
1654 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1655 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1661 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1662 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1665 return Visit(TL.getNamedTypeLoc());
1668 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1669 return Visit(TL.getPatternLoc());
1672 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1673 if (Expr *E = TL.getUnderlyingExpr())
1674 return Visit(MakeCXCursor(E, StmtParent, TU));
1679 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1680 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1683 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1684 return Visit(TL.getValueLoc());
1687 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1688 return Visit(TL.getValueLoc());
1691 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1692 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1693 return Visit##PARENT##Loc(TL); \
1696 DEFAULT_TYPELOC_IMPL(Complex, Type)
1697 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1698 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1699 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1700 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1701 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1702 DEFAULT_TYPELOC_IMPL(Vector, Type)
1703 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1704 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1705 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1706 DEFAULT_TYPELOC_IMPL(Record, TagType)
1707 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1708 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1709 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1710 DEFAULT_TYPELOC_IMPL(Auto, Type)
1712 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1713 // Visit the nested-name-specifier, if present.
1714 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1715 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1718 if (D->isCompleteDefinition()) {
1719 for (const auto &I : D->bases()) {
1720 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1725 return VisitTagDecl(D);
1728 bool CursorVisitor::VisitAttributes(Decl *D) {
1729 for (const auto *I : D->attrs())
1730 if (Visit(MakeCXCursor(I, D, TU)))
1736 //===----------------------------------------------------------------------===//
1737 // Data-recursive visitor methods.
1738 //===----------------------------------------------------------------------===//
1741 #define DEF_JOB(NAME, DATA, KIND)\
1742 class NAME : public VisitorJob {\
1744 NAME(const DATA *d, CXCursor parent) : \
1745 VisitorJob(parent, VisitorJob::KIND, d) {} \
1746 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1747 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1750 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1751 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1752 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1753 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1754 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1755 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1756 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1759 class ExplicitTemplateArgsVisit : public VisitorJob {
1761 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1762 const TemplateArgumentLoc *End, CXCursor parent)
1763 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1765 static bool classof(const VisitorJob *VJ) {
1766 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1768 const TemplateArgumentLoc *begin() const {
1769 return static_cast<const TemplateArgumentLoc *>(data[0]);
1771 const TemplateArgumentLoc *end() {
1772 return static_cast<const TemplateArgumentLoc *>(data[1]);
1775 class DeclVisit : public VisitorJob {
1777 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1778 VisitorJob(parent, VisitorJob::DeclVisitKind,
1779 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1780 static bool classof(const VisitorJob *VJ) {
1781 return VJ->getKind() == DeclVisitKind;
1783 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1784 bool isFirst() const { return data[1] != nullptr; }
1786 class TypeLocVisit : public VisitorJob {
1788 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1789 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1790 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1792 static bool classof(const VisitorJob *VJ) {
1793 return VJ->getKind() == TypeLocVisitKind;
1796 TypeLoc get() const {
1797 QualType T = QualType::getFromOpaquePtr(data[0]);
1798 return TypeLoc(T, const_cast<void *>(data[1]));
1802 class LabelRefVisit : public VisitorJob {
1804 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1805 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1806 labelLoc.getPtrEncoding()) {}
1808 static bool classof(const VisitorJob *VJ) {
1809 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1811 const LabelDecl *get() const {
1812 return static_cast<const LabelDecl *>(data[0]);
1814 SourceLocation getLoc() const {
1815 return SourceLocation::getFromPtrEncoding(data[1]); }
1818 class NestedNameSpecifierLocVisit : public VisitorJob {
1820 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1821 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1822 Qualifier.getNestedNameSpecifier(),
1823 Qualifier.getOpaqueData()) { }
1825 static bool classof(const VisitorJob *VJ) {
1826 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1829 NestedNameSpecifierLoc get() const {
1830 return NestedNameSpecifierLoc(
1831 const_cast<NestedNameSpecifier *>(
1832 static_cast<const NestedNameSpecifier *>(data[0])),
1833 const_cast<void *>(data[1]));
1837 class DeclarationNameInfoVisit : public VisitorJob {
1839 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1840 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1841 static bool classof(const VisitorJob *VJ) {
1842 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1844 DeclarationNameInfo get() const {
1845 const Stmt *S = static_cast<const Stmt *>(data[0]);
1846 switch (S->getStmtClass()) {
1848 llvm_unreachable("Unhandled Stmt");
1849 case clang::Stmt::MSDependentExistsStmtClass:
1850 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1851 case Stmt::CXXDependentScopeMemberExprClass:
1852 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1853 case Stmt::DependentScopeDeclRefExprClass:
1854 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1855 case Stmt::OMPCriticalDirectiveClass:
1856 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1860 class MemberRefVisit : public VisitorJob {
1862 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1863 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1864 L.getPtrEncoding()) {}
1865 static bool classof(const VisitorJob *VJ) {
1866 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1868 const FieldDecl *get() const {
1869 return static_cast<const FieldDecl *>(data[0]);
1871 SourceLocation getLoc() const {
1872 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1875 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1876 friend class OMPClauseEnqueue;
1877 VisitorWorkList &WL;
1880 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1881 : WL(wl), Parent(parent) {}
1883 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1884 void VisitBlockExpr(const BlockExpr *B);
1885 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1886 void VisitCompoundStmt(const CompoundStmt *S);
1887 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1888 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1889 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1890 void VisitCXXNewExpr(const CXXNewExpr *E);
1891 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1892 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1893 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1894 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1895 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1896 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1897 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1898 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1899 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1900 void VisitDeclRefExpr(const DeclRefExpr *D);
1901 void VisitDeclStmt(const DeclStmt *S);
1902 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1903 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1904 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1905 void VisitForStmt(const ForStmt *FS);
1906 void VisitGotoStmt(const GotoStmt *GS);
1907 void VisitIfStmt(const IfStmt *If);
1908 void VisitInitListExpr(const InitListExpr *IE);
1909 void VisitMemberExpr(const MemberExpr *M);
1910 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1911 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1912 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1913 void VisitOverloadExpr(const OverloadExpr *E);
1914 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1915 void VisitStmt(const Stmt *S);
1916 void VisitSwitchStmt(const SwitchStmt *S);
1917 void VisitWhileStmt(const WhileStmt *W);
1918 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1919 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1920 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1921 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1922 void VisitVAArgExpr(const VAArgExpr *E);
1923 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1924 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1925 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1926 void VisitLambdaExpr(const LambdaExpr *E);
1927 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1928 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1929 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1930 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1931 void VisitOMPForDirective(const OMPForDirective *D);
1932 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1933 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1934 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1935 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1936 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1937 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1938 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1939 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1940 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1941 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1942 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1943 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1944 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1945 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1947 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1948 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1949 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1950 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1951 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1952 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1953 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1954 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
1955 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
1956 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
1958 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
1959 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1960 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
1961 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
1962 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
1965 void AddDeclarationNameInfo(const Stmt *S);
1966 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1967 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1968 unsigned NumTemplateArgs);
1969 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1970 void AddStmt(const Stmt *S);
1971 void AddDecl(const Decl *D, bool isFirst = true);
1972 void AddTypeLoc(TypeSourceInfo *TI);
1973 void EnqueueChildren(const Stmt *S);
1974 void EnqueueChildren(const OMPClause *S);
1976 } // end anonyous namespace
1978 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1979 // 'S' should always be non-null, since it comes from the
1980 // statement we are visiting.
1981 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1985 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1987 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1990 void EnqueueVisitor::AddStmt(const Stmt *S) {
1992 WL.push_back(StmtVisit(S, Parent));
1994 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1996 WL.push_back(DeclVisit(D, Parent, isFirst));
1998 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1999 unsigned NumTemplateArgs) {
2000 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2002 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2004 WL.push_back(MemberRefVisit(D, L, Parent));
2006 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2008 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2010 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2011 unsigned size = WL.size();
2012 for (const Stmt *SubStmt : S->children()) {
2015 if (size == WL.size())
2017 // Now reverse the entries we just added. This will match the DFS
2018 // ordering performed by the worklist.
2019 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2023 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2024 EnqueueVisitor *Visitor;
2025 /// \brief Process clauses with list of variables.
2026 template <typename T>
2027 void VisitOMPClauseList(T *Node);
2029 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2030 #define OPENMP_CLAUSE(Name, Class) \
2031 void Visit##Class(const Class *C);
2032 #include "clang/Basic/OpenMPKinds.def"
2033 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2034 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2037 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2038 const OMPClauseWithPreInit *C) {
2039 Visitor->AddStmt(C->getPreInitStmt());
2042 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2043 const OMPClauseWithPostUpdate *C) {
2044 Visitor->AddStmt(C->getPostUpdateExpr());
2047 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2048 Visitor->AddStmt(C->getCondition());
2051 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2052 Visitor->AddStmt(C->getCondition());
2055 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2056 Visitor->AddStmt(C->getNumThreads());
2059 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2060 Visitor->AddStmt(C->getSafelen());
2063 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2064 Visitor->AddStmt(C->getSimdlen());
2067 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2068 Visitor->AddStmt(C->getNumForLoops());
2071 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2073 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2075 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2076 VisitOMPClauseWithPreInit(C);
2077 Visitor->AddStmt(C->getChunkSize());
2080 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2081 Visitor->AddStmt(C->getNumForLoops());
2084 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2086 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2088 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2090 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2092 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2094 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2096 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2098 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2100 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2102 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2104 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2106 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2107 Visitor->AddStmt(C->getDevice());
2110 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2111 Visitor->AddStmt(C->getNumTeams());
2114 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2115 Visitor->AddStmt(C->getThreadLimit());
2118 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2119 Visitor->AddStmt(C->getPriority());
2122 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2123 Visitor->AddStmt(C->getGrainsize());
2126 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2127 Visitor->AddStmt(C->getNumTasks());
2130 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2131 Visitor->AddStmt(C->getHint());
2134 template<typename T>
2135 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2136 for (const auto *I : Node->varlists()) {
2137 Visitor->AddStmt(I);
2141 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2142 VisitOMPClauseList(C);
2143 for (const auto *E : C->private_copies()) {
2144 Visitor->AddStmt(E);
2147 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2148 const OMPFirstprivateClause *C) {
2149 VisitOMPClauseList(C);
2150 VisitOMPClauseWithPreInit(C);
2151 for (const auto *E : C->private_copies()) {
2152 Visitor->AddStmt(E);
2154 for (const auto *E : C->inits()) {
2155 Visitor->AddStmt(E);
2158 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2159 const OMPLastprivateClause *C) {
2160 VisitOMPClauseList(C);
2161 VisitOMPClauseWithPreInit(C);
2162 VisitOMPClauseWithPostUpdate(C);
2163 for (auto *E : C->private_copies()) {
2164 Visitor->AddStmt(E);
2166 for (auto *E : C->source_exprs()) {
2167 Visitor->AddStmt(E);
2169 for (auto *E : C->destination_exprs()) {
2170 Visitor->AddStmt(E);
2172 for (auto *E : C->assignment_ops()) {
2173 Visitor->AddStmt(E);
2176 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2177 VisitOMPClauseList(C);
2179 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2180 VisitOMPClauseList(C);
2181 for (auto *E : C->privates()) {
2182 Visitor->AddStmt(E);
2184 for (auto *E : C->lhs_exprs()) {
2185 Visitor->AddStmt(E);
2187 for (auto *E : C->rhs_exprs()) {
2188 Visitor->AddStmt(E);
2190 for (auto *E : C->reduction_ops()) {
2191 Visitor->AddStmt(E);
2194 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2195 VisitOMPClauseList(C);
2196 for (const auto *E : C->privates()) {
2197 Visitor->AddStmt(E);
2199 for (const auto *E : C->inits()) {
2200 Visitor->AddStmt(E);
2202 for (const auto *E : C->updates()) {
2203 Visitor->AddStmt(E);
2205 for (const auto *E : C->finals()) {
2206 Visitor->AddStmt(E);
2208 Visitor->AddStmt(C->getStep());
2209 Visitor->AddStmt(C->getCalcStep());
2211 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2212 VisitOMPClauseList(C);
2213 Visitor->AddStmt(C->getAlignment());
2215 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2216 VisitOMPClauseList(C);
2217 for (auto *E : C->source_exprs()) {
2218 Visitor->AddStmt(E);
2220 for (auto *E : C->destination_exprs()) {
2221 Visitor->AddStmt(E);
2223 for (auto *E : C->assignment_ops()) {
2224 Visitor->AddStmt(E);
2228 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2229 VisitOMPClauseList(C);
2230 for (auto *E : C->source_exprs()) {
2231 Visitor->AddStmt(E);
2233 for (auto *E : C->destination_exprs()) {
2234 Visitor->AddStmt(E);
2236 for (auto *E : C->assignment_ops()) {
2237 Visitor->AddStmt(E);
2240 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2241 VisitOMPClauseList(C);
2243 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2244 VisitOMPClauseList(C);
2246 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2247 VisitOMPClauseList(C);
2249 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2250 const OMPDistScheduleClause *C) {
2251 VisitOMPClauseWithPreInit(C);
2252 Visitor->AddStmt(C->getChunkSize());
2254 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2255 const OMPDefaultmapClause * /*C*/) {}
2258 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2259 unsigned size = WL.size();
2260 OMPClauseEnqueue Visitor(this);
2262 if (size == WL.size())
2264 // Now reverse the entries we just added. This will match the DFS
2265 // ordering performed by the worklist.
2266 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2269 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2270 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2272 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2273 AddDecl(B->getBlockDecl());
2275 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2277 AddTypeLoc(E->getTypeSourceInfo());
2279 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2280 for (auto &I : llvm::reverse(S->body()))
2283 void EnqueueVisitor::
2284 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2285 AddStmt(S->getSubStmt());
2286 AddDeclarationNameInfo(S);
2287 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2288 AddNestedNameSpecifierLoc(QualifierLoc);
2291 void EnqueueVisitor::
2292 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2293 if (E->hasExplicitTemplateArgs())
2294 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2295 AddDeclarationNameInfo(E);
2296 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2297 AddNestedNameSpecifierLoc(QualifierLoc);
2298 if (!E->isImplicitAccess())
2299 AddStmt(E->getBase());
2301 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2302 // Enqueue the initializer , if any.
2303 AddStmt(E->getInitializer());
2304 // Enqueue the array size, if any.
2305 AddStmt(E->getArraySize());
2306 // Enqueue the allocated type.
2307 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2308 // Enqueue the placement arguments.
2309 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2310 AddStmt(E->getPlacementArg(I-1));
2312 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2313 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2314 AddStmt(CE->getArg(I-1));
2315 AddStmt(CE->getCallee());
2316 AddStmt(CE->getArg(0));
2318 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2319 const CXXPseudoDestructorExpr *E) {
2320 // Visit the name of the type being destroyed.
2321 AddTypeLoc(E->getDestroyedTypeInfo());
2322 // Visit the scope type that looks disturbingly like the nested-name-specifier
2324 AddTypeLoc(E->getScopeTypeInfo());
2325 // Visit the nested-name-specifier.
2326 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2327 AddNestedNameSpecifierLoc(QualifierLoc);
2328 // Visit base expression.
2329 AddStmt(E->getBase());
2331 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2332 const CXXScalarValueInitExpr *E) {
2333 AddTypeLoc(E->getTypeSourceInfo());
2335 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2336 const CXXTemporaryObjectExpr *E) {
2338 AddTypeLoc(E->getTypeSourceInfo());
2340 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2342 if (E->isTypeOperand())
2343 AddTypeLoc(E->getTypeOperandSourceInfo());
2346 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2347 const CXXUnresolvedConstructExpr *E) {
2349 AddTypeLoc(E->getTypeSourceInfo());
2351 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2353 if (E->isTypeOperand())
2354 AddTypeLoc(E->getTypeOperandSourceInfo());
2357 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2359 AddDecl(S->getExceptionDecl());
2362 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2363 AddStmt(S->getBody());
2364 AddStmt(S->getRangeInit());
2365 AddDecl(S->getLoopVariable());
2368 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2369 if (DR->hasExplicitTemplateArgs())
2370 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2371 WL.push_back(DeclRefExprParts(DR, Parent));
2373 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2374 const DependentScopeDeclRefExpr *E) {
2375 if (E->hasExplicitTemplateArgs())
2376 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2377 AddDeclarationNameInfo(E);
2378 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2380 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2381 unsigned size = WL.size();
2382 bool isFirst = true;
2383 for (const auto *D : S->decls()) {
2384 AddDecl(D, isFirst);
2387 if (size == WL.size())
2389 // Now reverse the entries we just added. This will match the DFS
2390 // ordering performed by the worklist.
2391 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2394 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2395 AddStmt(E->getInit());
2396 for (DesignatedInitExpr::const_reverse_designators_iterator
2397 D = E->designators_rbegin(), DEnd = E->designators_rend();
2399 if (D->isFieldDesignator()) {
2400 if (FieldDecl *Field = D->getField())
2401 AddMemberRef(Field, D->getFieldLoc());
2404 if (D->isArrayDesignator()) {
2405 AddStmt(E->getArrayIndex(*D));
2408 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2409 AddStmt(E->getArrayRangeEnd(*D));
2410 AddStmt(E->getArrayRangeStart(*D));
2413 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2415 AddTypeLoc(E->getTypeInfoAsWritten());
2417 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2418 AddStmt(FS->getBody());
2419 AddStmt(FS->getInc());
2420 AddStmt(FS->getCond());
2421 AddDecl(FS->getConditionVariable());
2422 AddStmt(FS->getInit());
2424 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2425 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2427 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2428 AddStmt(If->getElse());
2429 AddStmt(If->getThen());
2430 AddStmt(If->getCond());
2431 AddDecl(If->getConditionVariable());
2433 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2434 // We care about the syntactic form of the initializer list, only.
2435 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2437 EnqueueChildren(IE);
2439 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2440 WL.push_back(MemberExprParts(M, Parent));
2442 // If the base of the member access expression is an implicit 'this', don't
2444 // FIXME: If we ever want to show these implicit accesses, this will be
2445 // unfortunate. However, clang_getCursor() relies on this behavior.
2446 if (M->isImplicitAccess())
2449 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2450 // real field that that we are interested in.
2451 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2452 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2453 if (FD->isAnonymousStructOrUnion()) {
2454 AddStmt(SubME->getBase());
2460 AddStmt(M->getBase());
2462 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2463 AddTypeLoc(E->getEncodedTypeSourceInfo());
2465 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2467 AddTypeLoc(M->getClassReceiverTypeInfo());
2469 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2470 // Visit the components of the offsetof expression.
2471 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2472 const OffsetOfNode &Node = E->getComponent(I-1);
2473 switch (Node.getKind()) {
2474 case OffsetOfNode::Array:
2475 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2477 case OffsetOfNode::Field:
2478 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2480 case OffsetOfNode::Identifier:
2481 case OffsetOfNode::Base:
2485 // Visit the type into which we're computing the offset.
2486 AddTypeLoc(E->getTypeSourceInfo());
2488 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2489 if (E->hasExplicitTemplateArgs())
2490 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2491 WL.push_back(OverloadExprParts(E, Parent));
2493 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2494 const UnaryExprOrTypeTraitExpr *E) {
2496 if (E->isArgumentType())
2497 AddTypeLoc(E->getArgumentTypeInfo());
2499 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2502 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2503 AddStmt(S->getBody());
2504 AddStmt(S->getCond());
2505 AddDecl(S->getConditionVariable());
2508 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2509 AddStmt(W->getBody());
2510 AddStmt(W->getCond());
2511 AddDecl(W->getConditionVariable());
2514 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2515 for (unsigned I = E->getNumArgs(); I > 0; --I)
2516 AddTypeLoc(E->getArg(I-1));
2519 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2520 AddTypeLoc(E->getQueriedTypeSourceInfo());
2523 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2527 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2528 VisitOverloadExpr(U);
2529 if (!U->isImplicitAccess())
2530 AddStmt(U->getBase());
2532 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2533 AddStmt(E->getSubExpr());
2534 AddTypeLoc(E->getWrittenTypeInfo());
2536 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2537 WL.push_back(SizeOfPackExprParts(E, Parent));
2539 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2540 // If the opaque value has a source expression, just transparently
2541 // visit that. This is useful for (e.g.) pseudo-object expressions.
2542 if (Expr *SourceExpr = E->getSourceExpr())
2543 return Visit(SourceExpr);
2545 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2546 AddStmt(E->getBody());
2547 WL.push_back(LambdaExprParts(E, Parent));
2549 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2550 // Treat the expression like its syntactic form.
2551 Visit(E->getSyntacticForm());
2554 void EnqueueVisitor::VisitOMPExecutableDirective(
2555 const OMPExecutableDirective *D) {
2557 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2558 E = D->clauses().end();
2560 EnqueueChildren(*I);
2563 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2564 VisitOMPExecutableDirective(D);
2567 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2568 VisitOMPExecutableDirective(D);
2571 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2572 VisitOMPLoopDirective(D);
2575 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2576 VisitOMPLoopDirective(D);
2579 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2580 VisitOMPLoopDirective(D);
2583 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2584 VisitOMPExecutableDirective(D);
2587 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2588 VisitOMPExecutableDirective(D);
2591 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2592 VisitOMPExecutableDirective(D);
2595 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2596 VisitOMPExecutableDirective(D);
2599 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2600 VisitOMPExecutableDirective(D);
2601 AddDeclarationNameInfo(D);
2605 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2606 VisitOMPLoopDirective(D);
2609 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2610 const OMPParallelForSimdDirective *D) {
2611 VisitOMPLoopDirective(D);
2614 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2615 const OMPParallelSectionsDirective *D) {
2616 VisitOMPExecutableDirective(D);
2619 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2620 VisitOMPExecutableDirective(D);
2624 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2625 VisitOMPExecutableDirective(D);
2628 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2629 VisitOMPExecutableDirective(D);
2632 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2633 VisitOMPExecutableDirective(D);
2636 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2637 const OMPTaskgroupDirective *D) {
2638 VisitOMPExecutableDirective(D);
2641 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2642 VisitOMPExecutableDirective(D);
2645 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2646 VisitOMPExecutableDirective(D);
2649 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2650 VisitOMPExecutableDirective(D);
2653 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2654 VisitOMPExecutableDirective(D);
2657 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2658 OMPTargetDataDirective *D) {
2659 VisitOMPExecutableDirective(D);
2662 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2663 const OMPTargetEnterDataDirective *D) {
2664 VisitOMPExecutableDirective(D);
2667 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2668 const OMPTargetExitDataDirective *D) {
2669 VisitOMPExecutableDirective(D);
2672 void EnqueueVisitor::VisitOMPTargetParallelDirective(
2673 const OMPTargetParallelDirective *D) {
2674 VisitOMPExecutableDirective(D);
2677 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2678 const OMPTargetParallelForDirective *D) {
2679 VisitOMPLoopDirective(D);
2682 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2683 VisitOMPExecutableDirective(D);
2686 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2687 const OMPCancellationPointDirective *D) {
2688 VisitOMPExecutableDirective(D);
2691 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2692 VisitOMPExecutableDirective(D);
2695 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2696 VisitOMPLoopDirective(D);
2699 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2700 const OMPTaskLoopSimdDirective *D) {
2701 VisitOMPLoopDirective(D);
2704 void EnqueueVisitor::VisitOMPDistributeDirective(
2705 const OMPDistributeDirective *D) {
2706 VisitOMPLoopDirective(D);
2709 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2710 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2713 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2714 if (RegionOfInterest.isValid()) {
2715 SourceRange Range = getRawCursorExtent(C);
2716 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2722 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2723 while (!WL.empty()) {
2724 // Dequeue the worklist item.
2725 VisitorJob LI = WL.pop_back_val();
2727 // Set the Parent field, then back to its old value once we're done.
2728 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2730 switch (LI.getKind()) {
2731 case VisitorJob::DeclVisitKind: {
2732 const Decl *D = cast<DeclVisit>(&LI)->get();
2736 // For now, perform default visitation for Decls.
2737 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2738 cast<DeclVisit>(&LI)->isFirst())))
2743 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2744 for (const TemplateArgumentLoc &Arg :
2745 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2746 if (VisitTemplateArgumentLoc(Arg))
2751 case VisitorJob::TypeLocVisitKind: {
2752 // Perform default visitation for TypeLocs.
2753 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2757 case VisitorJob::LabelRefVisitKind: {
2758 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2759 if (LabelStmt *stmt = LS->getStmt()) {
2760 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2768 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2769 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2770 if (VisitNestedNameSpecifierLoc(V->get()))
2775 case VisitorJob::DeclarationNameInfoVisitKind: {
2776 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2781 case VisitorJob::MemberRefVisitKind: {
2782 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2783 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2787 case VisitorJob::StmtVisitKind: {
2788 const Stmt *S = cast<StmtVisit>(&LI)->get();
2792 // Update the current cursor.
2793 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2794 if (!IsInRegionOfInterest(Cursor))
2796 switch (Visitor(Cursor, Parent, ClientData)) {
2797 case CXChildVisit_Break: return true;
2798 case CXChildVisit_Continue: break;
2799 case CXChildVisit_Recurse:
2800 if (PostChildrenVisitor)
2801 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2802 EnqueueWorkList(WL, S);
2807 case VisitorJob::MemberExprPartsKind: {
2808 // Handle the other pieces in the MemberExpr besides the base.
2809 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2811 // Visit the nested-name-specifier
2812 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2813 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2816 // Visit the declaration name.
2817 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2820 // Visit the explicitly-specified template arguments, if any.
2821 if (M->hasExplicitTemplateArgs()) {
2822 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2823 *ArgEnd = Arg + M->getNumTemplateArgs();
2824 Arg != ArgEnd; ++Arg) {
2825 if (VisitTemplateArgumentLoc(*Arg))
2831 case VisitorJob::DeclRefExprPartsKind: {
2832 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2833 // Visit nested-name-specifier, if present.
2834 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2835 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2837 // Visit declaration name.
2838 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2842 case VisitorJob::OverloadExprPartsKind: {
2843 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2844 // Visit the nested-name-specifier.
2845 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2846 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2848 // Visit the declaration name.
2849 if (VisitDeclarationNameInfo(O->getNameInfo()))
2851 // Visit the overloaded declaration reference.
2852 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2856 case VisitorJob::SizeOfPackExprPartsKind: {
2857 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2858 NamedDecl *Pack = E->getPack();
2859 if (isa<TemplateTypeParmDecl>(Pack)) {
2860 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2861 E->getPackLoc(), TU)))
2867 if (isa<TemplateTemplateParmDecl>(Pack)) {
2868 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2869 E->getPackLoc(), TU)))
2875 // Non-type template parameter packs and function parameter packs are
2876 // treated like DeclRefExpr cursors.
2880 case VisitorJob::LambdaExprPartsKind: {
2882 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2883 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2884 CEnd = E->explicit_capture_end();
2886 // FIXME: Lambda init-captures.
2887 if (!C->capturesVariable())
2890 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2896 // Visit parameters and return type, if present.
2897 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2898 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2899 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2900 // Visit the whole type.
2903 } else if (FunctionProtoTypeLoc Proto =
2904 TL.getAs<FunctionProtoTypeLoc>()) {
2905 if (E->hasExplicitParameters()) {
2906 // Visit parameters.
2907 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2908 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2911 // Visit result type.
2912 if (Visit(Proto.getReturnLoc()))
2920 case VisitorJob::PostChildrenVisitKind:
2921 if (PostChildrenVisitor(Parent, ClientData))
2929 bool CursorVisitor::Visit(const Stmt *S) {
2930 VisitorWorkList *WL = nullptr;
2931 if (!WorkListFreeList.empty()) {
2932 WL = WorkListFreeList.back();
2934 WorkListFreeList.pop_back();
2937 WL = new VisitorWorkList();
2938 WorkListCache.push_back(WL);
2940 EnqueueWorkList(*WL, S);
2941 bool result = RunVisitorWorkList(*WL);
2942 WorkListFreeList.push_back(WL);
2947 typedef SmallVector<SourceRange, 4> RefNamePieces;
2948 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2949 const DeclarationNameInfo &NI, SourceRange QLoc,
2950 const SourceRange *TemplateArgsLoc = nullptr) {
2951 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2952 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2953 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2955 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2957 RefNamePieces Pieces;
2959 if (WantQualifier && QLoc.isValid())
2960 Pieces.push_back(QLoc);
2962 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2963 Pieces.push_back(NI.getLoc());
2965 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
2966 Pieces.push_back(*TemplateArgsLoc);
2968 if (Kind == DeclarationName::CXXOperatorName) {
2969 Pieces.push_back(SourceLocation::getFromRawEncoding(
2970 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2971 Pieces.push_back(SourceLocation::getFromRawEncoding(
2972 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2975 if (WantSinglePiece) {
2976 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2978 Pieces.push_back(R);
2985 //===----------------------------------------------------------------------===//
2987 //===----------------------------------------------------------------------===//
2989 static void fatal_error_handler(void *user_data, const std::string& reason,
2990 bool gen_crash_diag) {
2991 // Write the result out to stderr avoiding errs() because raw_ostreams can
2992 // call report_fatal_error.
2993 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2998 struct RegisterFatalErrorHandler {
2999 RegisterFatalErrorHandler() {
3000 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3005 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3008 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3009 int displayDiagnostics) {
3010 // We use crash recovery to make some of our APIs more reliable, implicitly
3012 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3013 llvm::CrashRecoveryContext::Enable();
3015 // Look through the managed static to trigger construction of the managed
3016 // static which registers our fatal error handler. This ensures it is only
3018 (void)*RegisterFatalErrorHandlerOnce;
3020 // Initialize targets for clang module support.
3021 llvm::InitializeAllTargets();
3022 llvm::InitializeAllTargetMCs();
3023 llvm::InitializeAllAsmPrinters();
3024 llvm::InitializeAllAsmParsers();
3026 CIndexer *CIdxr = new CIndexer();
3028 if (excludeDeclarationsFromPCH)
3029 CIdxr->setOnlyLocalDecls();
3030 if (displayDiagnostics)
3031 CIdxr->setDisplayDiagnostics();
3033 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3034 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3035 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3036 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3037 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3038 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3043 void clang_disposeIndex(CXIndex CIdx) {
3045 delete static_cast<CIndexer *>(CIdx);
3048 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3050 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3053 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3055 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3059 void clang_toggleCrashRecovery(unsigned isEnabled) {
3061 llvm::CrashRecoveryContext::Enable();
3063 llvm::CrashRecoveryContext::Disable();
3066 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3067 const char *ast_filename) {
3068 CXTranslationUnit TU;
3069 enum CXErrorCode Result =
3070 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3072 assert((TU && Result == CXError_Success) ||
3073 (!TU && Result != CXError_Success));
3077 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3078 const char *ast_filename,
3079 CXTranslationUnit *out_TU) {
3083 if (!CIdx || !ast_filename || !out_TU)
3084 return CXError_InvalidArguments;
3087 *Log << ast_filename;
3090 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3091 FileSystemOptions FileSystemOpts;
3093 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3094 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3095 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3096 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
3097 FileSystemOpts, /*UseDebugInfo=*/false,
3098 CXXIdx->getOnlyLocalDecls(), None,
3099 /*CaptureDiagnostics=*/true,
3100 /*AllowPCHWithCompilerErrors=*/true,
3101 /*UserFilesAreVolatile=*/true);
3102 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
3103 return *out_TU ? CXError_Success : CXError_Failure;
3106 unsigned clang_defaultEditingTranslationUnitOptions() {
3107 return CXTranslationUnit_PrecompiledPreamble |
3108 CXTranslationUnit_CacheCompletionResults;
3112 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3113 const char *source_filename,
3114 int num_command_line_args,
3115 const char * const *command_line_args,
3116 unsigned num_unsaved_files,
3117 struct CXUnsavedFile *unsaved_files) {
3118 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3119 return clang_parseTranslationUnit(CIdx, source_filename,
3120 command_line_args, num_command_line_args,
3121 unsaved_files, num_unsaved_files,
3126 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3127 const char *const *command_line_args,
3128 int num_command_line_args,
3129 ArrayRef<CXUnsavedFile> unsaved_files,
3130 unsigned options, CXTranslationUnit *out_TU) {
3131 // Set up the initial return values.
3136 if (!CIdx || !out_TU)
3137 return CXError_InvalidArguments;
3139 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3141 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3142 setThreadBackgroundPriority();
3144 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3145 bool CreatePreambleOnFirstParse =
3146 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3147 // FIXME: Add a flag for modules.
3148 TranslationUnitKind TUKind
3149 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3150 bool CacheCodeCompletionResults
3151 = options & CXTranslationUnit_CacheCompletionResults;
3152 bool IncludeBriefCommentsInCodeCompletion
3153 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3154 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3155 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3157 // Configure the diagnostics.
3158 IntrusiveRefCntPtr<DiagnosticsEngine>
3159 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3161 if (options & CXTranslationUnit_KeepGoing)
3162 Diags->setFatalsAsError(true);
3164 // Recover resources if we crash before exiting this function.
3165 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3166 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3167 DiagCleanup(Diags.get());
3169 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3170 new std::vector<ASTUnit::RemappedFile>());
3172 // Recover resources if we crash before exiting this function.
3173 llvm::CrashRecoveryContextCleanupRegistrar<
3174 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3176 for (auto &UF : unsaved_files) {
3177 std::unique_ptr<llvm::MemoryBuffer> MB =
3178 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3179 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3182 std::unique_ptr<std::vector<const char *>> Args(
3183 new std::vector<const char *>());
3185 // Recover resources if we crash before exiting this method.
3186 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3187 ArgsCleanup(Args.get());
3189 // Since the Clang C library is primarily used by batch tools dealing with
3190 // (often very broken) source code, where spell-checking can have a
3191 // significant negative impact on performance (particularly when
3192 // precompiled headers are involved), we disable it by default.
3193 // Only do this if we haven't found a spell-checking-related argument.
3194 bool FoundSpellCheckingArgument = false;
3195 for (int I = 0; I != num_command_line_args; ++I) {
3196 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3197 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3198 FoundSpellCheckingArgument = true;
3202 Args->insert(Args->end(), command_line_args,
3203 command_line_args + num_command_line_args);
3205 if (!FoundSpellCheckingArgument)
3206 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3208 // The 'source_filename' argument is optional. If the caller does not
3209 // specify it then it is assumed that the source file is specified
3210 // in the actual argument list.
3211 // Put the source file after command_line_args otherwise if '-x' flag is
3212 // present it will be unused.
3213 if (source_filename)
3214 Args->push_back(source_filename);
3216 // Do we need the detailed preprocessing record?
3217 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3218 Args->push_back("-Xclang");
3219 Args->push_back("-detailed-preprocessing-record");
3222 unsigned NumErrors = Diags->getClient()->getNumErrors();
3223 std::unique_ptr<ASTUnit> ErrUnit;
3224 // Unless the user specified that they want the preamble on the first parse
3225 // set it up to be created on the first reparse. This makes the first parse
3226 // faster, trading for a slower (first) reparse.
3227 unsigned PrecompilePreambleAfterNParses =
3228 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3229 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3230 Args->data(), Args->data() + Args->size(),
3231 CXXIdx->getPCHContainerOperations(), Diags,
3232 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3233 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3234 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3235 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3236 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3237 /*UserFilesAreVolatile=*/true, ForSerialization,
3238 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3241 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3242 if (!Unit && !ErrUnit)
3243 return CXError_ASTReadError;
3245 if (NumErrors != Diags->getClient()->getNumErrors()) {
3246 // Make sure to check that 'Unit' is non-NULL.
3247 if (CXXIdx->getDisplayDiagnostics())
3248 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3251 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3252 return CXError_ASTReadError;
3254 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3255 return *out_TU ? CXError_Success : CXError_Failure;
3259 clang_parseTranslationUnit(CXIndex CIdx,
3260 const char *source_filename,
3261 const char *const *command_line_args,
3262 int num_command_line_args,
3263 struct CXUnsavedFile *unsaved_files,
3264 unsigned num_unsaved_files,
3266 CXTranslationUnit TU;
3267 enum CXErrorCode Result = clang_parseTranslationUnit2(
3268 CIdx, source_filename, command_line_args, num_command_line_args,
3269 unsaved_files, num_unsaved_files, options, &TU);
3271 assert((TU && Result == CXError_Success) ||
3272 (!TU && Result != CXError_Success));
3276 enum CXErrorCode clang_parseTranslationUnit2(
3277 CXIndex CIdx, const char *source_filename,
3278 const char *const *command_line_args, int num_command_line_args,
3279 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3280 unsigned options, CXTranslationUnit *out_TU) {
3281 SmallVector<const char *, 4> Args;
3282 Args.push_back("clang");
3283 Args.append(command_line_args, command_line_args + num_command_line_args);
3284 return clang_parseTranslationUnit2FullArgv(
3285 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3286 num_unsaved_files, options, out_TU);
3289 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3290 CXIndex CIdx, const char *source_filename,
3291 const char *const *command_line_args, int num_command_line_args,
3292 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3293 unsigned options, CXTranslationUnit *out_TU) {
3295 *Log << source_filename << ": ";
3296 for (int i = 0; i != num_command_line_args; ++i)
3297 *Log << command_line_args[i] << " ";
3300 if (num_unsaved_files && !unsaved_files)
3301 return CXError_InvalidArguments;
3303 CXErrorCode result = CXError_Failure;
3304 auto ParseTranslationUnitImpl = [=, &result] {
3305 result = clang_parseTranslationUnit_Impl(
3306 CIdx, source_filename, command_line_args, num_command_line_args,
3307 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3309 llvm::CrashRecoveryContext CRC;
3311 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3312 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3313 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3314 fprintf(stderr, " 'command_line_args' : [");
3315 for (int i = 0; i != num_command_line_args; ++i) {
3317 fprintf(stderr, ", ");
3318 fprintf(stderr, "'%s'", command_line_args[i]);
3320 fprintf(stderr, "],\n");
3321 fprintf(stderr, " 'unsaved_files' : [");
3322 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3324 fprintf(stderr, ", ");
3325 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3326 unsaved_files[i].Length);
3328 fprintf(stderr, "],\n");
3329 fprintf(stderr, " 'options' : %d,\n", options);
3330 fprintf(stderr, "}\n");
3332 return CXError_Crashed;
3333 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3334 if (CXTranslationUnit *TU = out_TU)
3335 PrintLibclangResourceUsage(*TU);
3341 CXString clang_Type_getObjCEncoding(CXType CT) {
3342 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3343 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3344 std::string encoding;
3345 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3348 return cxstring::createDup(encoding);
3351 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3352 if (C.kind == CXCursor_MacroDefinition) {
3353 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3354 return MDR->getName();
3355 } else if (C.kind == CXCursor_MacroExpansion) {
3356 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3357 return ME.getName();
3362 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3363 const IdentifierInfo *II = getMacroIdentifier(C);
3367 ASTUnit *ASTU = getCursorASTUnit(C);
3368 Preprocessor &PP = ASTU->getPreprocessor();
3369 if (const MacroInfo *MI = PP.getMacroInfo(II))
3370 return MI->isFunctionLike();
3374 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3375 const IdentifierInfo *II = getMacroIdentifier(C);
3379 ASTUnit *ASTU = getCursorASTUnit(C);
3380 Preprocessor &PP = ASTU->getPreprocessor();
3381 if (const MacroInfo *MI = PP.getMacroInfo(II))
3382 return MI->isBuiltinMacro();
3386 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3387 const Decl *D = getCursorDecl(C);
3388 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3392 return FD->isInlined();
3395 static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3396 if (callExpr->getNumArgs() != 1) {
3400 StringLiteral *S = nullptr;
3401 auto *arg = callExpr->getArg(0);
3402 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3403 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3404 auto *subExpr = I->getSubExprAsWritten();
3406 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3410 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3411 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3412 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3420 CXEvalResultKind EvalType;
3428 void clang_EvalResult_dispose(CXEvalResult E) {
3429 ExprEvalResult *ER = (ExprEvalResult *)E;
3431 CXEvalResultKind evalType = ER->EvalType;
3433 if (evalType != CXEval_UnExposed && evalType != CXEval_Float &&
3434 evalType != CXEval_Int && ER->EvalData.stringVal) {
3435 free((void *) ER->EvalData.stringVal);
3441 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3443 return CXEval_UnExposed;
3445 return ((ExprEvalResult *)E)->EvalType;
3448 int clang_EvalResult_getAsInt(CXEvalResult E) {
3452 return ((ExprEvalResult *)E)->EvalData.intVal;
3455 double clang_EvalResult_getAsDouble(CXEvalResult E) {
3459 return ((ExprEvalResult *)E)->EvalData.floatVal;
3462 const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3466 return ((ExprEvalResult *)E)->EvalData.stringVal;
3469 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3470 Expr::EvalResult ER;
3471 ASTContext &ctx = getCursorContext(C);
3475 expr = expr->IgnoreParens();
3476 bool res = expr->EvaluateAsRValue(ER, ctx);
3479 ExprEvalResult *result = (ExprEvalResult *) malloc(sizeof(ExprEvalResult));
3483 result->EvalType = CXEval_UnExposed;
3487 if (ER.Val.isInt()) {
3488 result->EvalType = CXEval_Int;
3489 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3491 } else if (ER.Val.isFloat()) {
3493 llvm::SmallVector<char, 100> Buffer;
3494 ER.Val.getFloat().toString(Buffer);
3495 std::string floatStr(Buffer.data(), Buffer.size());
3496 result->EvalType = CXEval_Float;
3498 llvm::APFloat apFloat = ER.Val.getFloat();
3499 apFloat.convert(llvm::APFloat::IEEEdouble,
3500 llvm::APFloat::rmNearestTiesToEven, &ignored);
3501 result->EvalData.floatVal = apFloat.convertToDouble();
3504 } else if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3506 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3507 auto *subExpr = I->getSubExprAsWritten();
3508 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3509 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3511 const StringLiteral *StrE = nullptr;
3512 const ObjCStringLiteral *ObjCExpr;
3513 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3516 StrE = ObjCExpr->getString();
3517 result->EvalType = CXEval_ObjCStrLiteral;
3519 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3520 result->EvalType = CXEval_StrLiteral;
3523 std::string strRef(StrE->getString().str());
3524 result->EvalData.stringVal = (char *)malloc(strRef.size()+1);
3525 strncpy((char*)result->EvalData.stringVal, strRef.c_str(),
3527 result->EvalData.stringVal[strRef.size()] = '\0';
3531 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3532 expr->getStmtClass() == Stmt::StringLiteralClass) {
3534 const StringLiteral *StrE = nullptr;
3535 const ObjCStringLiteral *ObjCExpr;
3536 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3539 StrE = ObjCExpr->getString();
3540 result->EvalType = CXEval_ObjCStrLiteral;
3542 StrE = cast<StringLiteral>(expr);
3543 result->EvalType = CXEval_StrLiteral;
3546 std::string strRef(StrE->getString().str());
3547 result->EvalData.stringVal = (char *)malloc(strRef.size()+1);
3548 strncpy((char*)result->EvalData.stringVal, strRef.c_str(),
3550 result->EvalData.stringVal[strRef.size()] = '\0';
3553 } else if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3555 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3557 rettype = CC->getType();
3558 if (rettype.getAsString() == "CFStringRef" &&
3559 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3561 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3562 StringLiteral* S = getCFSTR_value(callExpr);
3564 std::string strLiteral(S->getString().str());
3565 result->EvalType = CXEval_CFStr;
3567 result->EvalData.stringVal = (char *)malloc(strLiteral.size()+1);
3568 strncpy((char*)result->EvalData.stringVal, strLiteral.c_str(),
3570 result->EvalData.stringVal[strLiteral.size()] = '\0';
3575 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3577 callExpr = static_cast<CallExpr *>(expr);
3578 rettype = callExpr->getCallReturnType(ctx);
3580 if (rettype->isVectorType() || callExpr->getNumArgs() > 1) {
3583 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3584 if(callExpr->getNumArgs() == 1 &&
3585 !callExpr->getArg(0)->getType()->isIntegralType(ctx)){
3589 } else if(rettype.getAsString() == "CFStringRef") {
3591 StringLiteral* S = getCFSTR_value(callExpr);
3593 std::string strLiteral(S->getString().str());
3594 result->EvalType = CXEval_CFStr;
3595 result->EvalData.stringVal = (char *)malloc(strLiteral.size()+1);
3596 strncpy((char*)result->EvalData.stringVal, strLiteral.c_str(),
3598 result->EvalData.stringVal[strLiteral.size()] = '\0';
3603 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3605 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3606 ValueDecl *V = D->getDecl();
3607 if (V->getKind() == Decl::Function) {
3608 std::string strName(V->getNameAsString());
3609 result->EvalType = CXEval_Other;
3610 result->EvalData.stringVal = (char *)malloc(strName.size()+1);
3611 strncpy((char*)result->EvalData.stringVal, strName.c_str(),
3613 result->EvalData.stringVal[strName.size()] = '\0';
3620 clang_EvalResult_dispose((CXEvalResult *)result);
3624 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3625 const Decl *D = getCursorDecl(C);
3627 const Expr *expr = nullptr;
3628 if (auto *Var = dyn_cast<VarDecl>(D)) {
3629 expr = Var->getInit();
3630 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3631 expr = Field->getInClassInitializer();
3634 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3635 evaluateExpr(const_cast<Expr *>(expr), C)));
3639 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3641 Expr *expr = nullptr;
3642 for (auto *bodyIterator : compoundStmt->body()) {
3643 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3648 return const_cast<CXEvalResult>(
3649 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3654 unsigned clang_Cursor_hasAttrs(CXCursor C) {
3655 const Decl *D = getCursorDecl(C);
3660 if (D->hasAttrs()) {
3666 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3667 return CXSaveTranslationUnit_None;
3670 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3671 const char *FileName,
3673 CIndexer *CXXIdx = TU->CIdx;
3674 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3675 setThreadBackgroundPriority();
3677 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3678 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3681 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3684 *Log << TU << ' ' << FileName;
3687 if (isNotUsableTU(TU)) {
3689 return CXSaveError_InvalidTU;
3692 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3693 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3694 if (!CXXUnit->hasSema())
3695 return CXSaveError_InvalidTU;
3698 auto SaveTranslationUnitImpl = [=, &result]() {
3699 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3702 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3703 getenv("LIBCLANG_NOTHREADS")) {
3704 SaveTranslationUnitImpl();
3706 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3707 PrintLibclangResourceUsage(TU);
3712 // We have an AST that has invalid nodes due to compiler errors.
3713 // Use a crash recovery thread for protection.
3715 llvm::CrashRecoveryContext CRC;
3717 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3718 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3719 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3720 fprintf(stderr, " 'options' : %d,\n", options);
3721 fprintf(stderr, "}\n");
3723 return CXSaveError_Unknown;
3725 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3726 PrintLibclangResourceUsage(TU);
3732 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3734 // If the translation unit has been marked as unsafe to free, just discard
3736 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3737 if (Unit && Unit->isUnsafeToFree())
3740 delete cxtu::getASTUnit(CTUnit);
3741 delete CTUnit->StringPool;
3742 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3743 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3744 delete CTUnit->CommentToXML;
3749 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3750 return CXReparse_None;
3754 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3755 ArrayRef<CXUnsavedFile> unsaved_files,
3758 if (isNotUsableTU(TU)) {
3760 return CXError_InvalidArguments;
3763 // Reset the associated diagnostics.
3764 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3765 TU->Diagnostics = nullptr;
3767 CIndexer *CXXIdx = TU->CIdx;
3768 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3769 setThreadBackgroundPriority();
3771 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3772 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3774 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3775 new std::vector<ASTUnit::RemappedFile>());
3777 // Recover resources if we crash before exiting this function.
3778 llvm::CrashRecoveryContextCleanupRegistrar<
3779 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3781 for (auto &UF : unsaved_files) {
3782 std::unique_ptr<llvm::MemoryBuffer> MB =
3783 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3784 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3787 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3788 *RemappedFiles.get()))
3789 return CXError_Success;
3790 if (isASTReadError(CXXUnit))
3791 return CXError_ASTReadError;
3792 return CXError_Failure;
3795 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3796 unsigned num_unsaved_files,
3797 struct CXUnsavedFile *unsaved_files,
3803 if (num_unsaved_files && !unsaved_files)
3804 return CXError_InvalidArguments;
3807 auto ReparseTranslationUnitImpl = [=, &result]() {
3808 result = clang_reparseTranslationUnit_Impl(
3809 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3812 if (getenv("LIBCLANG_NOTHREADS")) {
3813 ReparseTranslationUnitImpl();
3817 llvm::CrashRecoveryContext CRC;
3819 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3820 fprintf(stderr, "libclang: crash detected during reparsing\n");
3821 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3822 return CXError_Crashed;
3823 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3824 PrintLibclangResourceUsage(TU);
3830 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3831 if (isNotUsableTU(CTUnit)) {
3833 return cxstring::createEmpty();
3836 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3837 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3840 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3841 if (isNotUsableTU(TU)) {
3843 return clang_getNullCursor();
3846 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3847 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3850 } // end: extern "C"
3852 //===----------------------------------------------------------------------===//
3853 // CXFile Operations.
3854 //===----------------------------------------------------------------------===//
3857 CXString clang_getFileName(CXFile SFile) {
3859 return cxstring::createNull();
3861 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3862 return cxstring::createRef(FEnt->getName());
3865 time_t clang_getFileTime(CXFile SFile) {
3869 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3870 return FEnt->getModificationTime();
3873 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3874 if (isNotUsableTU(TU)) {
3879 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3881 FileManager &FMgr = CXXUnit->getFileManager();
3882 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3885 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3887 if (isNotUsableTU(TU)) {
3895 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3896 FileEntry *FEnt = static_cast<FileEntry *>(file);
3897 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3898 .isFileMultipleIncludeGuarded(FEnt);
3901 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3902 if (!file || !outID)
3905 FileEntry *FEnt = static_cast<FileEntry *>(file);
3906 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3907 outID->data[0] = ID.getDevice();
3908 outID->data[1] = ID.getFile();
3909 outID->data[2] = FEnt->getModificationTime();
3913 int clang_File_isEqual(CXFile file1, CXFile file2) {
3917 if (!file1 || !file2)
3920 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3921 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3922 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3925 } // end: extern "C"
3927 //===----------------------------------------------------------------------===//
3928 // CXCursor Operations.
3929 //===----------------------------------------------------------------------===//
3931 static const Decl *getDeclFromExpr(const Stmt *E) {
3932 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3933 return getDeclFromExpr(CE->getSubExpr());
3935 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3936 return RefExpr->getDecl();
3937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3938 return ME->getMemberDecl();
3939 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3940 return RE->getDecl();
3941 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3942 if (PRE->isExplicitProperty())
3943 return PRE->getExplicitProperty();
3944 // It could be messaging both getter and setter as in:
3946 // in which case prefer to associate the setter since it is less obvious
3947 // from inspecting the source that the setter is going to get called.
3948 if (PRE->isMessagingSetter())
3949 return PRE->getImplicitPropertySetter();
3950 return PRE->getImplicitPropertyGetter();
3952 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3953 return getDeclFromExpr(POE->getSyntacticForm());
3954 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3955 if (Expr *Src = OVE->getSourceExpr())
3956 return getDeclFromExpr(Src);
3958 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3959 return getDeclFromExpr(CE->getCallee());
3960 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3961 if (!CE->isElidable())
3962 return CE->getConstructor();
3963 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3964 return OME->getMethodDecl();
3966 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3967 return PE->getProtocol();
3968 if (const SubstNonTypeTemplateParmPackExpr *NTTP
3969 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3970 return NTTP->getParameterPack();
3971 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3972 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3973 isa<ParmVarDecl>(SizeOfPack->getPack()))
3974 return SizeOfPack->getPack();
3979 static SourceLocation getLocationFromExpr(const Expr *E) {
3980 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3981 return getLocationFromExpr(CE->getSubExpr());
3983 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3984 return /*FIXME:*/Msg->getLeftLoc();
3985 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3986 return DRE->getLocation();
3987 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3988 return Member->getMemberLoc();
3989 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3990 return Ivar->getLocation();
3991 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3992 return SizeOfPack->getPackLoc();
3993 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3994 return PropRef->getLocation();
3996 return E->getLocStart();
4001 unsigned clang_visitChildren(CXCursor parent,
4002 CXCursorVisitor visitor,
4003 CXClientData client_data) {
4004 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4005 /*VisitPreprocessorLast=*/false);
4006 return CursorVis.VisitChildren(parent);
4009 #ifndef __has_feature
4010 #define __has_feature(x) 0
4012 #if __has_feature(blocks)
4013 typedef enum CXChildVisitResult
4014 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4016 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4017 CXClientData client_data) {
4018 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4019 return block(cursor, parent);
4022 // If we are compiled with a compiler that doesn't have native blocks support,
4023 // define and call the block manually, so the
4024 typedef struct _CXChildVisitResult
4029 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4031 } *CXCursorVisitorBlock;
4033 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4034 CXClientData client_data) {
4035 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4036 return block->invoke(block, cursor, parent);
4041 unsigned clang_visitChildrenWithBlock(CXCursor parent,
4042 CXCursorVisitorBlock block) {
4043 return clang_visitChildren(parent, visitWithBlock, block);
4046 static CXString getDeclSpelling(const Decl *D) {
4048 return cxstring::createEmpty();
4050 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4052 if (const ObjCPropertyImplDecl *PropImpl =
4053 dyn_cast<ObjCPropertyImplDecl>(D))
4054 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4055 return cxstring::createDup(Property->getIdentifier()->getName());
4057 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4058 if (Module *Mod = ImportD->getImportedModule())
4059 return cxstring::createDup(Mod->getFullModuleName());
4061 return cxstring::createEmpty();
4064 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4065 return cxstring::createDup(OMD->getSelector().getAsString());
4067 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4068 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4069 // and returns different names. NamedDecl returns the class name and
4070 // ObjCCategoryImplDecl returns the category name.
4071 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4073 if (isa<UsingDirectiveDecl>(D))
4074 return cxstring::createEmpty();
4076 SmallString<1024> S;
4077 llvm::raw_svector_ostream os(S);
4080 return cxstring::createDup(os.str());
4083 CXString clang_getCursorSpelling(CXCursor C) {
4084 if (clang_isTranslationUnit(C.kind))
4085 return clang_getTranslationUnitSpelling(getCursorTU(C));
4087 if (clang_isReference(C.kind)) {
4089 case CXCursor_ObjCSuperClassRef: {
4090 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4091 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4093 case CXCursor_ObjCClassRef: {
4094 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4095 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4097 case CXCursor_ObjCProtocolRef: {
4098 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4099 assert(OID && "getCursorSpelling(): Missing protocol decl");
4100 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4102 case CXCursor_CXXBaseSpecifier: {
4103 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4104 return cxstring::createDup(B->getType().getAsString());
4106 case CXCursor_TypeRef: {
4107 const TypeDecl *Type = getCursorTypeRef(C).first;
4108 assert(Type && "Missing type decl");
4110 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4113 case CXCursor_TemplateRef: {
4114 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4115 assert(Template && "Missing template decl");
4117 return cxstring::createDup(Template->getNameAsString());
4120 case CXCursor_NamespaceRef: {
4121 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4122 assert(NS && "Missing namespace decl");
4124 return cxstring::createDup(NS->getNameAsString());
4127 case CXCursor_MemberRef: {
4128 const FieldDecl *Field = getCursorMemberRef(C).first;
4129 assert(Field && "Missing member decl");
4131 return cxstring::createDup(Field->getNameAsString());
4134 case CXCursor_LabelRef: {
4135 const LabelStmt *Label = getCursorLabelRef(C).first;
4136 assert(Label && "Missing label");
4138 return cxstring::createRef(Label->getName());
4141 case CXCursor_OverloadedDeclRef: {
4142 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4143 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4144 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4145 return cxstring::createDup(ND->getNameAsString());
4146 return cxstring::createEmpty();
4148 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4149 return cxstring::createDup(E->getName().getAsString());
4150 OverloadedTemplateStorage *Ovl
4151 = Storage.get<OverloadedTemplateStorage*>();
4152 if (Ovl->size() == 0)
4153 return cxstring::createEmpty();
4154 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4157 case CXCursor_VariableRef: {
4158 const VarDecl *Var = getCursorVariableRef(C).first;
4159 assert(Var && "Missing variable decl");
4161 return cxstring::createDup(Var->getNameAsString());
4165 return cxstring::createRef("<not implemented>");
4169 if (clang_isExpression(C.kind)) {
4170 const Expr *E = getCursorExpr(C);
4172 if (C.kind == CXCursor_ObjCStringLiteral ||
4173 C.kind == CXCursor_StringLiteral) {
4174 const StringLiteral *SLit;
4175 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4176 SLit = OSL->getString();
4178 SLit = cast<StringLiteral>(E);
4180 SmallString<256> Buf;
4181 llvm::raw_svector_ostream OS(Buf);
4182 SLit->outputString(OS);
4183 return cxstring::createDup(OS.str());
4186 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4188 return getDeclSpelling(D);
4189 return cxstring::createEmpty();
4192 if (clang_isStatement(C.kind)) {
4193 const Stmt *S = getCursorStmt(C);
4194 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4195 return cxstring::createRef(Label->getName());
4197 return cxstring::createEmpty();
4200 if (C.kind == CXCursor_MacroExpansion)
4201 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4204 if (C.kind == CXCursor_MacroDefinition)
4205 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4208 if (C.kind == CXCursor_InclusionDirective)
4209 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4211 if (clang_isDeclaration(C.kind))
4212 return getDeclSpelling(getCursorDecl(C));
4214 if (C.kind == CXCursor_AnnotateAttr) {
4215 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4216 return cxstring::createDup(AA->getAnnotation());
4219 if (C.kind == CXCursor_AsmLabelAttr) {
4220 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4221 return cxstring::createDup(AA->getLabel());
4224 if (C.kind == CXCursor_PackedAttr) {
4225 return cxstring::createRef("packed");
4228 if (C.kind == CXCursor_VisibilityAttr) {
4229 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4230 switch (AA->getVisibility()) {
4231 case VisibilityAttr::VisibilityType::Default:
4232 return cxstring::createRef("default");
4233 case VisibilityAttr::VisibilityType::Hidden:
4234 return cxstring::createRef("hidden");
4235 case VisibilityAttr::VisibilityType::Protected:
4236 return cxstring::createRef("protected");
4238 llvm_unreachable("unknown visibility type");
4241 return cxstring::createEmpty();
4244 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4245 unsigned pieceIndex,
4247 if (clang_Cursor_isNull(C))
4248 return clang_getNullRange();
4250 ASTContext &Ctx = getCursorContext(C);
4252 if (clang_isStatement(C.kind)) {
4253 const Stmt *S = getCursorStmt(C);
4254 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4256 return clang_getNullRange();
4257 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4260 return clang_getNullRange();
4263 if (C.kind == CXCursor_ObjCMessageExpr) {
4264 if (const ObjCMessageExpr *
4265 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4266 if (pieceIndex >= ME->getNumSelectorLocs())
4267 return clang_getNullRange();
4268 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4272 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4273 C.kind == CXCursor_ObjCClassMethodDecl) {
4274 if (const ObjCMethodDecl *
4275 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4276 if (pieceIndex >= MD->getNumSelectorLocs())
4277 return clang_getNullRange();
4278 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4282 if (C.kind == CXCursor_ObjCCategoryDecl ||
4283 C.kind == CXCursor_ObjCCategoryImplDecl) {
4285 return clang_getNullRange();
4286 if (const ObjCCategoryDecl *
4287 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4288 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4289 if (const ObjCCategoryImplDecl *
4290 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4291 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4294 if (C.kind == CXCursor_ModuleImportDecl) {
4296 return clang_getNullRange();
4297 if (const ImportDecl *ImportD =
4298 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4299 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4301 return cxloc::translateSourceRange(Ctx,
4302 SourceRange(Locs.front(), Locs.back()));
4304 return clang_getNullRange();
4307 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4308 C.kind == CXCursor_ConversionFunction) {
4310 return clang_getNullRange();
4311 if (const FunctionDecl *FD =
4312 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4313 DeclarationNameInfo FunctionName = FD->getNameInfo();
4314 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4316 return clang_getNullRange();
4319 // FIXME: A CXCursor_InclusionDirective should give the location of the
4320 // filename, but we don't keep track of this.
4322 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4323 // but we don't keep track of this.
4325 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4326 // but we don't keep track of this.
4328 // Default handling, give the location of the cursor.
4331 return clang_getNullRange();
4333 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4334 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4335 return cxloc::translateSourceRange(Ctx, Loc);
4338 CXString clang_Cursor_getMangling(CXCursor C) {
4339 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4340 return cxstring::createEmpty();
4342 // Mangling only works for functions and variables.
4343 const Decl *D = getCursorDecl(C);
4344 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4345 return cxstring::createEmpty();
4347 ASTContext &Ctx = D->getASTContext();
4348 index::CodegenNameGenerator CGNameGen(Ctx);
4349 return cxstring::createDup(CGNameGen.getName(D));
4352 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4353 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4356 const Decl *D = getCursorDecl(C);
4357 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4360 ASTContext &Ctx = D->getASTContext();
4361 index::CodegenNameGenerator CGNameGen(Ctx);
4362 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4363 return cxstring::createSet(Manglings);
4366 CXString clang_getCursorDisplayName(CXCursor C) {
4367 if (!clang_isDeclaration(C.kind))
4368 return clang_getCursorSpelling(C);
4370 const Decl *D = getCursorDecl(C);
4372 return cxstring::createEmpty();
4374 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4375 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4376 D = FunTmpl->getTemplatedDecl();
4378 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4379 SmallString<64> Str;
4380 llvm::raw_svector_ostream OS(Str);
4382 if (Function->getPrimaryTemplate())
4385 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4388 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4391 if (Function->isVariadic()) {
4392 if (Function->getNumParams())
4397 return cxstring::createDup(OS.str());
4400 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4401 SmallString<64> Str;
4402 llvm::raw_svector_ostream OS(Str);
4403 OS << *ClassTemplate;
4405 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4406 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4410 NamedDecl *Param = Params->getParam(I);
4411 if (Param->getIdentifier()) {
4412 OS << Param->getIdentifier()->getName();
4416 // There is no parameter name, which makes this tricky. Try to come up
4417 // with something useful that isn't too long.
4418 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4419 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4420 else if (NonTypeTemplateParmDecl *NTTP
4421 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4422 OS << NTTP->getType().getAsString(Policy);
4424 OS << "template<...> class";
4428 return cxstring::createDup(OS.str());
4431 if (const ClassTemplateSpecializationDecl *ClassSpec
4432 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4433 // If the type was explicitly written, use that.
4434 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4435 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
4437 SmallString<128> Str;
4438 llvm::raw_svector_ostream OS(Str);
4440 TemplateSpecializationType::PrintTemplateArgumentList(OS,
4441 ClassSpec->getTemplateArgs().data(),
4442 ClassSpec->getTemplateArgs().size(),
4444 return cxstring::createDup(OS.str());
4447 return clang_getCursorSpelling(C);
4450 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4452 case CXCursor_FunctionDecl:
4453 return cxstring::createRef("FunctionDecl");
4454 case CXCursor_TypedefDecl:
4455 return cxstring::createRef("TypedefDecl");
4456 case CXCursor_EnumDecl:
4457 return cxstring::createRef("EnumDecl");
4458 case CXCursor_EnumConstantDecl:
4459 return cxstring::createRef("EnumConstantDecl");
4460 case CXCursor_StructDecl:
4461 return cxstring::createRef("StructDecl");
4462 case CXCursor_UnionDecl:
4463 return cxstring::createRef("UnionDecl");
4464 case CXCursor_ClassDecl:
4465 return cxstring::createRef("ClassDecl");
4466 case CXCursor_FieldDecl:
4467 return cxstring::createRef("FieldDecl");
4468 case CXCursor_VarDecl:
4469 return cxstring::createRef("VarDecl");
4470 case CXCursor_ParmDecl:
4471 return cxstring::createRef("ParmDecl");
4472 case CXCursor_ObjCInterfaceDecl:
4473 return cxstring::createRef("ObjCInterfaceDecl");
4474 case CXCursor_ObjCCategoryDecl:
4475 return cxstring::createRef("ObjCCategoryDecl");
4476 case CXCursor_ObjCProtocolDecl:
4477 return cxstring::createRef("ObjCProtocolDecl");
4478 case CXCursor_ObjCPropertyDecl:
4479 return cxstring::createRef("ObjCPropertyDecl");
4480 case CXCursor_ObjCIvarDecl:
4481 return cxstring::createRef("ObjCIvarDecl");
4482 case CXCursor_ObjCInstanceMethodDecl:
4483 return cxstring::createRef("ObjCInstanceMethodDecl");
4484 case CXCursor_ObjCClassMethodDecl:
4485 return cxstring::createRef("ObjCClassMethodDecl");
4486 case CXCursor_ObjCImplementationDecl:
4487 return cxstring::createRef("ObjCImplementationDecl");
4488 case CXCursor_ObjCCategoryImplDecl:
4489 return cxstring::createRef("ObjCCategoryImplDecl");
4490 case CXCursor_CXXMethod:
4491 return cxstring::createRef("CXXMethod");
4492 case CXCursor_UnexposedDecl:
4493 return cxstring::createRef("UnexposedDecl");
4494 case CXCursor_ObjCSuperClassRef:
4495 return cxstring::createRef("ObjCSuperClassRef");
4496 case CXCursor_ObjCProtocolRef:
4497 return cxstring::createRef("ObjCProtocolRef");
4498 case CXCursor_ObjCClassRef:
4499 return cxstring::createRef("ObjCClassRef");
4500 case CXCursor_TypeRef:
4501 return cxstring::createRef("TypeRef");
4502 case CXCursor_TemplateRef:
4503 return cxstring::createRef("TemplateRef");
4504 case CXCursor_NamespaceRef:
4505 return cxstring::createRef("NamespaceRef");
4506 case CXCursor_MemberRef:
4507 return cxstring::createRef("MemberRef");
4508 case CXCursor_LabelRef:
4509 return cxstring::createRef("LabelRef");
4510 case CXCursor_OverloadedDeclRef:
4511 return cxstring::createRef("OverloadedDeclRef");
4512 case CXCursor_VariableRef:
4513 return cxstring::createRef("VariableRef");
4514 case CXCursor_IntegerLiteral:
4515 return cxstring::createRef("IntegerLiteral");
4516 case CXCursor_FloatingLiteral:
4517 return cxstring::createRef("FloatingLiteral");
4518 case CXCursor_ImaginaryLiteral:
4519 return cxstring::createRef("ImaginaryLiteral");
4520 case CXCursor_StringLiteral:
4521 return cxstring::createRef("StringLiteral");
4522 case CXCursor_CharacterLiteral:
4523 return cxstring::createRef("CharacterLiteral");
4524 case CXCursor_ParenExpr:
4525 return cxstring::createRef("ParenExpr");
4526 case CXCursor_UnaryOperator:
4527 return cxstring::createRef("UnaryOperator");
4528 case CXCursor_ArraySubscriptExpr:
4529 return cxstring::createRef("ArraySubscriptExpr");
4530 case CXCursor_OMPArraySectionExpr:
4531 return cxstring::createRef("OMPArraySectionExpr");
4532 case CXCursor_BinaryOperator:
4533 return cxstring::createRef("BinaryOperator");
4534 case CXCursor_CompoundAssignOperator:
4535 return cxstring::createRef("CompoundAssignOperator");
4536 case CXCursor_ConditionalOperator:
4537 return cxstring::createRef("ConditionalOperator");
4538 case CXCursor_CStyleCastExpr:
4539 return cxstring::createRef("CStyleCastExpr");
4540 case CXCursor_CompoundLiteralExpr:
4541 return cxstring::createRef("CompoundLiteralExpr");
4542 case CXCursor_InitListExpr:
4543 return cxstring::createRef("InitListExpr");
4544 case CXCursor_AddrLabelExpr:
4545 return cxstring::createRef("AddrLabelExpr");
4546 case CXCursor_StmtExpr:
4547 return cxstring::createRef("StmtExpr");
4548 case CXCursor_GenericSelectionExpr:
4549 return cxstring::createRef("GenericSelectionExpr");
4550 case CXCursor_GNUNullExpr:
4551 return cxstring::createRef("GNUNullExpr");
4552 case CXCursor_CXXStaticCastExpr:
4553 return cxstring::createRef("CXXStaticCastExpr");
4554 case CXCursor_CXXDynamicCastExpr:
4555 return cxstring::createRef("CXXDynamicCastExpr");
4556 case CXCursor_CXXReinterpretCastExpr:
4557 return cxstring::createRef("CXXReinterpretCastExpr");
4558 case CXCursor_CXXConstCastExpr:
4559 return cxstring::createRef("CXXConstCastExpr");
4560 case CXCursor_CXXFunctionalCastExpr:
4561 return cxstring::createRef("CXXFunctionalCastExpr");
4562 case CXCursor_CXXTypeidExpr:
4563 return cxstring::createRef("CXXTypeidExpr");
4564 case CXCursor_CXXBoolLiteralExpr:
4565 return cxstring::createRef("CXXBoolLiteralExpr");
4566 case CXCursor_CXXNullPtrLiteralExpr:
4567 return cxstring::createRef("CXXNullPtrLiteralExpr");
4568 case CXCursor_CXXThisExpr:
4569 return cxstring::createRef("CXXThisExpr");
4570 case CXCursor_CXXThrowExpr:
4571 return cxstring::createRef("CXXThrowExpr");
4572 case CXCursor_CXXNewExpr:
4573 return cxstring::createRef("CXXNewExpr");
4574 case CXCursor_CXXDeleteExpr:
4575 return cxstring::createRef("CXXDeleteExpr");
4576 case CXCursor_UnaryExpr:
4577 return cxstring::createRef("UnaryExpr");
4578 case CXCursor_ObjCStringLiteral:
4579 return cxstring::createRef("ObjCStringLiteral");
4580 case CXCursor_ObjCBoolLiteralExpr:
4581 return cxstring::createRef("ObjCBoolLiteralExpr");
4582 case CXCursor_ObjCSelfExpr:
4583 return cxstring::createRef("ObjCSelfExpr");
4584 case CXCursor_ObjCEncodeExpr:
4585 return cxstring::createRef("ObjCEncodeExpr");
4586 case CXCursor_ObjCSelectorExpr:
4587 return cxstring::createRef("ObjCSelectorExpr");
4588 case CXCursor_ObjCProtocolExpr:
4589 return cxstring::createRef("ObjCProtocolExpr");
4590 case CXCursor_ObjCBridgedCastExpr:
4591 return cxstring::createRef("ObjCBridgedCastExpr");
4592 case CXCursor_BlockExpr:
4593 return cxstring::createRef("BlockExpr");
4594 case CXCursor_PackExpansionExpr:
4595 return cxstring::createRef("PackExpansionExpr");
4596 case CXCursor_SizeOfPackExpr:
4597 return cxstring::createRef("SizeOfPackExpr");
4598 case CXCursor_LambdaExpr:
4599 return cxstring::createRef("LambdaExpr");
4600 case CXCursor_UnexposedExpr:
4601 return cxstring::createRef("UnexposedExpr");
4602 case CXCursor_DeclRefExpr:
4603 return cxstring::createRef("DeclRefExpr");
4604 case CXCursor_MemberRefExpr:
4605 return cxstring::createRef("MemberRefExpr");
4606 case CXCursor_CallExpr:
4607 return cxstring::createRef("CallExpr");
4608 case CXCursor_ObjCMessageExpr:
4609 return cxstring::createRef("ObjCMessageExpr");
4610 case CXCursor_UnexposedStmt:
4611 return cxstring::createRef("UnexposedStmt");
4612 case CXCursor_DeclStmt:
4613 return cxstring::createRef("DeclStmt");
4614 case CXCursor_LabelStmt:
4615 return cxstring::createRef("LabelStmt");
4616 case CXCursor_CompoundStmt:
4617 return cxstring::createRef("CompoundStmt");
4618 case CXCursor_CaseStmt:
4619 return cxstring::createRef("CaseStmt");
4620 case CXCursor_DefaultStmt:
4621 return cxstring::createRef("DefaultStmt");
4622 case CXCursor_IfStmt:
4623 return cxstring::createRef("IfStmt");
4624 case CXCursor_SwitchStmt:
4625 return cxstring::createRef("SwitchStmt");
4626 case CXCursor_WhileStmt:
4627 return cxstring::createRef("WhileStmt");
4628 case CXCursor_DoStmt:
4629 return cxstring::createRef("DoStmt");
4630 case CXCursor_ForStmt:
4631 return cxstring::createRef("ForStmt");
4632 case CXCursor_GotoStmt:
4633 return cxstring::createRef("GotoStmt");
4634 case CXCursor_IndirectGotoStmt:
4635 return cxstring::createRef("IndirectGotoStmt");
4636 case CXCursor_ContinueStmt:
4637 return cxstring::createRef("ContinueStmt");
4638 case CXCursor_BreakStmt:
4639 return cxstring::createRef("BreakStmt");
4640 case CXCursor_ReturnStmt:
4641 return cxstring::createRef("ReturnStmt");
4642 case CXCursor_GCCAsmStmt:
4643 return cxstring::createRef("GCCAsmStmt");
4644 case CXCursor_MSAsmStmt:
4645 return cxstring::createRef("MSAsmStmt");
4646 case CXCursor_ObjCAtTryStmt:
4647 return cxstring::createRef("ObjCAtTryStmt");
4648 case CXCursor_ObjCAtCatchStmt:
4649 return cxstring::createRef("ObjCAtCatchStmt");
4650 case CXCursor_ObjCAtFinallyStmt:
4651 return cxstring::createRef("ObjCAtFinallyStmt");
4652 case CXCursor_ObjCAtThrowStmt:
4653 return cxstring::createRef("ObjCAtThrowStmt");
4654 case CXCursor_ObjCAtSynchronizedStmt:
4655 return cxstring::createRef("ObjCAtSynchronizedStmt");
4656 case CXCursor_ObjCAutoreleasePoolStmt:
4657 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4658 case CXCursor_ObjCForCollectionStmt:
4659 return cxstring::createRef("ObjCForCollectionStmt");
4660 case CXCursor_CXXCatchStmt:
4661 return cxstring::createRef("CXXCatchStmt");
4662 case CXCursor_CXXTryStmt:
4663 return cxstring::createRef("CXXTryStmt");
4664 case CXCursor_CXXForRangeStmt:
4665 return cxstring::createRef("CXXForRangeStmt");
4666 case CXCursor_SEHTryStmt:
4667 return cxstring::createRef("SEHTryStmt");
4668 case CXCursor_SEHExceptStmt:
4669 return cxstring::createRef("SEHExceptStmt");
4670 case CXCursor_SEHFinallyStmt:
4671 return cxstring::createRef("SEHFinallyStmt");
4672 case CXCursor_SEHLeaveStmt:
4673 return cxstring::createRef("SEHLeaveStmt");
4674 case CXCursor_NullStmt:
4675 return cxstring::createRef("NullStmt");
4676 case CXCursor_InvalidFile:
4677 return cxstring::createRef("InvalidFile");
4678 case CXCursor_InvalidCode:
4679 return cxstring::createRef("InvalidCode");
4680 case CXCursor_NoDeclFound:
4681 return cxstring::createRef("NoDeclFound");
4682 case CXCursor_NotImplemented:
4683 return cxstring::createRef("NotImplemented");
4684 case CXCursor_TranslationUnit:
4685 return cxstring::createRef("TranslationUnit");
4686 case CXCursor_UnexposedAttr:
4687 return cxstring::createRef("UnexposedAttr");
4688 case CXCursor_IBActionAttr:
4689 return cxstring::createRef("attribute(ibaction)");
4690 case CXCursor_IBOutletAttr:
4691 return cxstring::createRef("attribute(iboutlet)");
4692 case CXCursor_IBOutletCollectionAttr:
4693 return cxstring::createRef("attribute(iboutletcollection)");
4694 case CXCursor_CXXFinalAttr:
4695 return cxstring::createRef("attribute(final)");
4696 case CXCursor_CXXOverrideAttr:
4697 return cxstring::createRef("attribute(override)");
4698 case CXCursor_AnnotateAttr:
4699 return cxstring::createRef("attribute(annotate)");
4700 case CXCursor_AsmLabelAttr:
4701 return cxstring::createRef("asm label");
4702 case CXCursor_PackedAttr:
4703 return cxstring::createRef("attribute(packed)");
4704 case CXCursor_PureAttr:
4705 return cxstring::createRef("attribute(pure)");
4706 case CXCursor_ConstAttr:
4707 return cxstring::createRef("attribute(const)");
4708 case CXCursor_NoDuplicateAttr:
4709 return cxstring::createRef("attribute(noduplicate)");
4710 case CXCursor_CUDAConstantAttr:
4711 return cxstring::createRef("attribute(constant)");
4712 case CXCursor_CUDADeviceAttr:
4713 return cxstring::createRef("attribute(device)");
4714 case CXCursor_CUDAGlobalAttr:
4715 return cxstring::createRef("attribute(global)");
4716 case CXCursor_CUDAHostAttr:
4717 return cxstring::createRef("attribute(host)");
4718 case CXCursor_CUDASharedAttr:
4719 return cxstring::createRef("attribute(shared)");
4720 case CXCursor_VisibilityAttr:
4721 return cxstring::createRef("attribute(visibility)");
4722 case CXCursor_DLLExport:
4723 return cxstring::createRef("attribute(dllexport)");
4724 case CXCursor_DLLImport:
4725 return cxstring::createRef("attribute(dllimport)");
4726 case CXCursor_PreprocessingDirective:
4727 return cxstring::createRef("preprocessing directive");
4728 case CXCursor_MacroDefinition:
4729 return cxstring::createRef("macro definition");
4730 case CXCursor_MacroExpansion:
4731 return cxstring::createRef("macro expansion");
4732 case CXCursor_InclusionDirective:
4733 return cxstring::createRef("inclusion directive");
4734 case CXCursor_Namespace:
4735 return cxstring::createRef("Namespace");
4736 case CXCursor_LinkageSpec:
4737 return cxstring::createRef("LinkageSpec");
4738 case CXCursor_CXXBaseSpecifier:
4739 return cxstring::createRef("C++ base class specifier");
4740 case CXCursor_Constructor:
4741 return cxstring::createRef("CXXConstructor");
4742 case CXCursor_Destructor:
4743 return cxstring::createRef("CXXDestructor");
4744 case CXCursor_ConversionFunction:
4745 return cxstring::createRef("CXXConversion");
4746 case CXCursor_TemplateTypeParameter:
4747 return cxstring::createRef("TemplateTypeParameter");
4748 case CXCursor_NonTypeTemplateParameter:
4749 return cxstring::createRef("NonTypeTemplateParameter");
4750 case CXCursor_TemplateTemplateParameter:
4751 return cxstring::createRef("TemplateTemplateParameter");
4752 case CXCursor_FunctionTemplate:
4753 return cxstring::createRef("FunctionTemplate");
4754 case CXCursor_ClassTemplate:
4755 return cxstring::createRef("ClassTemplate");
4756 case CXCursor_ClassTemplatePartialSpecialization:
4757 return cxstring::createRef("ClassTemplatePartialSpecialization");
4758 case CXCursor_NamespaceAlias:
4759 return cxstring::createRef("NamespaceAlias");
4760 case CXCursor_UsingDirective:
4761 return cxstring::createRef("UsingDirective");
4762 case CXCursor_UsingDeclaration:
4763 return cxstring::createRef("UsingDeclaration");
4764 case CXCursor_TypeAliasDecl:
4765 return cxstring::createRef("TypeAliasDecl");
4766 case CXCursor_ObjCSynthesizeDecl:
4767 return cxstring::createRef("ObjCSynthesizeDecl");
4768 case CXCursor_ObjCDynamicDecl:
4769 return cxstring::createRef("ObjCDynamicDecl");
4770 case CXCursor_CXXAccessSpecifier:
4771 return cxstring::createRef("CXXAccessSpecifier");
4772 case CXCursor_ModuleImportDecl:
4773 return cxstring::createRef("ModuleImport");
4774 case CXCursor_OMPParallelDirective:
4775 return cxstring::createRef("OMPParallelDirective");
4776 case CXCursor_OMPSimdDirective:
4777 return cxstring::createRef("OMPSimdDirective");
4778 case CXCursor_OMPForDirective:
4779 return cxstring::createRef("OMPForDirective");
4780 case CXCursor_OMPForSimdDirective:
4781 return cxstring::createRef("OMPForSimdDirective");
4782 case CXCursor_OMPSectionsDirective:
4783 return cxstring::createRef("OMPSectionsDirective");
4784 case CXCursor_OMPSectionDirective:
4785 return cxstring::createRef("OMPSectionDirective");
4786 case CXCursor_OMPSingleDirective:
4787 return cxstring::createRef("OMPSingleDirective");
4788 case CXCursor_OMPMasterDirective:
4789 return cxstring::createRef("OMPMasterDirective");
4790 case CXCursor_OMPCriticalDirective:
4791 return cxstring::createRef("OMPCriticalDirective");
4792 case CXCursor_OMPParallelForDirective:
4793 return cxstring::createRef("OMPParallelForDirective");
4794 case CXCursor_OMPParallelForSimdDirective:
4795 return cxstring::createRef("OMPParallelForSimdDirective");
4796 case CXCursor_OMPParallelSectionsDirective:
4797 return cxstring::createRef("OMPParallelSectionsDirective");
4798 case CXCursor_OMPTaskDirective:
4799 return cxstring::createRef("OMPTaskDirective");
4800 case CXCursor_OMPTaskyieldDirective:
4801 return cxstring::createRef("OMPTaskyieldDirective");
4802 case CXCursor_OMPBarrierDirective:
4803 return cxstring::createRef("OMPBarrierDirective");
4804 case CXCursor_OMPTaskwaitDirective:
4805 return cxstring::createRef("OMPTaskwaitDirective");
4806 case CXCursor_OMPTaskgroupDirective:
4807 return cxstring::createRef("OMPTaskgroupDirective");
4808 case CXCursor_OMPFlushDirective:
4809 return cxstring::createRef("OMPFlushDirective");
4810 case CXCursor_OMPOrderedDirective:
4811 return cxstring::createRef("OMPOrderedDirective");
4812 case CXCursor_OMPAtomicDirective:
4813 return cxstring::createRef("OMPAtomicDirective");
4814 case CXCursor_OMPTargetDirective:
4815 return cxstring::createRef("OMPTargetDirective");
4816 case CXCursor_OMPTargetDataDirective:
4817 return cxstring::createRef("OMPTargetDataDirective");
4818 case CXCursor_OMPTargetEnterDataDirective:
4819 return cxstring::createRef("OMPTargetEnterDataDirective");
4820 case CXCursor_OMPTargetExitDataDirective:
4821 return cxstring::createRef("OMPTargetExitDataDirective");
4822 case CXCursor_OMPTargetParallelDirective:
4823 return cxstring::createRef("OMPTargetParallelDirective");
4824 case CXCursor_OMPTargetParallelForDirective:
4825 return cxstring::createRef("OMPTargetParallelForDirective");
4826 case CXCursor_OMPTeamsDirective:
4827 return cxstring::createRef("OMPTeamsDirective");
4828 case CXCursor_OMPCancellationPointDirective:
4829 return cxstring::createRef("OMPCancellationPointDirective");
4830 case CXCursor_OMPCancelDirective:
4831 return cxstring::createRef("OMPCancelDirective");
4832 case CXCursor_OMPTaskLoopDirective:
4833 return cxstring::createRef("OMPTaskLoopDirective");
4834 case CXCursor_OMPTaskLoopSimdDirective:
4835 return cxstring::createRef("OMPTaskLoopSimdDirective");
4836 case CXCursor_OMPDistributeDirective:
4837 return cxstring::createRef("OMPDistributeDirective");
4838 case CXCursor_OverloadCandidate:
4839 return cxstring::createRef("OverloadCandidate");
4840 case CXCursor_TypeAliasTemplateDecl:
4841 return cxstring::createRef("TypeAliasTemplateDecl");
4844 llvm_unreachable("Unhandled CXCursorKind");
4847 struct GetCursorData {
4848 SourceLocation TokenBeginLoc;
4849 bool PointsAtMacroArgExpansion;
4850 bool VisitedObjCPropertyImplDecl;
4851 SourceLocation VisitedDeclaratorDeclStartLoc;
4852 CXCursor &BestCursor;
4854 GetCursorData(SourceManager &SM,
4855 SourceLocation tokenBegin, CXCursor &outputCursor)
4856 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4857 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4858 VisitedObjCPropertyImplDecl = false;
4862 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4864 CXClientData client_data) {
4865 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4866 CXCursor *BestCursor = &Data->BestCursor;
4868 // If we point inside a macro argument we should provide info of what the
4869 // token is so use the actual cursor, don't replace it with a macro expansion
4871 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4872 return CXChildVisit_Recurse;
4874 if (clang_isDeclaration(cursor.kind)) {
4875 // Avoid having the implicit methods override the property decls.
4876 if (const ObjCMethodDecl *MD
4877 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4878 if (MD->isImplicit())
4879 return CXChildVisit_Break;
4881 } else if (const ObjCInterfaceDecl *ID
4882 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4883 // Check that when we have multiple @class references in the same line,
4884 // that later ones do not override the previous ones.
4887 // source ranges for both start at '@', so 'Bar' will end up overriding
4888 // 'Foo' even though the cursor location was at 'Foo'.
4889 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4890 BestCursor->kind == CXCursor_ObjCClassRef)
4891 if (const ObjCInterfaceDecl *PrevID
4892 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4894 !PrevID->isThisDeclarationADefinition() &&
4895 !ID->isThisDeclarationADefinition())
4896 return CXChildVisit_Break;
4899 } else if (const DeclaratorDecl *DD
4900 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4901 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4902 // Check that when we have multiple declarators in the same line,
4903 // that later ones do not override the previous ones.
4906 // source ranges for both start at 'int', so 'Bar' will end up overriding
4907 // 'Foo' even though the cursor location was at 'Foo'.
4908 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4909 return CXChildVisit_Break;
4910 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4912 } else if (const ObjCPropertyImplDecl *PropImp
4913 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4915 // Check that when we have multiple @synthesize in the same line,
4916 // that later ones do not override the previous ones.
4918 // @synthesize Foo, Bar;
4919 // source ranges for both start at '@', so 'Bar' will end up overriding
4920 // 'Foo' even though the cursor location was at 'Foo'.
4921 if (Data->VisitedObjCPropertyImplDecl)
4922 return CXChildVisit_Break;
4923 Data->VisitedObjCPropertyImplDecl = true;
4927 if (clang_isExpression(cursor.kind) &&
4928 clang_isDeclaration(BestCursor->kind)) {
4929 if (const Decl *D = getCursorDecl(*BestCursor)) {
4930 // Avoid having the cursor of an expression replace the declaration cursor
4931 // when the expression source range overlaps the declaration range.
4932 // This can happen for C++ constructor expressions whose range generally
4933 // include the variable declaration, e.g.:
4934 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4935 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4936 D->getLocation() == Data->TokenBeginLoc)
4937 return CXChildVisit_Break;
4941 // If our current best cursor is the construction of a temporary object,
4942 // don't replace that cursor with a type reference, because we want
4943 // clang_getCursor() to point at the constructor.
4944 if (clang_isExpression(BestCursor->kind) &&
4945 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4946 cursor.kind == CXCursor_TypeRef) {
4947 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4948 // as having the actual point on the type reference.
4949 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4950 return CXChildVisit_Recurse;
4953 // If we already have an Objective-C superclass reference, don't
4954 // update it further.
4955 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4956 return CXChildVisit_Break;
4958 *BestCursor = cursor;
4959 return CXChildVisit_Recurse;
4962 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4963 if (isNotUsableTU(TU)) {
4965 return clang_getNullCursor();
4968 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4969 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4971 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4972 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4976 unsigned SearchLine, SearchColumn;
4978 unsigned ResultLine, ResultColumn;
4979 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4980 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4981 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4983 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4985 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4986 &ResultColumn, nullptr);
4987 SearchFileName = clang_getFileName(SearchFile);
4988 ResultFileName = clang_getFileName(ResultFile);
4989 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4990 USR = clang_getCursorUSR(Result);
4991 *Log << llvm::format("(%s:%d:%d) = %s",
4992 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4993 clang_getCString(KindSpelling))
4994 << llvm::format("(%s:%d:%d):%s%s",
4995 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4996 clang_getCString(USR), IsDef);
4997 clang_disposeString(SearchFileName);
4998 clang_disposeString(ResultFileName);
4999 clang_disposeString(KindSpelling);
5000 clang_disposeString(USR);
5002 CXCursor Definition = clang_getCursorDefinition(Result);
5003 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5004 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5005 CXString DefinitionKindSpelling
5006 = clang_getCursorKindSpelling(Definition.kind);
5007 CXFile DefinitionFile;
5008 unsigned DefinitionLine, DefinitionColumn;
5009 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5010 &DefinitionLine, &DefinitionColumn, nullptr);
5011 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5012 *Log << llvm::format(" -> %s(%s:%d:%d)",
5013 clang_getCString(DefinitionKindSpelling),
5014 clang_getCString(DefinitionFileName),
5015 DefinitionLine, DefinitionColumn);
5016 clang_disposeString(DefinitionFileName);
5017 clang_disposeString(DefinitionKindSpelling);
5024 CXCursor clang_getNullCursor(void) {
5025 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5028 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5029 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5030 // can't set consistently. For example, when visiting a DeclStmt we will set
5031 // it but we don't set it on the result of clang_getCursorDefinition for
5032 // a reference of the same declaration.
5033 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5034 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5035 // to provide that kind of info.
5036 if (clang_isDeclaration(X.kind))
5037 X.data[1] = nullptr;
5038 if (clang_isDeclaration(Y.kind))
5039 Y.data[1] = nullptr;
5044 unsigned clang_hashCursor(CXCursor C) {
5046 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5049 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5050 std::make_pair(C.kind, C.data[Index]));
5053 unsigned clang_isInvalid(enum CXCursorKind K) {
5054 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5057 unsigned clang_isDeclaration(enum CXCursorKind K) {
5058 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5059 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5062 unsigned clang_isReference(enum CXCursorKind K) {
5063 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5066 unsigned clang_isExpression(enum CXCursorKind K) {
5067 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5070 unsigned clang_isStatement(enum CXCursorKind K) {
5071 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5074 unsigned clang_isAttribute(enum CXCursorKind K) {
5075 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5078 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5079 return K == CXCursor_TranslationUnit;
5082 unsigned clang_isPreprocessing(enum CXCursorKind K) {
5083 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5086 unsigned clang_isUnexposed(enum CXCursorKind K) {
5088 case CXCursor_UnexposedDecl:
5089 case CXCursor_UnexposedExpr:
5090 case CXCursor_UnexposedStmt:
5091 case CXCursor_UnexposedAttr:
5098 CXCursorKind clang_getCursorKind(CXCursor C) {
5102 CXSourceLocation clang_getCursorLocation(CXCursor C) {
5103 if (clang_isReference(C.kind)) {
5105 case CXCursor_ObjCSuperClassRef: {
5106 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5107 = getCursorObjCSuperClassRef(C);
5108 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5111 case CXCursor_ObjCProtocolRef: {
5112 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5113 = getCursorObjCProtocolRef(C);
5114 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5117 case CXCursor_ObjCClassRef: {
5118 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5119 = getCursorObjCClassRef(C);
5120 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5123 case CXCursor_TypeRef: {
5124 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5125 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5128 case CXCursor_TemplateRef: {
5129 std::pair<const TemplateDecl *, SourceLocation> P =
5130 getCursorTemplateRef(C);
5131 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5134 case CXCursor_NamespaceRef: {
5135 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5136 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5139 case CXCursor_MemberRef: {
5140 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5141 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5144 case CXCursor_VariableRef: {
5145 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5146 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5149 case CXCursor_CXXBaseSpecifier: {
5150 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5152 return clang_getNullLocation();
5154 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5155 return cxloc::translateSourceLocation(getCursorContext(C),
5156 TSInfo->getTypeLoc().getBeginLoc());
5158 return cxloc::translateSourceLocation(getCursorContext(C),
5159 BaseSpec->getLocStart());
5162 case CXCursor_LabelRef: {
5163 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5164 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5167 case CXCursor_OverloadedDeclRef:
5168 return cxloc::translateSourceLocation(getCursorContext(C),
5169 getCursorOverloadedDeclRef(C).second);
5172 // FIXME: Need a way to enumerate all non-reference cases.
5173 llvm_unreachable("Missed a reference kind");
5177 if (clang_isExpression(C.kind))
5178 return cxloc::translateSourceLocation(getCursorContext(C),
5179 getLocationFromExpr(getCursorExpr(C)));
5181 if (clang_isStatement(C.kind))
5182 return cxloc::translateSourceLocation(getCursorContext(C),
5183 getCursorStmt(C)->getLocStart());
5185 if (C.kind == CXCursor_PreprocessingDirective) {
5186 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5187 return cxloc::translateSourceLocation(getCursorContext(C), L);
5190 if (C.kind == CXCursor_MacroExpansion) {
5192 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5193 return cxloc::translateSourceLocation(getCursorContext(C), L);
5196 if (C.kind == CXCursor_MacroDefinition) {
5197 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5198 return cxloc::translateSourceLocation(getCursorContext(C), L);
5201 if (C.kind == CXCursor_InclusionDirective) {
5203 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5204 return cxloc::translateSourceLocation(getCursorContext(C), L);
5207 if (clang_isAttribute(C.kind)) {
5209 = cxcursor::getCursorAttr(C)->getLocation();
5210 return cxloc::translateSourceLocation(getCursorContext(C), L);
5213 if (!clang_isDeclaration(C.kind))
5214 return clang_getNullLocation();
5216 const Decl *D = getCursorDecl(C);
5218 return clang_getNullLocation();
5220 SourceLocation Loc = D->getLocation();
5221 // FIXME: Multiple variables declared in a single declaration
5222 // currently lack the information needed to correctly determine their
5223 // ranges when accounting for the type-specifier. We use context
5224 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5225 // and if so, whether it is the first decl.
5226 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5227 if (!cxcursor::isFirstInDeclGroup(C))
5228 Loc = VD->getLocation();
5231 // For ObjC methods, give the start location of the method name.
5232 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5233 Loc = MD->getSelectorStartLoc();
5235 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5240 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5243 // Guard against an invalid SourceLocation, or we may assert in one
5244 // of the following calls.
5245 if (SLoc.isInvalid())
5246 return clang_getNullCursor();
5248 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5250 // Translate the given source location to make it point at the beginning of
5251 // the token under the cursor.
5252 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5253 CXXUnit->getASTContext().getLangOpts());
5255 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5256 if (SLoc.isValid()) {
5257 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5258 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5259 /*VisitPreprocessorLast=*/true,
5260 /*VisitIncludedEntities=*/false,
5261 SourceLocation(SLoc));
5262 CursorVis.visitFileRegion();
5268 static SourceRange getRawCursorExtent(CXCursor C) {
5269 if (clang_isReference(C.kind)) {
5271 case CXCursor_ObjCSuperClassRef:
5272 return getCursorObjCSuperClassRef(C).second;
5274 case CXCursor_ObjCProtocolRef:
5275 return getCursorObjCProtocolRef(C).second;
5277 case CXCursor_ObjCClassRef:
5278 return getCursorObjCClassRef(C).second;
5280 case CXCursor_TypeRef:
5281 return getCursorTypeRef(C).second;
5283 case CXCursor_TemplateRef:
5284 return getCursorTemplateRef(C).second;
5286 case CXCursor_NamespaceRef:
5287 return getCursorNamespaceRef(C).second;
5289 case CXCursor_MemberRef:
5290 return getCursorMemberRef(C).second;
5292 case CXCursor_CXXBaseSpecifier:
5293 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5295 case CXCursor_LabelRef:
5296 return getCursorLabelRef(C).second;
5298 case CXCursor_OverloadedDeclRef:
5299 return getCursorOverloadedDeclRef(C).second;
5301 case CXCursor_VariableRef:
5302 return getCursorVariableRef(C).second;
5305 // FIXME: Need a way to enumerate all non-reference cases.
5306 llvm_unreachable("Missed a reference kind");
5310 if (clang_isExpression(C.kind))
5311 return getCursorExpr(C)->getSourceRange();
5313 if (clang_isStatement(C.kind))
5314 return getCursorStmt(C)->getSourceRange();
5316 if (clang_isAttribute(C.kind))
5317 return getCursorAttr(C)->getRange();
5319 if (C.kind == CXCursor_PreprocessingDirective)
5320 return cxcursor::getCursorPreprocessingDirective(C);
5322 if (C.kind == CXCursor_MacroExpansion) {
5323 ASTUnit *TU = getCursorASTUnit(C);
5324 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5325 return TU->mapRangeFromPreamble(Range);
5328 if (C.kind == CXCursor_MacroDefinition) {
5329 ASTUnit *TU = getCursorASTUnit(C);
5330 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5331 return TU->mapRangeFromPreamble(Range);
5334 if (C.kind == CXCursor_InclusionDirective) {
5335 ASTUnit *TU = getCursorASTUnit(C);
5336 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5337 return TU->mapRangeFromPreamble(Range);
5340 if (C.kind == CXCursor_TranslationUnit) {
5341 ASTUnit *TU = getCursorASTUnit(C);
5342 FileID MainID = TU->getSourceManager().getMainFileID();
5343 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5344 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5345 return SourceRange(Start, End);
5348 if (clang_isDeclaration(C.kind)) {
5349 const Decl *D = cxcursor::getCursorDecl(C);
5351 return SourceRange();
5353 SourceRange R = D->getSourceRange();
5354 // FIXME: Multiple variables declared in a single declaration
5355 // currently lack the information needed to correctly determine their
5356 // ranges when accounting for the type-specifier. We use context
5357 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5358 // and if so, whether it is the first decl.
5359 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5360 if (!cxcursor::isFirstInDeclGroup(C))
5361 R.setBegin(VD->getLocation());
5365 return SourceRange();
5368 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
5369 /// the decl-specifier-seq for declarations.
5370 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5371 if (clang_isDeclaration(C.kind)) {
5372 const Decl *D = cxcursor::getCursorDecl(C);
5374 return SourceRange();
5376 SourceRange R = D->getSourceRange();
5378 // Adjust the start of the location for declarations preceded by
5379 // declaration specifiers.
5380 SourceLocation StartLoc;
5381 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5382 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5383 StartLoc = TI->getTypeLoc().getLocStart();
5384 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
5385 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5386 StartLoc = TI->getTypeLoc().getLocStart();
5389 if (StartLoc.isValid() && R.getBegin().isValid() &&
5390 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5391 R.setBegin(StartLoc);
5393 // FIXME: Multiple variables declared in a single declaration
5394 // currently lack the information needed to correctly determine their
5395 // ranges when accounting for the type-specifier. We use context
5396 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5397 // and if so, whether it is the first decl.
5398 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5399 if (!cxcursor::isFirstInDeclGroup(C))
5400 R.setBegin(VD->getLocation());
5406 return getRawCursorExtent(C);
5411 CXSourceRange clang_getCursorExtent(CXCursor C) {
5412 SourceRange R = getRawCursorExtent(C);
5414 return clang_getNullRange();
5416 return cxloc::translateSourceRange(getCursorContext(C), R);
5419 CXCursor clang_getCursorReferenced(CXCursor C) {
5420 if (clang_isInvalid(C.kind))
5421 return clang_getNullCursor();
5423 CXTranslationUnit tu = getCursorTU(C);
5424 if (clang_isDeclaration(C.kind)) {
5425 const Decl *D = getCursorDecl(C);
5427 return clang_getNullCursor();
5428 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5429 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
5430 if (const ObjCPropertyImplDecl *PropImpl =
5431 dyn_cast<ObjCPropertyImplDecl>(D))
5432 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5433 return MakeCXCursor(Property, tu);
5438 if (clang_isExpression(C.kind)) {
5439 const Expr *E = getCursorExpr(C);
5440 const Decl *D = getDeclFromExpr(E);
5442 CXCursor declCursor = MakeCXCursor(D, tu);
5443 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5448 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
5449 return MakeCursorOverloadedDeclRef(Ovl, tu);
5451 return clang_getNullCursor();
5454 if (clang_isStatement(C.kind)) {
5455 const Stmt *S = getCursorStmt(C);
5456 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
5457 if (LabelDecl *label = Goto->getLabel())
5458 if (LabelStmt *labelS = label->getStmt())
5459 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5461 return clang_getNullCursor();
5464 if (C.kind == CXCursor_MacroExpansion) {
5465 if (const MacroDefinitionRecord *Def =
5466 getCursorMacroExpansion(C).getDefinition())
5467 return MakeMacroDefinitionCursor(Def, tu);
5470 if (!clang_isReference(C.kind))
5471 return clang_getNullCursor();
5474 case CXCursor_ObjCSuperClassRef:
5475 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5477 case CXCursor_ObjCProtocolRef: {
5478 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5479 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5480 return MakeCXCursor(Def, tu);
5482 return MakeCXCursor(Prot, tu);
5485 case CXCursor_ObjCClassRef: {
5486 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5487 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5488 return MakeCXCursor(Def, tu);
5490 return MakeCXCursor(Class, tu);
5493 case CXCursor_TypeRef:
5494 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5496 case CXCursor_TemplateRef:
5497 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5499 case CXCursor_NamespaceRef:
5500 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5502 case CXCursor_MemberRef:
5503 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5505 case CXCursor_CXXBaseSpecifier: {
5506 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5507 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5511 case CXCursor_LabelRef:
5512 // FIXME: We end up faking the "parent" declaration here because we
5513 // don't want to make CXCursor larger.
5514 return MakeCXCursor(getCursorLabelRef(C).first,
5515 cxtu::getASTUnit(tu)->getASTContext()
5516 .getTranslationUnitDecl(),
5519 case CXCursor_OverloadedDeclRef:
5522 case CXCursor_VariableRef:
5523 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5526 // We would prefer to enumerate all non-reference cursor kinds here.
5527 llvm_unreachable("Unhandled reference cursor kind");
5531 CXCursor clang_getCursorDefinition(CXCursor C) {
5532 if (clang_isInvalid(C.kind))
5533 return clang_getNullCursor();
5535 CXTranslationUnit TU = getCursorTU(C);
5537 bool WasReference = false;
5538 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5539 C = clang_getCursorReferenced(C);
5540 WasReference = true;
5543 if (C.kind == CXCursor_MacroExpansion)
5544 return clang_getCursorReferenced(C);
5546 if (!clang_isDeclaration(C.kind))
5547 return clang_getNullCursor();
5549 const Decl *D = getCursorDecl(C);
5551 return clang_getNullCursor();
5553 switch (D->getKind()) {
5554 // Declaration kinds that don't really separate the notions of
5555 // declaration and definition.
5556 case Decl::Namespace:
5558 case Decl::TypeAlias:
5559 case Decl::TypeAliasTemplate:
5560 case Decl::TemplateTypeParm:
5561 case Decl::EnumConstant:
5563 case Decl::MSProperty:
5564 case Decl::IndirectField:
5565 case Decl::ObjCIvar:
5566 case Decl::ObjCAtDefsField:
5567 case Decl::ImplicitParam:
5569 case Decl::NonTypeTemplateParm:
5570 case Decl::TemplateTemplateParm:
5571 case Decl::ObjCCategoryImpl:
5572 case Decl::ObjCImplementation:
5573 case Decl::AccessSpec:
5574 case Decl::LinkageSpec:
5575 case Decl::ObjCPropertyImpl:
5576 case Decl::FileScopeAsm:
5577 case Decl::StaticAssert:
5579 case Decl::Captured:
5580 case Decl::OMPCapturedExpr:
5581 case Decl::Label: // FIXME: Is this right??
5582 case Decl::ClassScopeFunctionSpecialization:
5584 case Decl::OMPThreadPrivate:
5585 case Decl::ObjCTypeParam:
5586 case Decl::BuiltinTemplate:
5589 // Declaration kinds that don't make any sense here, but are
5590 // nonetheless harmless.
5592 case Decl::TranslationUnit:
5593 case Decl::ExternCContext:
5596 // Declaration kinds for which the definition is not resolvable.
5597 case Decl::UnresolvedUsingTypename:
5598 case Decl::UnresolvedUsingValue:
5601 case Decl::UsingDirective:
5602 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5605 case Decl::NamespaceAlias:
5606 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5610 case Decl::CXXRecord:
5611 case Decl::ClassTemplateSpecialization:
5612 case Decl::ClassTemplatePartialSpecialization:
5613 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5614 return MakeCXCursor(Def, TU);
5615 return clang_getNullCursor();
5617 case Decl::Function:
5618 case Decl::CXXMethod:
5619 case Decl::CXXConstructor:
5620 case Decl::CXXDestructor:
5621 case Decl::CXXConversion: {
5622 const FunctionDecl *Def = nullptr;
5623 if (cast<FunctionDecl>(D)->getBody(Def))
5624 return MakeCXCursor(Def, TU);
5625 return clang_getNullCursor();
5629 case Decl::VarTemplateSpecialization:
5630 case Decl::VarTemplatePartialSpecialization: {
5631 // Ask the variable if it has a definition.
5632 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5633 return MakeCXCursor(Def, TU);
5634 return clang_getNullCursor();
5637 case Decl::FunctionTemplate: {
5638 const FunctionDecl *Def = nullptr;
5639 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5640 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5641 return clang_getNullCursor();
5644 case Decl::ClassTemplate: {
5645 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5647 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5649 return clang_getNullCursor();
5652 case Decl::VarTemplate: {
5654 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5655 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5656 return clang_getNullCursor();
5660 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5661 D->getLocation(), TU);
5663 case Decl::UsingShadow:
5664 return clang_getCursorDefinition(
5665 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5668 case Decl::ObjCMethod: {
5669 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5670 if (Method->isThisDeclarationADefinition())
5673 // Dig out the method definition in the associated
5674 // @implementation, if we have it.
5675 // FIXME: The ASTs should make finding the definition easier.
5676 if (const ObjCInterfaceDecl *Class
5677 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5678 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5679 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5680 Method->isInstanceMethod()))
5681 if (Def->isThisDeclarationADefinition())
5682 return MakeCXCursor(Def, TU);
5684 return clang_getNullCursor();
5687 case Decl::ObjCCategory:
5688 if (ObjCCategoryImplDecl *Impl
5689 = cast<ObjCCategoryDecl>(D)->getImplementation())
5690 return MakeCXCursor(Impl, TU);
5691 return clang_getNullCursor();
5693 case Decl::ObjCProtocol:
5694 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5695 return MakeCXCursor(Def, TU);
5696 return clang_getNullCursor();
5698 case Decl::ObjCInterface: {
5699 // There are two notions of a "definition" for an Objective-C
5700 // class: the interface and its implementation. When we resolved a
5701 // reference to an Objective-C class, produce the @interface as
5702 // the definition; when we were provided with the interface,
5703 // produce the @implementation as the definition.
5704 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5706 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5707 return MakeCXCursor(Def, TU);
5708 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5709 return MakeCXCursor(Impl, TU);
5710 return clang_getNullCursor();
5713 case Decl::ObjCProperty:
5714 // FIXME: We don't really know where to find the
5715 // ObjCPropertyImplDecls that implement this property.
5716 return clang_getNullCursor();
5718 case Decl::ObjCCompatibleAlias:
5719 if (const ObjCInterfaceDecl *Class
5720 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5721 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5722 return MakeCXCursor(Def, TU);
5724 return clang_getNullCursor();
5727 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5728 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5729 return clang_getNullCursor();
5731 case Decl::FriendTemplate:
5732 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5733 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5734 return clang_getNullCursor();
5737 return clang_getNullCursor();
5740 unsigned clang_isCursorDefinition(CXCursor C) {
5741 if (!clang_isDeclaration(C.kind))
5744 return clang_getCursorDefinition(C) == C;
5747 CXCursor clang_getCanonicalCursor(CXCursor C) {
5748 if (!clang_isDeclaration(C.kind))
5751 if (const Decl *D = getCursorDecl(C)) {
5752 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5753 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5754 return MakeCXCursor(CatD, getCursorTU(C));
5756 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5757 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5758 return MakeCXCursor(IFD, getCursorTU(C));
5760 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5766 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5767 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5770 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5771 if (C.kind != CXCursor_OverloadedDeclRef)
5774 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5775 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5776 return E->getNumDecls();
5778 if (OverloadedTemplateStorage *S
5779 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5782 const Decl *D = Storage.get<const Decl *>();
5783 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5784 return Using->shadow_size();
5789 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5790 if (cursor.kind != CXCursor_OverloadedDeclRef)
5791 return clang_getNullCursor();
5793 if (index >= clang_getNumOverloadedDecls(cursor))
5794 return clang_getNullCursor();
5796 CXTranslationUnit TU = getCursorTU(cursor);
5797 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5798 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5799 return MakeCXCursor(E->decls_begin()[index], TU);
5801 if (OverloadedTemplateStorage *S
5802 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5803 return MakeCXCursor(S->begin()[index], TU);
5805 const Decl *D = Storage.get<const Decl *>();
5806 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5807 // FIXME: This is, unfortunately, linear time.
5808 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5809 std::advance(Pos, index);
5810 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5813 return clang_getNullCursor();
5816 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5817 const char **startBuf,
5818 const char **endBuf,
5819 unsigned *startLine,
5820 unsigned *startColumn,
5822 unsigned *endColumn) {
5823 assert(getCursorDecl(C) && "CXCursor has null decl");
5824 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5825 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5827 SourceManager &SM = FD->getASTContext().getSourceManager();
5828 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5829 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5830 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5831 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5832 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5833 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5837 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5838 unsigned PieceIndex) {
5839 RefNamePieces Pieces;
5842 case CXCursor_MemberRefExpr:
5843 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5844 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5845 E->getQualifierLoc().getSourceRange());
5848 case CXCursor_DeclRefExpr:
5849 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5850 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5852 buildPieces(NameFlags, false, E->getNameInfo(),
5853 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5857 case CXCursor_CallExpr:
5858 if (const CXXOperatorCallExpr *OCE =
5859 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5860 const Expr *Callee = OCE->getCallee();
5861 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5862 Callee = ICE->getSubExpr();
5864 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5865 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5866 DRE->getQualifierLoc().getSourceRange());
5874 if (Pieces.empty()) {
5875 if (PieceIndex == 0)
5876 return clang_getCursorExtent(C);
5877 } else if (PieceIndex < Pieces.size()) {
5878 SourceRange R = Pieces[PieceIndex];
5880 return cxloc::translateSourceRange(getCursorContext(C), R);
5883 return clang_getNullRange();
5886 void clang_enableStackTraces(void) {
5887 llvm::sys::PrintStackTraceOnErrorSignal();
5890 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5891 unsigned stack_size) {
5892 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5895 } // end: extern "C"
5897 //===----------------------------------------------------------------------===//
5898 // Token-based Operations.
5899 //===----------------------------------------------------------------------===//
5902 * int_data[0]: a CXTokenKind
5903 * int_data[1]: starting token location
5904 * int_data[2]: token length
5905 * int_data[3]: reserved
5906 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5911 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5912 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5915 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5916 switch (clang_getTokenKind(CXTok)) {
5917 case CXToken_Identifier:
5918 case CXToken_Keyword:
5919 // We know we have an IdentifierInfo*, so use that.
5920 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5923 case CXToken_Literal: {
5924 // We have stashed the starting pointer in the ptr_data field. Use it.
5925 const char *Text = static_cast<const char *>(CXTok.ptr_data);
5926 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5929 case CXToken_Punctuation:
5930 case CXToken_Comment:
5934 if (isNotUsableTU(TU)) {
5936 return cxstring::createEmpty();
5939 // We have to find the starting buffer pointer the hard way, by
5940 // deconstructing the source location.
5941 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5943 return cxstring::createEmpty();
5945 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5946 std::pair<FileID, unsigned> LocInfo
5947 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5948 bool Invalid = false;
5950 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5952 return cxstring::createEmpty();
5954 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5957 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5958 if (isNotUsableTU(TU)) {
5960 return clang_getNullLocation();
5963 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5965 return clang_getNullLocation();
5967 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5968 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5971 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5972 if (isNotUsableTU(TU)) {
5974 return clang_getNullRange();
5977 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5979 return clang_getNullRange();
5981 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5982 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5985 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5986 SmallVectorImpl<CXToken> &CXTokens) {
5987 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5988 std::pair<FileID, unsigned> BeginLocInfo
5989 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5990 std::pair<FileID, unsigned> EndLocInfo
5991 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5993 // Cannot tokenize across files.
5994 if (BeginLocInfo.first != EndLocInfo.first)
5998 bool Invalid = false;
6000 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6004 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6005 CXXUnit->getASTContext().getLangOpts(),
6006 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6007 Lex.SetCommentRetentionState(true);
6009 // Lex tokens until we hit the end of the range.
6010 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6012 bool previousWasAt = false;
6014 // Lex the next token
6015 Lex.LexFromRawLexer(Tok);
6016 if (Tok.is(tok::eof))
6019 // Initialize the CXToken.
6023 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6024 CXTok.int_data[2] = Tok.getLength();
6025 CXTok.int_data[3] = 0;
6027 // - Kind-specific fields
6028 if (Tok.isLiteral()) {
6029 CXTok.int_data[0] = CXToken_Literal;
6030 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6031 } else if (Tok.is(tok::raw_identifier)) {
6032 // Lookup the identifier to determine whether we have a keyword.
6034 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6036 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6037 CXTok.int_data[0] = CXToken_Keyword;
6040 CXTok.int_data[0] = Tok.is(tok::identifier)
6041 ? CXToken_Identifier
6044 CXTok.ptr_data = II;
6045 } else if (Tok.is(tok::comment)) {
6046 CXTok.int_data[0] = CXToken_Comment;
6047 CXTok.ptr_data = nullptr;
6049 CXTok.int_data[0] = CXToken_Punctuation;
6050 CXTok.ptr_data = nullptr;
6052 CXTokens.push_back(CXTok);
6053 previousWasAt = Tok.is(tok::at);
6054 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
6057 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6058 CXToken **Tokens, unsigned *NumTokens) {
6060 *Log << TU << ' ' << Range;
6068 if (isNotUsableTU(TU)) {
6073 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6074 if (!CXXUnit || !Tokens || !NumTokens)
6077 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6079 SourceRange R = cxloc::translateCXSourceRange(Range);
6083 SmallVector<CXToken, 32> CXTokens;
6084 getTokens(CXXUnit, R, CXTokens);
6086 if (CXTokens.empty())
6089 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6090 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6091 *NumTokens = CXTokens.size();
6094 void clang_disposeTokens(CXTranslationUnit TU,
6095 CXToken *Tokens, unsigned NumTokens) {
6099 } // end: extern "C"
6101 //===----------------------------------------------------------------------===//
6102 // Token annotation APIs.
6103 //===----------------------------------------------------------------------===//
6105 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6107 CXClientData client_data);
6108 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6109 CXClientData client_data);
6112 class AnnotateTokensWorker {
6117 unsigned PreprocessingTokIdx;
6118 CursorVisitor AnnotateVis;
6119 SourceManager &SrcMgr;
6120 bool HasContextSensitiveKeywords;
6122 struct PostChildrenInfo {
6124 SourceRange CursorRange;
6125 unsigned BeforeReachingCursorIdx;
6126 unsigned BeforeChildrenTokenIdx;
6128 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
6130 CXToken &getTok(unsigned Idx) {
6131 assert(Idx < NumTokens);
6134 const CXToken &getTok(unsigned Idx) const {
6135 assert(Idx < NumTokens);
6138 bool MoreTokens() const { return TokIdx < NumTokens; }
6139 unsigned NextToken() const { return TokIdx; }
6140 void AdvanceToken() { ++TokIdx; }
6141 SourceLocation GetTokenLoc(unsigned tokI) {
6142 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6144 bool isFunctionMacroToken(unsigned tokI) const {
6145 return getTok(tokI).int_data[3] != 0;
6147 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
6148 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6151 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
6152 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
6156 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
6157 CXTranslationUnit TU, SourceRange RegionOfInterest)
6158 : Tokens(tokens), Cursors(cursors),
6159 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6161 AnnotateTokensVisitor, this,
6162 /*VisitPreprocessorLast=*/true,
6163 /*VisitIncludedEntities=*/false,
6165 /*VisitDeclsOnly=*/false,
6166 AnnotateTokensPostChildrenVisitor),
6167 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6168 HasContextSensitiveKeywords(false) { }
6170 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6171 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6172 bool postVisitChildren(CXCursor cursor);
6173 void AnnotateTokens();
6175 /// \brief Determine whether the annotator saw any cursors that have
6176 /// context-sensitive keywords.
6177 bool hasContextSensitiveKeywords() const {
6178 return HasContextSensitiveKeywords;
6181 ~AnnotateTokensWorker() {
6182 assert(PostChildrenInfos.empty());
6187 void AnnotateTokensWorker::AnnotateTokens() {
6188 // Walk the AST within the region of interest, annotating tokens
6190 AnnotateVis.visitFileRegion();
6193 static inline void updateCursorAnnotation(CXCursor &Cursor,
6194 const CXCursor &updateC) {
6195 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6200 /// \brief It annotates and advances tokens with a cursor until the comparison
6201 //// between the cursor location and the source range is the same as
6202 /// \arg compResult.
6204 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6205 /// Pass RangeOverlap to annotate tokens inside a range.
6206 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6207 RangeComparisonResult compResult,
6208 SourceRange range) {
6209 while (MoreTokens()) {
6210 const unsigned I = NextToken();
6211 if (isFunctionMacroToken(I))
6212 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6215 SourceLocation TokLoc = GetTokenLoc(I);
6216 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6217 updateCursorAnnotation(Cursors[I], updateC);
6225 /// \brief Special annotation handling for macro argument tokens.
6226 /// \returns true if it advanced beyond all macro tokens, false otherwise.
6227 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
6229 RangeComparisonResult compResult,
6230 SourceRange range) {
6231 assert(MoreTokens());
6232 assert(isFunctionMacroToken(NextToken()) &&
6233 "Should be called only for macro arg tokens");
6235 // This works differently than annotateAndAdvanceTokens; because expanded
6236 // macro arguments can have arbitrary translation-unit source order, we do not
6237 // advance the token index one by one until a token fails the range test.
6238 // We only advance once past all of the macro arg tokens if all of them
6239 // pass the range test. If one of them fails we keep the token index pointing
6240 // at the start of the macro arg tokens so that the failing token will be
6241 // annotated by a subsequent annotation try.
6243 bool atLeastOneCompFail = false;
6245 unsigned I = NextToken();
6246 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6247 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6248 if (TokLoc.isFileID())
6249 continue; // not macro arg token, it's parens or comma.
6250 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6251 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6252 Cursors[I] = updateC;
6254 atLeastOneCompFail = true;
6257 if (atLeastOneCompFail)
6260 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6264 enum CXChildVisitResult
6265 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
6266 SourceRange cursorRange = getRawCursorExtent(cursor);
6267 if (cursorRange.isInvalid())
6268 return CXChildVisit_Recurse;
6270 if (!HasContextSensitiveKeywords) {
6271 // Objective-C properties can have context-sensitive keywords.
6272 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
6273 if (const ObjCPropertyDecl *Property
6274 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6275 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6277 // Objective-C methods can have context-sensitive keywords.
6278 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6279 cursor.kind == CXCursor_ObjCClassMethodDecl) {
6280 if (const ObjCMethodDecl *Method
6281 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6282 if (Method->getObjCDeclQualifier())
6283 HasContextSensitiveKeywords = true;
6285 for (const auto *P : Method->params()) {
6286 if (P->getObjCDeclQualifier()) {
6287 HasContextSensitiveKeywords = true;
6294 // C++ methods can have context-sensitive keywords.
6295 else if (cursor.kind == CXCursor_CXXMethod) {
6296 if (const CXXMethodDecl *Method
6297 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6298 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6299 HasContextSensitiveKeywords = true;
6302 // C++ classes can have context-sensitive keywords.
6303 else if (cursor.kind == CXCursor_StructDecl ||
6304 cursor.kind == CXCursor_ClassDecl ||
6305 cursor.kind == CXCursor_ClassTemplate ||
6306 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
6307 if (const Decl *D = getCursorDecl(cursor))
6308 if (D->hasAttr<FinalAttr>())
6309 HasContextSensitiveKeywords = true;
6313 // Don't override a property annotation with its getter/setter method.
6314 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6315 parent.kind == CXCursor_ObjCPropertyDecl)
6316 return CXChildVisit_Continue;
6318 if (clang_isPreprocessing(cursor.kind)) {
6319 // Items in the preprocessing record are kept separate from items in
6320 // declarations, so we keep a separate token index.
6321 unsigned SavedTokIdx = TokIdx;
6322 TokIdx = PreprocessingTokIdx;
6324 // Skip tokens up until we catch up to the beginning of the preprocessing
6326 while (MoreTokens()) {
6327 const unsigned I = NextToken();
6328 SourceLocation TokLoc = GetTokenLoc(I);
6329 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6340 // Look at all of the tokens within this range.
6341 while (MoreTokens()) {
6342 const unsigned I = NextToken();
6343 SourceLocation TokLoc = GetTokenLoc(I);
6344 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6346 llvm_unreachable("Infeasible");
6350 // For macro expansions, just note where the beginning of the macro
6351 // expansion occurs.
6352 if (cursor.kind == CXCursor_MacroExpansion) {
6353 if (TokLoc == cursorRange.getBegin())
6354 Cursors[I] = cursor;
6358 // We may have already annotated macro names inside macro definitions.
6359 if (Cursors[I].kind != CXCursor_MacroExpansion)
6360 Cursors[I] = cursor;
6367 // Save the preprocessing token index; restore the non-preprocessing
6369 PreprocessingTokIdx = TokIdx;
6370 TokIdx = SavedTokIdx;
6371 return CXChildVisit_Recurse;
6374 if (cursorRange.isInvalid())
6375 return CXChildVisit_Continue;
6377 unsigned BeforeReachingCursorIdx = NextToken();
6378 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
6379 const enum CXCursorKind K = clang_getCursorKind(parent);
6380 const CXCursor updateC =
6381 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6382 // Attributes are annotated out-of-order, skip tokens until we reach it.
6383 clang_isAttribute(cursor.kind))
6384 ? clang_getNullCursor() : parent;
6386 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6388 // Avoid having the cursor of an expression "overwrite" the annotation of the
6389 // variable declaration that it belongs to.
6390 // This can happen for C++ constructor expressions whose range generally
6391 // include the variable declaration, e.g.:
6392 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
6393 if (clang_isExpression(cursorK) && MoreTokens()) {
6394 const Expr *E = getCursorExpr(cursor);
6395 if (const Decl *D = getCursorParentDecl(cursor)) {
6396 const unsigned I = NextToken();
6397 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6398 E->getLocStart() == D->getLocation() &&
6399 E->getLocStart() == GetTokenLoc(I)) {
6400 updateCursorAnnotation(Cursors[I], updateC);
6406 // Before recursing into the children keep some state that we are going
6407 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6408 // extra work after the child nodes are visited.
6409 // Note that we don't call VisitChildren here to avoid traversing statements
6410 // code-recursively which can blow the stack.
6412 PostChildrenInfo Info;
6413 Info.Cursor = cursor;
6414 Info.CursorRange = cursorRange;
6415 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
6416 Info.BeforeChildrenTokenIdx = NextToken();
6417 PostChildrenInfos.push_back(Info);
6419 return CXChildVisit_Recurse;
6422 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6423 if (PostChildrenInfos.empty())
6425 const PostChildrenInfo &Info = PostChildrenInfos.back();
6426 if (!clang_equalCursors(Info.Cursor, cursor))
6429 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6430 const unsigned AfterChildren = NextToken();
6431 SourceRange cursorRange = Info.CursorRange;
6433 // Scan the tokens that are at the end of the cursor, but are not captured
6434 // but the child cursors.
6435 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6437 // Scan the tokens that are at the beginning of the cursor, but are not
6438 // capture by the child cursors.
6439 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6440 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6443 Cursors[I] = cursor;
6446 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6447 // encountered the attribute cursor.
6448 if (clang_isAttribute(cursor.kind))
6449 TokIdx = Info.BeforeReachingCursorIdx;
6451 PostChildrenInfos.pop_back();
6455 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6457 CXClientData client_data) {
6458 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6461 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6462 CXClientData client_data) {
6463 return static_cast<AnnotateTokensWorker*>(client_data)->
6464 postVisitChildren(cursor);
6469 /// \brief Uses the macro expansions in the preprocessing record to find
6470 /// and mark tokens that are macro arguments. This info is used by the
6471 /// AnnotateTokensWorker.
6472 class MarkMacroArgTokensVisitor {
6479 MarkMacroArgTokensVisitor(SourceManager &SM,
6480 CXToken *tokens, unsigned numTokens)
6481 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6483 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6484 if (cursor.kind != CXCursor_MacroExpansion)
6485 return CXChildVisit_Continue;
6487 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6488 if (macroRange.getBegin() == macroRange.getEnd())
6489 return CXChildVisit_Continue; // it's not a function macro.
6491 for (; CurIdx < NumTokens; ++CurIdx) {
6492 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6493 macroRange.getBegin()))
6497 if (CurIdx == NumTokens)
6498 return CXChildVisit_Break;
6500 for (; CurIdx < NumTokens; ++CurIdx) {
6501 SourceLocation tokLoc = getTokenLoc(CurIdx);
6502 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6505 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6508 if (CurIdx == NumTokens)
6509 return CXChildVisit_Break;
6511 return CXChildVisit_Continue;
6515 CXToken &getTok(unsigned Idx) {
6516 assert(Idx < NumTokens);
6519 const CXToken &getTok(unsigned Idx) const {
6520 assert(Idx < NumTokens);
6524 SourceLocation getTokenLoc(unsigned tokI) {
6525 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6528 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6529 // The third field is reserved and currently not used. Use it here
6530 // to mark macro arg expanded tokens with their expanded locations.
6531 getTok(tokI).int_data[3] = loc.getRawEncoding();
6535 } // end anonymous namespace
6537 static CXChildVisitResult
6538 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6539 CXClientData client_data) {
6540 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6544 /// \brief Used by \c annotatePreprocessorTokens.
6545 /// \returns true if lexing was finished, false otherwise.
6546 static bool lexNext(Lexer &Lex, Token &Tok,
6547 unsigned &NextIdx, unsigned NumTokens) {
6548 if (NextIdx >= NumTokens)
6552 Lex.LexFromRawLexer(Tok);
6553 return Tok.is(tok::eof);
6556 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6557 SourceRange RegionOfInterest,
6560 unsigned NumTokens) {
6561 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6563 Preprocessor &PP = CXXUnit->getPreprocessor();
6564 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6565 std::pair<FileID, unsigned> BeginLocInfo
6566 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6567 std::pair<FileID, unsigned> EndLocInfo
6568 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6570 if (BeginLocInfo.first != EndLocInfo.first)
6574 bool Invalid = false;
6575 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6576 if (Buffer.empty() || Invalid)
6579 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6580 CXXUnit->getASTContext().getLangOpts(),
6581 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6583 Lex.SetCommentRetentionState(true);
6585 unsigned NextIdx = 0;
6586 // Lex tokens in raw mode until we hit the end of the range, to avoid
6587 // entering #includes or expanding macros.
6590 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6592 unsigned TokIdx = NextIdx-1;
6593 assert(Tok.getLocation() ==
6594 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6597 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6598 // We have found a preprocessing directive. Annotate the tokens
6601 // FIXME: Some simple tests here could identify macro definitions and
6602 // #undefs, to provide specific cursor kinds for those.
6604 SourceLocation BeginLoc = Tok.getLocation();
6605 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6608 MacroInfo *MI = nullptr;
6609 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6610 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6613 if (Tok.is(tok::raw_identifier)) {
6614 IdentifierInfo &II =
6615 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6616 SourceLocation MappedTokLoc =
6617 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6618 MI = getMacroInfo(II, MappedTokLoc, TU);
6622 bool finished = false;
6624 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6628 // If we are in a macro definition, check if the token was ever a
6629 // macro name and annotate it if that's the case.
6631 SourceLocation SaveLoc = Tok.getLocation();
6632 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6633 MacroDefinitionRecord *MacroDef =
6634 checkForMacroInMacroDefinition(MI, Tok, TU);
6635 Tok.setLocation(SaveLoc);
6637 Cursors[NextIdx - 1] =
6638 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6640 } while (!Tok.isAtStartOfLine());
6642 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6643 assert(TokIdx <= LastIdx);
6644 SourceLocation EndLoc =
6645 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6647 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6649 for (; TokIdx <= LastIdx; ++TokIdx)
6650 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6659 // This gets run a separate thread to avoid stack blowout.
6660 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6661 CXToken *Tokens, unsigned NumTokens,
6662 CXCursor *Cursors) {
6663 CIndexer *CXXIdx = TU->CIdx;
6664 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6665 setThreadBackgroundPriority();
6667 // Determine the region of interest, which contains all of the tokens.
6668 SourceRange RegionOfInterest;
6669 RegionOfInterest.setBegin(
6670 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6671 RegionOfInterest.setEnd(
6672 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6673 Tokens[NumTokens-1])));
6675 // Relex the tokens within the source range to look for preprocessing
6677 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6679 // If begin location points inside a macro argument, set it to the expansion
6680 // location so we can have the full context when annotating semantically.
6682 SourceManager &SM = CXXUnit->getSourceManager();
6683 SourceLocation Loc =
6684 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6685 if (Loc.isMacroID())
6686 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6689 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6690 // Search and mark tokens that are macro argument expansions.
6691 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6693 CursorVisitor MacroArgMarker(TU,
6694 MarkMacroArgTokensVisitorDelegate, &Visitor,
6695 /*VisitPreprocessorLast=*/true,
6696 /*VisitIncludedEntities=*/false,
6698 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6701 // Annotate all of the source locations in the region of interest that map to
6702 // a specific cursor.
6703 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6705 // FIXME: We use a ridiculous stack size here because the data-recursion
6706 // algorithm uses a large stack frame than the non-data recursive version,
6707 // and AnnotationTokensWorker currently transforms the data-recursion
6708 // algorithm back into a traditional recursion by explicitly calling
6709 // VisitChildren(). We will need to remove this explicit recursive call.
6712 // If we ran into any entities that involve context-sensitive keywords,
6713 // take another pass through the tokens to mark them as such.
6714 if (W.hasContextSensitiveKeywords()) {
6715 for (unsigned I = 0; I != NumTokens; ++I) {
6716 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6719 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6720 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6721 if (const ObjCPropertyDecl *Property
6722 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6723 if (Property->getPropertyAttributesAsWritten() != 0 &&
6724 llvm::StringSwitch<bool>(II->getName())
6725 .Case("readonly", true)
6726 .Case("assign", true)
6727 .Case("unsafe_unretained", true)
6728 .Case("readwrite", true)
6729 .Case("retain", true)
6731 .Case("nonatomic", true)
6732 .Case("atomic", true)
6733 .Case("getter", true)
6734 .Case("setter", true)
6735 .Case("strong", true)
6738 Tokens[I].int_data[0] = CXToken_Keyword;
6743 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6744 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6745 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6746 if (llvm::StringSwitch<bool>(II->getName())
6749 .Case("inout", true)
6750 .Case("oneway", true)
6751 .Case("bycopy", true)
6752 .Case("byref", true)
6754 Tokens[I].int_data[0] = CXToken_Keyword;
6758 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6759 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6760 Tokens[I].int_data[0] = CXToken_Keyword;
6769 void clang_annotateTokens(CXTranslationUnit TU,
6770 CXToken *Tokens, unsigned NumTokens,
6771 CXCursor *Cursors) {
6772 if (isNotUsableTU(TU)) {
6776 if (NumTokens == 0 || !Tokens || !Cursors) {
6777 LOG_FUNC_SECTION { *Log << "<null input>"; }
6783 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6784 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6785 *Log << clang_getRange(bloc, eloc);
6788 // Any token we don't specifically annotate will have a NULL cursor.
6789 CXCursor C = clang_getNullCursor();
6790 for (unsigned I = 0; I != NumTokens; ++I)
6793 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6797 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6799 auto AnnotateTokensImpl = [=]() {
6800 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6802 llvm::CrashRecoveryContext CRC;
6803 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6804 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6808 } // end: extern "C"
6810 //===----------------------------------------------------------------------===//
6811 // Operations for querying linkage of a cursor.
6812 //===----------------------------------------------------------------------===//
6815 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6816 if (!clang_isDeclaration(cursor.kind))
6817 return CXLinkage_Invalid;
6819 const Decl *D = cxcursor::getCursorDecl(cursor);
6820 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6821 switch (ND->getLinkageInternal()) {
6823 case VisibleNoLinkage: return CXLinkage_NoLinkage;
6824 case InternalLinkage: return CXLinkage_Internal;
6825 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6826 case ExternalLinkage: return CXLinkage_External;
6829 return CXLinkage_Invalid;
6831 } // end: extern "C"
6833 //===----------------------------------------------------------------------===//
6834 // Operations for querying visibility of a cursor.
6835 //===----------------------------------------------------------------------===//
6838 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6839 if (!clang_isDeclaration(cursor.kind))
6840 return CXVisibility_Invalid;
6842 const Decl *D = cxcursor::getCursorDecl(cursor);
6843 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6844 switch (ND->getVisibility()) {
6845 case HiddenVisibility: return CXVisibility_Hidden;
6846 case ProtectedVisibility: return CXVisibility_Protected;
6847 case DefaultVisibility: return CXVisibility_Default;
6850 return CXVisibility_Invalid;
6852 } // end: extern "C"
6854 //===----------------------------------------------------------------------===//
6855 // Operations for querying language of a cursor.
6856 //===----------------------------------------------------------------------===//
6858 static CXLanguageKind getDeclLanguage(const Decl *D) {
6860 return CXLanguage_C;
6862 switch (D->getKind()) {
6865 case Decl::ImplicitParam:
6866 case Decl::ObjCAtDefsField:
6867 case Decl::ObjCCategory:
6868 case Decl::ObjCCategoryImpl:
6869 case Decl::ObjCCompatibleAlias:
6870 case Decl::ObjCImplementation:
6871 case Decl::ObjCInterface:
6872 case Decl::ObjCIvar:
6873 case Decl::ObjCMethod:
6874 case Decl::ObjCProperty:
6875 case Decl::ObjCPropertyImpl:
6876 case Decl::ObjCProtocol:
6877 case Decl::ObjCTypeParam:
6878 return CXLanguage_ObjC;
6879 case Decl::CXXConstructor:
6880 case Decl::CXXConversion:
6881 case Decl::CXXDestructor:
6882 case Decl::CXXMethod:
6883 case Decl::CXXRecord:
6884 case Decl::ClassTemplate:
6885 case Decl::ClassTemplatePartialSpecialization:
6886 case Decl::ClassTemplateSpecialization:
6888 case Decl::FriendTemplate:
6889 case Decl::FunctionTemplate:
6890 case Decl::LinkageSpec:
6891 case Decl::Namespace:
6892 case Decl::NamespaceAlias:
6893 case Decl::NonTypeTemplateParm:
6894 case Decl::StaticAssert:
6895 case Decl::TemplateTemplateParm:
6896 case Decl::TemplateTypeParm:
6897 case Decl::UnresolvedUsingTypename:
6898 case Decl::UnresolvedUsingValue:
6900 case Decl::UsingDirective:
6901 case Decl::UsingShadow:
6902 return CXLanguage_CPlusPlus;
6905 return CXLanguage_C;
6910 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6911 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6912 return CXAvailability_NotAvailable;
6914 switch (D->getAvailability()) {
6916 case AR_NotYetIntroduced:
6917 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6918 return getCursorAvailabilityForDecl(
6919 cast<Decl>(EnumConst->getDeclContext()));
6920 return CXAvailability_Available;
6923 return CXAvailability_Deprecated;
6925 case AR_Unavailable:
6926 return CXAvailability_NotAvailable;
6929 llvm_unreachable("Unknown availability kind!");
6932 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6933 if (clang_isDeclaration(cursor.kind))
6934 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6935 return getCursorAvailabilityForDecl(D);
6937 return CXAvailability_Available;
6940 static CXVersion convertVersion(VersionTuple In) {
6941 CXVersion Out = { -1, -1, -1 };
6945 Out.Major = In.getMajor();
6947 Optional<unsigned> Minor = In.getMinor();
6948 if (Minor.hasValue())
6953 Optional<unsigned> Subminor = In.getSubminor();
6954 if (Subminor.hasValue())
6955 Out.Subminor = *Subminor;
6960 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6961 int *always_deprecated,
6962 CXString *deprecated_message,
6963 int *always_unavailable,
6964 CXString *unavailable_message,
6965 CXPlatformAvailability *availability,
6966 int availability_size) {
6967 bool HadAvailAttr = false;
6969 for (auto A : D->attrs()) {
6970 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6971 HadAvailAttr = true;
6972 if (always_deprecated)
6973 *always_deprecated = 1;
6974 if (deprecated_message) {
6975 clang_disposeString(*deprecated_message);
6976 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6981 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6982 HadAvailAttr = true;
6983 if (always_unavailable)
6984 *always_unavailable = 1;
6985 if (unavailable_message) {
6986 clang_disposeString(*unavailable_message);
6987 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6992 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6993 HadAvailAttr = true;
6994 if (N < availability_size) {
6995 availability[N].Platform
6996 = cxstring::createDup(Avail->getPlatform()->getName());
6997 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6998 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6999 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7000 availability[N].Unavailable = Avail->getUnavailable();
7001 availability[N].Message = cxstring::createDup(Avail->getMessage());
7008 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7009 return getCursorPlatformAvailabilityForDecl(
7010 cast<Decl>(EnumConst->getDeclContext()),
7014 unavailable_message,
7021 int clang_getCursorPlatformAvailability(CXCursor cursor,
7022 int *always_deprecated,
7023 CXString *deprecated_message,
7024 int *always_unavailable,
7025 CXString *unavailable_message,
7026 CXPlatformAvailability *availability,
7027 int availability_size) {
7028 if (always_deprecated)
7029 *always_deprecated = 0;
7030 if (deprecated_message)
7031 *deprecated_message = cxstring::createEmpty();
7032 if (always_unavailable)
7033 *always_unavailable = 0;
7034 if (unavailable_message)
7035 *unavailable_message = cxstring::createEmpty();
7037 if (!clang_isDeclaration(cursor.kind))
7040 const Decl *D = cxcursor::getCursorDecl(cursor);
7044 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7047 unavailable_message,
7052 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7053 clang_disposeString(availability->Platform);
7054 clang_disposeString(availability->Message);
7057 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7058 if (clang_isDeclaration(cursor.kind))
7059 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7061 return CXLanguage_Invalid;
7064 /// \brief If the given cursor is the "templated" declaration
7065 /// descibing a class or function template, return the class or
7066 /// function template.
7067 static const Decl *maybeGetTemplateCursor(const Decl *D) {
7071 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7072 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7075 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7076 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7083 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7084 StorageClass sc = SC_None;
7085 const Decl *D = getCursorDecl(C);
7087 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7088 sc = FD->getStorageClass();
7089 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7090 sc = VD->getStorageClass();
7092 return CX_SC_Invalid;
7095 return CX_SC_Invalid;
7101 return CX_SC_Extern;
7103 return CX_SC_Static;
7104 case SC_PrivateExtern:
7105 return CX_SC_PrivateExtern;
7109 return CX_SC_Register;
7111 llvm_unreachable("Unhandled storage class!");
7114 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7115 if (clang_isDeclaration(cursor.kind)) {
7116 if (const Decl *D = getCursorDecl(cursor)) {
7117 const DeclContext *DC = D->getDeclContext();
7119 return clang_getNullCursor();
7121 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7122 getCursorTU(cursor));
7126 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
7127 if (const Decl *D = getCursorDecl(cursor))
7128 return MakeCXCursor(D, getCursorTU(cursor));
7131 return clang_getNullCursor();
7134 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7135 if (clang_isDeclaration(cursor.kind)) {
7136 if (const Decl *D = getCursorDecl(cursor)) {
7137 const DeclContext *DC = D->getLexicalDeclContext();
7139 return clang_getNullCursor();
7141 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7142 getCursorTU(cursor));
7146 // FIXME: Note that we can't easily compute the lexical context of a
7147 // statement or expression, so we return nothing.
7148 return clang_getNullCursor();
7151 CXFile clang_getIncludedFile(CXCursor cursor) {
7152 if (cursor.kind != CXCursor_InclusionDirective)
7155 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
7156 return const_cast<FileEntry *>(ID->getFile());
7159 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7160 if (C.kind != CXCursor_ObjCPropertyDecl)
7161 return CXObjCPropertyAttr_noattr;
7163 unsigned Result = CXObjCPropertyAttr_noattr;
7164 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7165 ObjCPropertyDecl::PropertyAttributeKind Attr =
7166 PD->getPropertyAttributesAsWritten();
7168 #define SET_CXOBJCPROP_ATTR(A) \
7169 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7170 Result |= CXObjCPropertyAttr_##A
7171 SET_CXOBJCPROP_ATTR(readonly);
7172 SET_CXOBJCPROP_ATTR(getter);
7173 SET_CXOBJCPROP_ATTR(assign);
7174 SET_CXOBJCPROP_ATTR(readwrite);
7175 SET_CXOBJCPROP_ATTR(retain);
7176 SET_CXOBJCPROP_ATTR(copy);
7177 SET_CXOBJCPROP_ATTR(nonatomic);
7178 SET_CXOBJCPROP_ATTR(setter);
7179 SET_CXOBJCPROP_ATTR(atomic);
7180 SET_CXOBJCPROP_ATTR(weak);
7181 SET_CXOBJCPROP_ATTR(strong);
7182 SET_CXOBJCPROP_ATTR(unsafe_unretained);
7183 #undef SET_CXOBJCPROP_ATTR
7188 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7189 if (!clang_isDeclaration(C.kind))
7190 return CXObjCDeclQualifier_None;
7192 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7193 const Decl *D = getCursorDecl(C);
7194 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7195 QT = MD->getObjCDeclQualifier();
7196 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7197 QT = PD->getObjCDeclQualifier();
7198 if (QT == Decl::OBJC_TQ_None)
7199 return CXObjCDeclQualifier_None;
7201 unsigned Result = CXObjCDeclQualifier_None;
7202 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7203 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7204 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7205 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7206 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7207 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7212 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7213 if (!clang_isDeclaration(C.kind))
7216 const Decl *D = getCursorDecl(C);
7217 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7218 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7219 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7220 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7225 unsigned clang_Cursor_isVariadic(CXCursor C) {
7226 if (!clang_isDeclaration(C.kind))
7229 const Decl *D = getCursorDecl(C);
7230 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7231 return FD->isVariadic();
7232 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7233 return MD->isVariadic();
7238 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7239 if (!clang_isDeclaration(C.kind))
7240 return clang_getNullRange();
7242 const Decl *D = getCursorDecl(C);
7243 ASTContext &Context = getCursorContext(C);
7244 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7246 return clang_getNullRange();
7248 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7251 CXString clang_Cursor_getRawCommentText(CXCursor C) {
7252 if (!clang_isDeclaration(C.kind))
7253 return cxstring::createNull();
7255 const Decl *D = getCursorDecl(C);
7256 ASTContext &Context = getCursorContext(C);
7257 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7258 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7261 // Don't duplicate the string because RawText points directly into source
7263 return cxstring::createRef(RawText);
7266 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7267 if (!clang_isDeclaration(C.kind))
7268 return cxstring::createNull();
7270 const Decl *D = getCursorDecl(C);
7271 const ASTContext &Context = getCursorContext(C);
7272 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7275 StringRef BriefText = RC->getBriefText(Context);
7277 // Don't duplicate the string because RawComment ensures that this memory
7278 // will not go away.
7279 return cxstring::createRef(BriefText);
7282 return cxstring::createNull();
7285 CXModule clang_Cursor_getModule(CXCursor C) {
7286 if (C.kind == CXCursor_ModuleImportDecl) {
7287 if (const ImportDecl *ImportD =
7288 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
7289 return ImportD->getImportedModule();
7295 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7296 if (isNotUsableTU(TU)) {
7302 FileEntry *FE = static_cast<FileEntry *>(File);
7304 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7305 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7306 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7308 return Header.getModule();
7311 CXFile clang_Module_getASTFile(CXModule CXMod) {
7314 Module *Mod = static_cast<Module*>(CXMod);
7315 return const_cast<FileEntry *>(Mod->getASTFile());
7318 CXModule clang_Module_getParent(CXModule CXMod) {
7321 Module *Mod = static_cast<Module*>(CXMod);
7325 CXString clang_Module_getName(CXModule CXMod) {
7327 return cxstring::createEmpty();
7328 Module *Mod = static_cast<Module*>(CXMod);
7329 return cxstring::createDup(Mod->Name);
7332 CXString clang_Module_getFullName(CXModule CXMod) {
7334 return cxstring::createEmpty();
7335 Module *Mod = static_cast<Module*>(CXMod);
7336 return cxstring::createDup(Mod->getFullModuleName());
7339 int clang_Module_isSystem(CXModule CXMod) {
7342 Module *Mod = static_cast<Module*>(CXMod);
7343 return Mod->IsSystem;
7346 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7348 if (isNotUsableTU(TU)) {
7354 Module *Mod = static_cast<Module*>(CXMod);
7355 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7356 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7357 return TopHeaders.size();
7360 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7361 CXModule CXMod, unsigned Index) {
7362 if (isNotUsableTU(TU)) {
7368 Module *Mod = static_cast<Module*>(CXMod);
7369 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7371 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7372 if (Index < TopHeaders.size())
7373 return const_cast<FileEntry *>(TopHeaders[Index]);
7378 } // end: extern "C"
7380 //===----------------------------------------------------------------------===//
7381 // C++ AST instrospection.
7382 //===----------------------------------------------------------------------===//
7385 unsigned clang_CXXField_isMutable(CXCursor C) {
7386 if (!clang_isDeclaration(C.kind))
7389 if (const auto D = cxcursor::getCursorDecl(C))
7390 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7391 return FD->isMutable() ? 1 : 0;
7395 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7396 if (!clang_isDeclaration(C.kind))
7399 const Decl *D = cxcursor::getCursorDecl(C);
7400 const CXXMethodDecl *Method =
7401 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7402 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7405 unsigned clang_CXXMethod_isConst(CXCursor C) {
7406 if (!clang_isDeclaration(C.kind))
7409 const Decl *D = cxcursor::getCursorDecl(C);
7410 const CXXMethodDecl *Method =
7411 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7412 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7415 unsigned clang_CXXMethod_isStatic(CXCursor C) {
7416 if (!clang_isDeclaration(C.kind))
7419 const Decl *D = cxcursor::getCursorDecl(C);
7420 const CXXMethodDecl *Method =
7421 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7422 return (Method && Method->isStatic()) ? 1 : 0;
7425 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7426 if (!clang_isDeclaration(C.kind))
7429 const Decl *D = cxcursor::getCursorDecl(C);
7430 const CXXMethodDecl *Method =
7431 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7432 return (Method && Method->isVirtual()) ? 1 : 0;
7434 } // end: extern "C"
7436 //===----------------------------------------------------------------------===//
7437 // Attribute introspection.
7438 //===----------------------------------------------------------------------===//
7441 CXType clang_getIBOutletCollectionType(CXCursor C) {
7442 if (C.kind != CXCursor_IBOutletCollectionAttr)
7443 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7445 const IBOutletCollectionAttr *A =
7446 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7448 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7450 } // end: extern "C"
7452 //===----------------------------------------------------------------------===//
7453 // Inspecting memory usage.
7454 //===----------------------------------------------------------------------===//
7456 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7458 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7459 enum CXTUResourceUsageKind k,
7460 unsigned long amount) {
7461 CXTUResourceUsageEntry entry = { k, amount };
7462 entries.push_back(entry);
7467 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7468 const char *str = "";
7470 case CXTUResourceUsage_AST:
7471 str = "ASTContext: expressions, declarations, and types";
7473 case CXTUResourceUsage_Identifiers:
7474 str = "ASTContext: identifiers";
7476 case CXTUResourceUsage_Selectors:
7477 str = "ASTContext: selectors";
7479 case CXTUResourceUsage_GlobalCompletionResults:
7480 str = "Code completion: cached global results";
7482 case CXTUResourceUsage_SourceManagerContentCache:
7483 str = "SourceManager: content cache allocator";
7485 case CXTUResourceUsage_AST_SideTables:
7486 str = "ASTContext: side tables";
7488 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7489 str = "SourceManager: malloc'ed memory buffers";
7491 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7492 str = "SourceManager: mmap'ed memory buffers";
7494 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7495 str = "ExternalASTSource: malloc'ed memory buffers";
7497 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7498 str = "ExternalASTSource: mmap'ed memory buffers";
7500 case CXTUResourceUsage_Preprocessor:
7501 str = "Preprocessor: malloc'ed memory";
7503 case CXTUResourceUsage_PreprocessingRecord:
7504 str = "Preprocessor: PreprocessingRecord";
7506 case CXTUResourceUsage_SourceManager_DataStructures:
7507 str = "SourceManager: data structures and tables";
7509 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7510 str = "Preprocessor: header search tables";
7516 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7517 if (isNotUsableTU(TU)) {
7519 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7523 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7524 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7525 ASTContext &astContext = astUnit->getASTContext();
7527 // How much memory is used by AST nodes and types?
7528 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7529 (unsigned long) astContext.getASTAllocatedMemory());
7531 // How much memory is used by identifiers?
7532 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7533 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7535 // How much memory is used for selectors?
7536 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7537 (unsigned long) astContext.Selectors.getTotalMemory());
7539 // How much memory is used by ASTContext's side tables?
7540 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7541 (unsigned long) astContext.getSideTableAllocatedMemory());
7543 // How much memory is used for caching global code completion results?
7544 unsigned long completionBytes = 0;
7545 if (GlobalCodeCompletionAllocator *completionAllocator =
7546 astUnit->getCachedCompletionAllocator().get()) {
7547 completionBytes = completionAllocator->getTotalMemory();
7549 createCXTUResourceUsageEntry(*entries,
7550 CXTUResourceUsage_GlobalCompletionResults,
7553 // How much memory is being used by SourceManager's content cache?
7554 createCXTUResourceUsageEntry(*entries,
7555 CXTUResourceUsage_SourceManagerContentCache,
7556 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7558 // How much memory is being used by the MemoryBuffer's in SourceManager?
7559 const SourceManager::MemoryBufferSizes &srcBufs =
7560 astUnit->getSourceManager().getMemoryBufferSizes();
7562 createCXTUResourceUsageEntry(*entries,
7563 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7564 (unsigned long) srcBufs.malloc_bytes);
7565 createCXTUResourceUsageEntry(*entries,
7566 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7567 (unsigned long) srcBufs.mmap_bytes);
7568 createCXTUResourceUsageEntry(*entries,
7569 CXTUResourceUsage_SourceManager_DataStructures,
7570 (unsigned long) astContext.getSourceManager()
7571 .getDataStructureSizes());
7573 // How much memory is being used by the ExternalASTSource?
7574 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7575 const ExternalASTSource::MemoryBufferSizes &sizes =
7576 esrc->getMemoryBufferSizes();
7578 createCXTUResourceUsageEntry(*entries,
7579 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7580 (unsigned long) sizes.malloc_bytes);
7581 createCXTUResourceUsageEntry(*entries,
7582 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7583 (unsigned long) sizes.mmap_bytes);
7586 // How much memory is being used by the Preprocessor?
7587 Preprocessor &pp = astUnit->getPreprocessor();
7588 createCXTUResourceUsageEntry(*entries,
7589 CXTUResourceUsage_Preprocessor,
7590 pp.getTotalMemory());
7592 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7593 createCXTUResourceUsageEntry(*entries,
7594 CXTUResourceUsage_PreprocessingRecord,
7595 pRec->getTotalMemory());
7598 createCXTUResourceUsageEntry(*entries,
7599 CXTUResourceUsage_Preprocessor_HeaderSearch,
7600 pp.getHeaderSearchInfo().getTotalMemory());
7602 CXTUResourceUsage usage = { (void*) entries.get(),
7603 (unsigned) entries->size(),
7604 !entries->empty() ? &(*entries)[0] : nullptr };
7609 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7611 delete (MemUsageEntries*) usage.data;
7614 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7615 CXSourceRangeList *skipped = new CXSourceRangeList;
7617 skipped->ranges = nullptr;
7619 if (isNotUsableTU(TU)) {
7627 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7628 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7632 ASTContext &Ctx = astUnit->getASTContext();
7633 SourceManager &sm = Ctx.getSourceManager();
7634 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7635 FileID wantedFileID = sm.translateFile(fileEntry);
7637 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7638 std::vector<SourceRange> wantedRanges;
7639 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7641 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7642 wantedRanges.push_back(*i);
7645 skipped->count = wantedRanges.size();
7646 skipped->ranges = new CXSourceRange[skipped->count];
7647 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7648 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7653 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7655 delete[] ranges->ranges;
7662 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7663 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7664 for (unsigned I = 0; I != Usage.numEntries; ++I)
7665 fprintf(stderr, " %s: %lu\n",
7666 clang_getTUResourceUsageName(Usage.entries[I].kind),
7667 Usage.entries[I].amount);
7669 clang_disposeCXTUResourceUsage(Usage);
7672 //===----------------------------------------------------------------------===//
7673 // Misc. utility functions.
7674 //===----------------------------------------------------------------------===//
7676 /// Default to using an 8 MB stack size on "safety" threads.
7677 static unsigned SafetyStackThreadSize = 8 << 20;
7681 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7684 Size = GetSafetyThreadStackSize();
7686 return CRC.RunSafelyOnThread(Fn, Size);
7687 return CRC.RunSafely(Fn);
7690 unsigned GetSafetyThreadStackSize() {
7691 return SafetyStackThreadSize;
7694 void SetSafetyThreadStackSize(unsigned Value) {
7695 SafetyStackThreadSize = Value;
7700 void clang::setThreadBackgroundPriority() {
7701 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7704 #ifdef USE_DARWIN_THREADS
7705 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7709 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7713 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7714 DEnd = Unit->stored_diag_end();
7716 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7717 CXString Msg = clang_formatDiagnostic(&Diag,
7718 clang_defaultDiagnosticDisplayOptions());
7719 fprintf(stderr, "%s\n", clang_getCString(Msg));
7720 clang_disposeString(Msg);
7722 #ifdef LLVM_ON_WIN32
7723 // On Windows, force a flush, since there may be multiple copies of
7724 // stderr and stdout in the file system, all with different buffers
7725 // but writing to the same device.
7730 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7731 SourceLocation MacroDefLoc,
7732 CXTranslationUnit TU){
7733 if (MacroDefLoc.isInvalid() || !TU)
7735 if (!II.hadMacroDefinition())
7738 ASTUnit *Unit = cxtu::getASTUnit(TU);
7739 Preprocessor &PP = Unit->getPreprocessor();
7740 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7742 for (MacroDirective::DefInfo
7743 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7744 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7745 return Def.getMacroInfo();
7752 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7753 CXTranslationUnit TU) {
7754 if (!MacroDef || !TU)
7756 const IdentifierInfo *II = MacroDef->getName();
7760 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7763 MacroDefinitionRecord *
7764 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7765 CXTranslationUnit TU) {
7768 if (Tok.isNot(tok::raw_identifier))
7771 if (MI->getNumTokens() == 0)
7773 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7774 MI->getDefinitionEndLoc());
7775 ASTUnit *Unit = cxtu::getASTUnit(TU);
7777 // Check that the token is inside the definition and not its argument list.
7778 SourceManager &SM = Unit->getSourceManager();
7779 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7781 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7784 Preprocessor &PP = Unit->getPreprocessor();
7785 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7789 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7790 if (!II.hadMacroDefinition())
7793 // Check that the identifier is not one of the macro arguments.
7794 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7797 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7801 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7804 MacroDefinitionRecord *
7805 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7806 CXTranslationUnit TU) {
7807 if (Loc.isInvalid() || !MI || !TU)
7810 if (MI->getNumTokens() == 0)
7812 ASTUnit *Unit = cxtu::getASTUnit(TU);
7813 Preprocessor &PP = Unit->getPreprocessor();
7814 if (!PP.getPreprocessingRecord())
7816 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7818 if (PP.getRawToken(Loc, Tok))
7821 return checkForMacroInMacroDefinition(MI, Tok, TU);
7826 CXString clang_getClangVersion() {
7827 return cxstring::createDup(getClangFullVersion());
7830 } // end: extern "C"
7832 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7834 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7835 LogOS << '<' << Unit->getMainFileName() << '>';
7836 if (Unit->isMainFileAST())
7837 LogOS << " (" << Unit->getASTFileName() << ')';
7841 LogOS << "<NULL TU>";
7846 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7847 *this << FE->getName();
7851 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7852 CXString cursorName = clang_getCursorDisplayName(cursor);
7853 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7854 clang_disposeString(cursorName);
7858 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7860 unsigned Line, Column;
7861 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7862 CXString FileName = clang_getFileName(File);
7863 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7864 clang_disposeString(FileName);
7868 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7869 CXSourceLocation BLoc = clang_getRangeStart(range);
7870 CXSourceLocation ELoc = clang_getRangeEnd(range);
7873 unsigned BLine, BColumn;
7874 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7877 unsigned ELine, EColumn;
7878 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7880 CXString BFileName = clang_getFileName(BFile);
7881 if (BFile == EFile) {
7882 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7883 BLine, BColumn, ELine, EColumn);
7885 CXString EFileName = clang_getFileName(EFile);
7886 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7888 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7890 clang_disposeString(EFileName);
7892 clang_disposeString(BFileName);
7896 Logger &cxindex::Logger::operator<<(CXString Str) {
7897 *this << clang_getCString(Str);
7901 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7906 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7908 cxindex::Logger::~Logger() {
7909 llvm::sys::ScopedLock L(*LoggingMutex);
7911 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7913 raw_ostream &OS = llvm::errs();
7914 OS << "[libclang:" << Name << ':';
7916 #ifdef USE_DARWIN_THREADS
7917 // TODO: Portability.
7918 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7922 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7923 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7927 llvm::sys::PrintStackTrace(OS);
7928 OS << "--------------------------------------------------\n";