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 //===----------------------------------------------------------------------===//
17 #include "CXTranslationUnit.h"
20 #include "CXSourceLocation.h"
21 #include "CIndexDiagnostic.h"
22 #include "CursorVisitor.h"
24 #include "clang/Basic/Version.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Frontend/ASTUnit.h"
29 #include "clang/Frontend/CompilerInstance.h"
30 #include "clang/Frontend/FrontendDiagnostic.h"
31 #include "clang/Lex/Lexer.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Lex/PreprocessingRecord.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/Optional.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/SaveAndRestore.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Mutex.h"
45 #include "llvm/Support/Program.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/Threading.h"
48 #include "llvm/Support/Compiler.h"
50 using namespace clang;
51 using namespace clang::cxcursor;
52 using namespace clang::cxstring;
53 using namespace clang::cxtu;
54 using namespace clang::cxindex;
56 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
59 CXTranslationUnit D = new CXTranslationUnitImpl();
62 D->StringPool = createCXStringPool();
67 cxtu::CXTUOwner::~CXTUOwner() {
69 clang_disposeTranslationUnit(TU);
72 /// \brief Compare two source ranges to determine their relative position in
73 /// the translation unit.
74 static RangeComparisonResult RangeCompare(SourceManager &SM,
77 assert(R1.isValid() && "First range is invalid?");
78 assert(R2.isValid() && "Second range is invalid?");
79 if (R1.getEnd() != R2.getBegin() &&
80 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
82 if (R2.getEnd() != R1.getBegin() &&
83 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
88 /// \brief Determine if a source location falls within, before, or after a
89 /// a given source range.
90 static RangeComparisonResult LocationCompare(SourceManager &SM,
91 SourceLocation L, SourceRange R) {
92 assert(R.isValid() && "First range is invalid?");
93 assert(L.isValid() && "Second range is invalid?");
94 if (L == R.getBegin() || L == R.getEnd())
96 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 /// \brief Translate a Clang source range into a CIndex source range.
105 /// Clang internally represents ranges where the end location points to the
106 /// start of the token at the end. However, for external clients it is more
107 /// useful to have a CXSourceRange be a proper half-open interval. This routine
108 /// does the appropriate translation.
109 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
110 const LangOptions &LangOpts,
111 const CharSourceRange &R) {
112 // We want the last character in this location, so we will adjust the
113 // location accordingly.
114 SourceLocation EndLoc = R.getEnd();
115 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
116 EndLoc = SM.getExpansionRange(EndLoc).second;
117 if (R.isTokenRange() && !EndLoc.isInvalid()) {
118 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
120 EndLoc = EndLoc.getLocWithOffset(Length);
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
133 static SourceRange getRawCursorExtent(CXCursor C);
134 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
137 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
138 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
141 /// \brief Visit the given cursor and, if requested by the visitor,
144 /// \param Cursor the cursor to visit.
146 /// \param CheckRegionOfInterest if true, then the caller already checked that
147 /// this cursor is within the region of interest.
149 /// \returns true if the visitation should be aborted, false if it
151 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
152 if (clang_isInvalid(Cursor.kind))
155 if (clang_isDeclaration(Cursor.kind)) {
156 Decl *D = getCursorDecl(Cursor);
158 assert(0 && "Invalid declaration cursor");
159 return true; // abort.
162 // Ignore implicit declarations, unless it's an objc method because
163 // currently we should report implicit methods for properties when indexing.
164 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
168 // If we have a range of interest, and this cursor doesn't intersect with it,
170 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
171 SourceRange Range = getRawCursorExtent(Cursor);
172 if (Range.isInvalid() || CompareRegionOfInterest(Range))
176 switch (Visitor(Cursor, Parent, ClientData)) {
177 case CXChildVisit_Break:
180 case CXChildVisit_Continue:
183 case CXChildVisit_Recurse:
184 return VisitChildren(Cursor);
187 llvm_unreachable("Invalid CXChildVisitResult!");
190 static bool visitPreprocessedEntitiesInRange(SourceRange R,
191 PreprocessingRecord &PPRec,
192 CursorVisitor &Visitor) {
193 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
196 if (!Visitor.shouldVisitIncludedEntities()) {
197 // If the begin/end of the range lie in the same FileID, do the optimization
198 // where we skip preprocessed entities that do not come from the same FileID.
199 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
200 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
204 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
205 Entities = PPRec.getPreprocessedEntitiesInRange(R);
206 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
210 void CursorVisitor::visitFileRegion() {
211 if (RegionOfInterest.isInvalid())
214 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
215 SourceManager &SM = Unit->getSourceManager();
217 std::pair<FileID, unsigned>
218 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
219 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
221 if (End.first != Begin.first) {
222 // If the end does not reside in the same file, try to recover by
223 // picking the end of the file of begin location.
224 End.first = Begin.first;
225 End.second = SM.getFileIDSize(Begin.first);
228 assert(Begin.first == End.first);
229 if (Begin.second > End.second)
232 FileID File = Begin.first;
233 unsigned Offset = Begin.second;
234 unsigned Length = End.second - Begin.second;
236 if (!VisitDeclsOnly && !VisitPreprocessorLast)
237 if (visitPreprocessedEntitiesInRegion())
238 return; // visitation break.
240 visitDeclsFromFileRegion(File, Offset, Length);
242 if (!VisitDeclsOnly && VisitPreprocessorLast)
243 visitPreprocessedEntitiesInRegion();
246 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
250 for (DeclContext *DeclDC = D->getLexicalDeclContext();
251 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
258 void CursorVisitor::visitDeclsFromFileRegion(FileID File,
259 unsigned Offset, unsigned Length) {
260 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
261 SourceManager &SM = Unit->getSourceManager();
262 SourceRange Range = RegionOfInterest;
264 SmallVector<Decl *, 16> Decls;
265 Unit->findFileRegionDecls(File, Offset, Length, Decls);
267 // If we didn't find any file level decls for the file, try looking at the
268 // file that it was included from.
269 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
270 bool Invalid = false;
271 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
275 SourceLocation Outer;
276 if (SLEntry.isFile())
277 Outer = SLEntry.getFile().getIncludeLoc();
279 Outer = SLEntry.getExpansion().getExpansionLocStart();
280 if (Outer.isInvalid())
283 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
285 Unit->findFileRegionDecls(File, Offset, Length, Decls);
288 assert(!Decls.empty());
290 bool VisitedAtLeastOnce = false;
291 DeclContext *CurDC = 0;
292 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
293 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
295 if (D->getSourceRange().isInvalid())
298 if (isInLexicalContext(D, CurDC))
301 CurDC = dyn_cast<DeclContext>(D);
303 if (TagDecl *TD = dyn_cast<TagDecl>(D))
304 if (!TD->isFreeStanding())
307 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
308 if (CompRes == RangeBefore)
310 if (CompRes == RangeAfter)
313 assert(CompRes == RangeOverlap);
314 VisitedAtLeastOnce = true;
316 if (isa<ObjCContainerDecl>(D)) {
317 FileDI_current = &DIt;
323 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
327 if (VisitedAtLeastOnce)
330 // No Decls overlapped with the range. Move up the lexical context until there
331 // is a context that contains the range or we reach the translation unit
333 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
334 : (*(DIt-1))->getLexicalDeclContext();
336 while (DC && !DC->isTranslationUnit()) {
337 Decl *D = cast<Decl>(DC);
338 SourceRange CurDeclRange = D->getSourceRange();
339 if (CurDeclRange.isInvalid())
342 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
343 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
347 DC = D->getLexicalDeclContext();
351 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
352 if (!AU->getPreprocessor().getPreprocessingRecord())
355 PreprocessingRecord &PPRec
356 = *AU->getPreprocessor().getPreprocessingRecord();
357 SourceManager &SM = AU->getSourceManager();
359 if (RegionOfInterest.isValid()) {
360 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
361 SourceLocation B = MappedRange.getBegin();
362 SourceLocation E = MappedRange.getEnd();
364 if (AU->isInPreambleFileID(B)) {
365 if (SM.isLoadedSourceLocation(E))
366 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
369 // Beginning of range lies in the preamble but it also extends beyond
370 // it into the main file. Split the range into 2 parts, one covering
371 // the preamble and another covering the main file. This allows subsequent
372 // calls to visitPreprocessedEntitiesInRange to accept a source range that
373 // lies in the same FileID, allowing it to skip preprocessed entities that
374 // do not come from the same FileID.
376 visitPreprocessedEntitiesInRange(
377 SourceRange(B, AU->getEndOfPreambleFileID()),
379 if (breaked) return true;
380 return visitPreprocessedEntitiesInRange(
381 SourceRange(AU->getStartOfMainFileID(), E),
385 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
389 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
392 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
395 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
398 template<typename InputIterator>
399 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
401 PreprocessingRecord &PPRec,
403 for (; First != Last; ++First) {
404 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
407 PreprocessedEntity *PPE = *First;
408 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
409 if (Visit(MakeMacroExpansionCursor(ME, TU)))
415 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
416 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
422 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
423 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
433 /// \brief Visit the children of the given cursor.
435 /// \returns true if the visitation should be aborted, false if it
437 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
438 if (clang_isReference(Cursor.kind) &&
439 Cursor.kind != CXCursor_CXXBaseSpecifier) {
440 // By definition, references have no children.
444 // Set the Parent field to Cursor, then back to its old value once we're
446 SetParentRAII SetParent(Parent, StmtParent, Cursor);
448 if (clang_isDeclaration(Cursor.kind)) {
449 Decl *D = getCursorDecl(Cursor);
453 return VisitAttributes(D) || Visit(D);
456 if (clang_isStatement(Cursor.kind)) {
457 if (Stmt *S = getCursorStmt(Cursor))
463 if (clang_isExpression(Cursor.kind)) {
464 if (Expr *E = getCursorExpr(Cursor))
470 if (clang_isTranslationUnit(Cursor.kind)) {
471 CXTranslationUnit tu = getCursorTU(Cursor);
472 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
474 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
475 for (unsigned I = 0; I != 2; ++I) {
477 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
478 RegionOfInterest.isInvalid()) {
479 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
480 TLEnd = CXXUnit->top_level_end();
482 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
485 } else if (VisitDeclContext(
486 CXXUnit->getASTContext().getTranslationUnitDecl()))
491 // Walk the preprocessing record.
492 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
493 visitPreprocessedEntitiesInRegion();
499 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
500 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
501 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
502 return Visit(BaseTSInfo->getTypeLoc());
507 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
508 IBOutletCollectionAttr *A =
509 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
510 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
511 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
512 A->getInterfaceLoc(), TU));
515 // Nothing to visit at the moment.
519 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
520 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
521 if (Visit(TSInfo->getTypeLoc()))
524 if (Stmt *Body = B->getBody())
525 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
530 llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
531 if (RegionOfInterest.isValid()) {
532 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
533 if (Range.isInvalid())
534 return llvm::Optional<bool>();
536 switch (CompareRegionOfInterest(Range)) {
538 // This declaration comes before the region of interest; skip it.
539 return llvm::Optional<bool>();
542 // This declaration comes after the region of interest; we're done.
546 // This declaration overlaps the region of interest; visit it.
553 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
554 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
556 // FIXME: Eventually remove. This part of a hack to support proper
557 // iteration over all Decls contained lexically within an ObjC container.
558 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
559 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
561 for ( ; I != E; ++I) {
563 if (D->getLexicalDeclContext() != DC)
565 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
567 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
568 // declarations is a mismatch with the compiler semantics.
569 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
570 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
571 if (!ID->isThisDeclarationADefinition())
572 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
574 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
575 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
576 if (!PD->isThisDeclarationADefinition())
577 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
580 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
585 if (Visit(Cursor, true))
591 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
592 llvm_unreachable("Translation units are visited directly by Visit()");
595 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
602 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
603 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
604 return Visit(TSInfo->getTypeLoc());
609 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
610 return VisitDeclContext(D);
613 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
614 ClassTemplateSpecializationDecl *D) {
615 bool ShouldVisitBody = false;
616 switch (D->getSpecializationKind()) {
618 case TSK_ImplicitInstantiation:
622 case TSK_ExplicitInstantiationDeclaration:
623 case TSK_ExplicitInstantiationDefinition:
626 case TSK_ExplicitSpecialization:
627 ShouldVisitBody = true;
631 // Visit the template arguments used in the specialization.
632 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
633 TypeLoc TL = SpecType->getTypeLoc();
634 if (TemplateSpecializationTypeLoc *TSTLoc
635 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
636 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
637 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
642 if (ShouldVisitBody && VisitCXXRecordDecl(D))
648 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
649 ClassTemplatePartialSpecializationDecl *D) {
650 // FIXME: Visit the "outer" template parameter lists on the TagDecl
651 // before visiting these template parameters.
652 if (VisitTemplateParameters(D->getTemplateParameters()))
655 // Visit the partial specialization arguments.
656 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
657 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
658 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
661 return VisitCXXRecordDecl(D);
664 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
665 // Visit the default argument.
666 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
667 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
668 if (Visit(DefArg->getTypeLoc()))
674 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
675 if (Expr *Init = D->getInitExpr())
676 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
680 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
681 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
682 if (Visit(TSInfo->getTypeLoc()))
685 // Visit the nested-name-specifier, if present.
686 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
687 if (VisitNestedNameSpecifierLoc(QualifierLoc))
693 /// \brief Compare two base or member initializers based on their source order.
694 static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
695 CXXCtorInitializer const * const *X
696 = static_cast<CXXCtorInitializer const * const *>(Xp);
697 CXXCtorInitializer const * const *Y
698 = static_cast<CXXCtorInitializer const * const *>(Yp);
700 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
702 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
709 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
710 // Visit the function declaration's syntactic components in the order
711 // written. This requires a bit of work.
712 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
713 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
715 // If we have a function declared directly (without the use of a typedef),
716 // visit just the return type. Otherwise, just visit the function's type
718 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
722 // Visit the nested-name-specifier, if present.
723 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
724 if (VisitNestedNameSpecifierLoc(QualifierLoc))
727 // Visit the declaration name.
728 if (VisitDeclarationNameInfo(ND->getNameInfo()))
731 // FIXME: Visit explicitly-specified template arguments!
733 // Visit the function parameters, if we have a function type.
734 if (FTL && VisitFunctionTypeLoc(*FTL, true))
737 // FIXME: Attributes?
740 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
742 // Find the initializers that were written in the source.
743 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
744 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
745 IEnd = Constructor->init_end();
747 if (!(*I)->isWritten())
750 WrittenInits.push_back(*I);
753 // Sort the initializers in source order
754 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
755 &CompareCXXCtorInitializers);
757 // Visit the initializers in source order
758 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
759 CXXCtorInitializer *Init = WrittenInits[I];
760 if (Init->isAnyMemberInitializer()) {
761 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
762 Init->getMemberLocation(), TU)))
764 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
765 if (Visit(TInfo->getTypeLoc()))
769 // Visit the initializer value.
770 if (Expr *Initializer = Init->getInit())
771 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
776 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
783 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
784 if (VisitDeclaratorDecl(D))
787 if (Expr *BitWidth = D->getBitWidth())
788 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
793 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
794 if (VisitDeclaratorDecl(D))
797 if (Expr *Init = D->getInit())
798 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
803 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
804 if (VisitDeclaratorDecl(D))
807 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
808 if (Expr *DefArg = D->getDefaultArgument())
809 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
814 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
815 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
816 // before visiting these template parameters.
817 if (VisitTemplateParameters(D->getTemplateParameters()))
820 return VisitFunctionDecl(D->getTemplatedDecl());
823 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
824 // FIXME: Visit the "outer" template parameter lists on the TagDecl
825 // before visiting these template parameters.
826 if (VisitTemplateParameters(D->getTemplateParameters()))
829 return VisitCXXRecordDecl(D->getTemplatedDecl());
832 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
833 if (VisitTemplateParameters(D->getTemplateParameters()))
836 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
837 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
844 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
845 if (Visit(TSInfo->getTypeLoc()))
848 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
849 PEnd = ND->param_end();
851 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
855 if (ND->isThisDeclarationADefinition() &&
856 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
862 template <typename DeclIt>
863 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
864 SourceManager &SM, SourceLocation EndLoc,
865 SmallVectorImpl<Decl *> &Decls) {
866 DeclIt next = *DI_current;
867 while (++next != DE_current) {
868 Decl *D_next = *next;
871 SourceLocation L = D_next->getLocStart();
874 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
876 Decls.push_back(D_next);
884 struct ContainerDeclsSort {
886 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
887 bool operator()(Decl *A, Decl *B) {
888 SourceLocation L_A = A->getLocStart();
889 SourceLocation L_B = B->getLocStart();
890 assert(L_A.isValid() && L_B.isValid());
891 return SM.isBeforeInTranslationUnit(L_A, L_B);
896 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
897 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
898 // an @implementation can lexically contain Decls that are not properly
899 // nested in the AST. When we identify such cases, we need to retrofit
900 // this nesting here.
901 if (!DI_current && !FileDI_current)
902 return VisitDeclContext(D);
904 // Scan the Decls that immediately come after the container
905 // in the current DeclContext. If any fall within the
906 // container's lexical region, stash them into a vector
907 // for later processing.
908 SmallVector<Decl *, 24> DeclsInContainer;
909 SourceLocation EndLoc = D->getSourceRange().getEnd();
910 SourceManager &SM = AU->getSourceManager();
911 if (EndLoc.isValid()) {
913 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
916 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
922 if (DeclsInContainer.empty())
923 return VisitDeclContext(D);
925 // Get all the Decls in the DeclContext, and sort them with the
926 // additional ones we've collected. Then visit them.
927 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
930 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
931 subDecl->getLocStart().isInvalid())
933 DeclsInContainer.push_back(subDecl);
936 // Now sort the Decls so that they appear in lexical order.
937 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
938 ContainerDeclsSort(SM));
940 // Now visit the decls.
941 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
942 E = DeclsInContainer.end(); I != E; ++I) {
943 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
944 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
949 if (Visit(Cursor, true))
955 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
956 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
960 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
961 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
962 E = ND->protocol_end(); I != E; ++I, ++PL)
963 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966 return VisitObjCContainerDecl(ND);
969 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
970 if (!PID->isThisDeclarationADefinition())
971 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
973 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
974 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
975 E = PID->protocol_end(); I != E; ++I, ++PL)
976 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
979 return VisitObjCContainerDecl(PID);
982 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
983 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
986 // FIXME: This implements a workaround with @property declarations also being
987 // installed in the DeclContext for the @interface. Eventually this code
988 // should be removed.
989 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
990 if (!CDecl || !CDecl->IsClassExtension())
993 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
997 IdentifierInfo *PropertyId = PD->getIdentifier();
998 ObjCPropertyDecl *prevDecl =
999 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1004 // Visit synthesized methods since they will be skipped when visiting
1006 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1007 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1008 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1011 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1012 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1013 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1019 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1020 if (!D->isThisDeclarationADefinition()) {
1021 // Forward declaration is treated like a reference.
1022 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1025 // Issue callbacks for super class.
1026 if (D->getSuperClass() &&
1027 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1028 D->getSuperClassLoc(),
1032 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1033 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1034 E = D->protocol_end(); I != E; ++I, ++PL)
1035 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1038 return VisitObjCContainerDecl(D);
1041 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1042 return VisitObjCContainerDecl(D);
1045 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1046 // 'ID' could be null when dealing with invalid code.
1047 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1048 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1051 return VisitObjCImplDecl(D);
1054 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1056 // Issue callbacks for super class.
1057 // FIXME: No source location information!
1058 if (D->getSuperClass() &&
1059 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1060 D->getSuperClassLoc(),
1065 return VisitObjCImplDecl(D);
1068 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1069 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1070 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1075 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1076 return VisitDeclContext(D);
1079 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1080 // Visit nested-name-specifier.
1081 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1082 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1085 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1086 D->getTargetNameLoc(), TU));
1089 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1090 // Visit nested-name-specifier.
1091 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1092 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1096 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099 return VisitDeclarationNameInfo(D->getNameInfo());
1102 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1103 // Visit nested-name-specifier.
1104 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1108 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1109 D->getIdentLocation(), TU));
1112 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1113 // Visit nested-name-specifier.
1114 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1115 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1119 return VisitDeclarationNameInfo(D->getNameInfo());
1122 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1123 UnresolvedUsingTypenameDecl *D) {
1124 // Visit nested-name-specifier.
1125 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1126 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1132 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1133 switch (Name.getName().getNameKind()) {
1134 case clang::DeclarationName::Identifier:
1135 case clang::DeclarationName::CXXLiteralOperatorName:
1136 case clang::DeclarationName::CXXOperatorName:
1137 case clang::DeclarationName::CXXUsingDirective:
1140 case clang::DeclarationName::CXXConstructorName:
1141 case clang::DeclarationName::CXXDestructorName:
1142 case clang::DeclarationName::CXXConversionFunctionName:
1143 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1144 return Visit(TSInfo->getTypeLoc());
1147 case clang::DeclarationName::ObjCZeroArgSelector:
1148 case clang::DeclarationName::ObjCOneArgSelector:
1149 case clang::DeclarationName::ObjCMultiArgSelector:
1150 // FIXME: Per-identifier location info?
1154 llvm_unreachable("Invalid DeclarationName::Kind!");
1157 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1158 SourceRange Range) {
1159 // FIXME: This whole routine is a hack to work around the lack of proper
1160 // source information in nested-name-specifiers (PR5791). Since we do have
1161 // a beginning source location, we can visit the first component of the
1162 // nested-name-specifier, if it's a single-token component.
1166 // Get the first component in the nested-name-specifier.
1167 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170 switch (NNS->getKind()) {
1171 case NestedNameSpecifier::Namespace:
1172 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175 case NestedNameSpecifier::NamespaceAlias:
1176 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1177 Range.getBegin(), TU));
1179 case NestedNameSpecifier::TypeSpec: {
1180 // If the type has a form where we know that the beginning of the source
1181 // range matches up with a reference cursor. Visit the appropriate reference
1183 const Type *T = NNS->getAsType();
1184 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1185 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1186 if (const TagType *Tag = dyn_cast<TagType>(T))
1187 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1188 if (const TemplateSpecializationType *TST
1189 = dyn_cast<TemplateSpecializationType>(T))
1190 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1194 case NestedNameSpecifier::TypeSpecWithTemplate:
1195 case NestedNameSpecifier::Global:
1196 case NestedNameSpecifier::Identifier:
1204 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1205 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1206 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1207 Qualifiers.push_back(Qualifier);
1209 while (!Qualifiers.empty()) {
1210 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1211 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1212 switch (NNS->getKind()) {
1213 case NestedNameSpecifier::Namespace:
1214 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1215 Q.getLocalBeginLoc(),
1221 case NestedNameSpecifier::NamespaceAlias:
1222 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1223 Q.getLocalBeginLoc(),
1229 case NestedNameSpecifier::TypeSpec:
1230 case NestedNameSpecifier::TypeSpecWithTemplate:
1231 if (Visit(Q.getTypeLoc()))
1236 case NestedNameSpecifier::Global:
1237 case NestedNameSpecifier::Identifier:
1245 bool CursorVisitor::VisitTemplateParameters(
1246 const TemplateParameterList *Params) {
1250 for (TemplateParameterList::const_iterator P = Params->begin(),
1251 PEnd = Params->end();
1253 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1260 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1261 switch (Name.getKind()) {
1262 case TemplateName::Template:
1263 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1265 case TemplateName::OverloadedTemplate:
1266 // Visit the overloaded template set.
1267 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1272 case TemplateName::DependentTemplate:
1273 // FIXME: Visit nested-name-specifier.
1276 case TemplateName::QualifiedTemplate:
1277 // FIXME: Visit nested-name-specifier.
1278 return Visit(MakeCursorTemplateRef(
1279 Name.getAsQualifiedTemplateName()->getDecl(),
1282 case TemplateName::SubstTemplateTemplateParm:
1283 return Visit(MakeCursorTemplateRef(
1284 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1287 case TemplateName::SubstTemplateTemplateParmPack:
1288 return Visit(MakeCursorTemplateRef(
1289 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1293 llvm_unreachable("Invalid TemplateName::Kind!");
1296 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1297 switch (TAL.getArgument().getKind()) {
1298 case TemplateArgument::Null:
1299 case TemplateArgument::Integral:
1300 case TemplateArgument::Pack:
1303 case TemplateArgument::Type:
1304 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1305 return Visit(TSInfo->getTypeLoc());
1308 case TemplateArgument::Declaration:
1309 if (Expr *E = TAL.getSourceDeclExpression())
1310 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1313 case TemplateArgument::Expression:
1314 if (Expr *E = TAL.getSourceExpression())
1315 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1318 case TemplateArgument::Template:
1319 case TemplateArgument::TemplateExpansion:
1320 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1323 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1324 TAL.getTemplateNameLoc());
1327 llvm_unreachable("Invalid TemplateArgument::Kind!");
1330 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1331 return VisitDeclContext(D);
1334 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1335 return Visit(TL.getUnqualifiedLoc());
1338 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1339 ASTContext &Context = AU->getASTContext();
1341 // Some builtin types (such as Objective-C's "id", "sel", and
1342 // "Class") have associated declarations. Create cursors for those.
1344 switch (TL.getTypePtr()->getKind()) {
1346 case BuiltinType::Void:
1347 case BuiltinType::NullPtr:
1348 case BuiltinType::Dependent:
1349 #define BUILTIN_TYPE(Id, SingletonId)
1350 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1352 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1353 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1354 #include "clang/AST/BuiltinTypes.def"
1357 case BuiltinType::ObjCId:
1358 VisitType = Context.getObjCIdType();
1361 case BuiltinType::ObjCClass:
1362 VisitType = Context.getObjCClassType();
1365 case BuiltinType::ObjCSel:
1366 VisitType = Context.getObjCSelType();
1370 if (!VisitType.isNull()) {
1371 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1372 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1379 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1380 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1383 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1384 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1387 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1388 if (TL.isDefinition())
1389 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1391 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1394 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1398 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1399 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1405 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1406 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1409 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1410 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1418 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1419 return Visit(TL.getPointeeLoc());
1422 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1423 return Visit(TL.getInnerLoc());
1426 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1427 return Visit(TL.getPointeeLoc());
1430 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1431 return Visit(TL.getPointeeLoc());
1434 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1435 return Visit(TL.getPointeeLoc());
1438 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1439 return Visit(TL.getPointeeLoc());
1442 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1443 return Visit(TL.getPointeeLoc());
1446 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1447 return Visit(TL.getModifiedLoc());
1450 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1451 bool SkipResultType) {
1452 if (!SkipResultType && Visit(TL.getResultLoc()))
1455 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1456 if (Decl *D = TL.getArg(I))
1457 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1463 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1464 if (Visit(TL.getElementLoc()))
1467 if (Expr *Size = TL.getSizeExpr())
1468 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1473 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1474 TemplateSpecializationTypeLoc TL) {
1475 // Visit the template name.
1476 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1477 TL.getTemplateNameLoc()))
1480 // Visit the template arguments.
1481 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1482 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1488 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1489 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1492 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1493 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1494 return Visit(TSInfo->getTypeLoc());
1499 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1500 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501 return Visit(TSInfo->getTypeLoc());
1506 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1507 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1513 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1514 DependentTemplateSpecializationTypeLoc TL) {
1515 // Visit the nested-name-specifier, if there is one.
1516 if (TL.getQualifierLoc() &&
1517 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1520 // Visit the template arguments.
1521 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1522 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1528 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1529 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1532 return Visit(TL.getNamedTypeLoc());
1535 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1536 return Visit(TL.getPatternLoc());
1539 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1540 if (Expr *E = TL.getUnderlyingExpr())
1541 return Visit(MakeCXCursor(E, StmtParent, TU));
1546 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1547 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1550 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1551 return Visit(TL.getValueLoc());
1554 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1555 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1556 return Visit##PARENT##Loc(TL); \
1559 DEFAULT_TYPELOC_IMPL(Complex, Type)
1560 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1561 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1562 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1563 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1564 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1565 DEFAULT_TYPELOC_IMPL(Vector, Type)
1566 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1567 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1568 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1569 DEFAULT_TYPELOC_IMPL(Record, TagType)
1570 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1571 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1572 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1573 DEFAULT_TYPELOC_IMPL(Auto, Type)
1575 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1576 // Visit the nested-name-specifier, if present.
1577 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1578 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1581 if (D->isCompleteDefinition()) {
1582 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1583 E = D->bases_end(); I != E; ++I) {
1584 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1589 return VisitTagDecl(D);
1592 bool CursorVisitor::VisitAttributes(Decl *D) {
1593 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1595 if (Visit(MakeCXCursor(*i, D, TU)))
1601 //===----------------------------------------------------------------------===//
1602 // Data-recursive visitor methods.
1603 //===----------------------------------------------------------------------===//
1606 #define DEF_JOB(NAME, DATA, KIND)\
1607 class NAME : public VisitorJob {\
1609 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1610 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1611 DATA *get() const { return static_cast<DATA*>(data[0]); }\
1614 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1615 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1616 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1617 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1618 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1619 ExplicitTemplateArgsVisitKind)
1620 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1621 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1624 class DeclVisit : public VisitorJob {
1626 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1627 VisitorJob(parent, VisitorJob::DeclVisitKind,
1628 d, isFirst ? (void*) 1 : (void*) 0) {}
1629 static bool classof(const VisitorJob *VJ) {
1630 return VJ->getKind() == DeclVisitKind;
1632 Decl *get() const { return static_cast<Decl*>(data[0]); }
1633 bool isFirst() const { return data[1] ? true : false; }
1635 class TypeLocVisit : public VisitorJob {
1637 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1638 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1639 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1641 static bool classof(const VisitorJob *VJ) {
1642 return VJ->getKind() == TypeLocVisitKind;
1645 TypeLoc get() const {
1646 QualType T = QualType::getFromOpaquePtr(data[0]);
1647 return TypeLoc(T, data[1]);
1651 class LabelRefVisit : public VisitorJob {
1653 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1654 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1655 labelLoc.getPtrEncoding()) {}
1657 static bool classof(const VisitorJob *VJ) {
1658 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1660 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1661 SourceLocation getLoc() const {
1662 return SourceLocation::getFromPtrEncoding(data[1]); }
1665 class NestedNameSpecifierLocVisit : public VisitorJob {
1667 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1669 Qualifier.getNestedNameSpecifier(),
1670 Qualifier.getOpaqueData()) { }
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1676 NestedNameSpecifierLoc get() const {
1677 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1682 class DeclarationNameInfoVisit : public VisitorJob {
1684 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1685 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1689 DeclarationNameInfo get() const {
1690 Stmt *S = static_cast<Stmt*>(data[0]);
1691 switch (S->getStmtClass()) {
1693 llvm_unreachable("Unhandled Stmt");
1694 case clang::Stmt::MSDependentExistsStmtClass:
1695 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1696 case Stmt::CXXDependentScopeMemberExprClass:
1697 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1698 case Stmt::DependentScopeDeclRefExprClass:
1699 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1703 class MemberRefVisit : public VisitorJob {
1705 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1706 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1707 L.getPtrEncoding()) {}
1708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1711 FieldDecl *get() const {
1712 return static_cast<FieldDecl*>(data[0]);
1714 SourceLocation getLoc() const {
1715 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1718 class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1719 VisitorWorkList &WL;
1722 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1723 : WL(wl), Parent(parent) {}
1725 void VisitAddrLabelExpr(AddrLabelExpr *E);
1726 void VisitBlockExpr(BlockExpr *B);
1727 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1728 void VisitCompoundStmt(CompoundStmt *S);
1729 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1730 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1731 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1732 void VisitCXXNewExpr(CXXNewExpr *E);
1733 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1734 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1735 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1736 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1737 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1738 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1739 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1740 void VisitCXXCatchStmt(CXXCatchStmt *S);
1741 void VisitDeclRefExpr(DeclRefExpr *D);
1742 void VisitDeclStmt(DeclStmt *S);
1743 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1744 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1745 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1746 void VisitForStmt(ForStmt *FS);
1747 void VisitGotoStmt(GotoStmt *GS);
1748 void VisitIfStmt(IfStmt *If);
1749 void VisitInitListExpr(InitListExpr *IE);
1750 void VisitMemberExpr(MemberExpr *M);
1751 void VisitOffsetOfExpr(OffsetOfExpr *E);
1752 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1753 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1754 void VisitOverloadExpr(OverloadExpr *E);
1755 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1756 void VisitStmt(Stmt *S);
1757 void VisitSwitchStmt(SwitchStmt *S);
1758 void VisitWhileStmt(WhileStmt *W);
1759 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1760 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1761 void VisitTypeTraitExpr(TypeTraitExpr *E);
1762 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1763 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1764 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1765 void VisitVAArgExpr(VAArgExpr *E);
1766 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1767 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1768 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1769 void VisitLambdaExpr(LambdaExpr *E);
1772 void AddDeclarationNameInfo(Stmt *S);
1773 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1774 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1775 void AddMemberRef(FieldDecl *D, SourceLocation L);
1776 void AddStmt(Stmt *S);
1777 void AddDecl(Decl *D, bool isFirst = true);
1778 void AddTypeLoc(TypeSourceInfo *TI);
1779 void EnqueueChildren(Stmt *S);
1781 } // end anonyous namespace
1783 void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1784 // 'S' should always be non-null, since it comes from the
1785 // statement we are visiting.
1786 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1790 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1792 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1795 void EnqueueVisitor::AddStmt(Stmt *S) {
1797 WL.push_back(StmtVisit(S, Parent));
1799 void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1801 WL.push_back(DeclVisit(D, Parent, isFirst));
1803 void EnqueueVisitor::
1804 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1806 WL.push_back(ExplicitTemplateArgsVisit(
1807 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1809 void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1811 WL.push_back(MemberRefVisit(D, L, Parent));
1813 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1815 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1817 void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1818 unsigned size = WL.size();
1819 for (Stmt::child_range Child = S->children(); Child; ++Child) {
1822 if (size == WL.size())
1824 // Now reverse the entries we just added. This will match the DFS
1825 // ordering performed by the worklist.
1826 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1829 void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1830 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1832 void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1833 AddDecl(B->getBlockDecl());
1835 void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1837 AddTypeLoc(E->getTypeSourceInfo());
1839 void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1840 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1841 E = S->body_rend(); I != E; ++I) {
1845 void EnqueueVisitor::
1846 VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1847 AddStmt(S->getSubStmt());
1848 AddDeclarationNameInfo(S);
1849 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1850 AddNestedNameSpecifierLoc(QualifierLoc);
1853 void EnqueueVisitor::
1854 VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1855 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1856 AddDeclarationNameInfo(E);
1857 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1858 AddNestedNameSpecifierLoc(QualifierLoc);
1859 if (!E->isImplicitAccess())
1860 AddStmt(E->getBase());
1862 void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1863 // Enqueue the initializer , if any.
1864 AddStmt(E->getInitializer());
1865 // Enqueue the array size, if any.
1866 AddStmt(E->getArraySize());
1867 // Enqueue the allocated type.
1868 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1869 // Enqueue the placement arguments.
1870 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1871 AddStmt(E->getPlacementArg(I-1));
1873 void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1874 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1875 AddStmt(CE->getArg(I-1));
1876 AddStmt(CE->getCallee());
1877 AddStmt(CE->getArg(0));
1879 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1880 // Visit the name of the type being destroyed.
1881 AddTypeLoc(E->getDestroyedTypeInfo());
1882 // Visit the scope type that looks disturbingly like the nested-name-specifier
1884 AddTypeLoc(E->getScopeTypeInfo());
1885 // Visit the nested-name-specifier.
1886 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1887 AddNestedNameSpecifierLoc(QualifierLoc);
1888 // Visit base expression.
1889 AddStmt(E->getBase());
1891 void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1892 AddTypeLoc(E->getTypeSourceInfo());
1894 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1896 AddTypeLoc(E->getTypeSourceInfo());
1898 void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1900 if (E->isTypeOperand())
1901 AddTypeLoc(E->getTypeOperandSourceInfo());
1904 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1907 AddTypeLoc(E->getTypeSourceInfo());
1909 void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1911 if (E->isTypeOperand())
1912 AddTypeLoc(E->getTypeOperandSourceInfo());
1915 void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1917 AddDecl(S->getExceptionDecl());
1920 void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1921 if (DR->hasExplicitTemplateArgs()) {
1922 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1924 WL.push_back(DeclRefExprParts(DR, Parent));
1926 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1927 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1928 AddDeclarationNameInfo(E);
1929 AddNestedNameSpecifierLoc(E->getQualifierLoc());
1931 void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1932 unsigned size = WL.size();
1933 bool isFirst = true;
1934 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1936 AddDecl(*D, isFirst);
1939 if (size == WL.size())
1941 // Now reverse the entries we just added. This will match the DFS
1942 // ordering performed by the worklist.
1943 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1946 void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1947 AddStmt(E->getInit());
1948 typedef DesignatedInitExpr::Designator Designator;
1949 for (DesignatedInitExpr::reverse_designators_iterator
1950 D = E->designators_rbegin(), DEnd = E->designators_rend();
1952 if (D->isFieldDesignator()) {
1953 if (FieldDecl *Field = D->getField())
1954 AddMemberRef(Field, D->getFieldLoc());
1957 if (D->isArrayDesignator()) {
1958 AddStmt(E->getArrayIndex(*D));
1961 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1962 AddStmt(E->getArrayRangeEnd(*D));
1963 AddStmt(E->getArrayRangeStart(*D));
1966 void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1968 AddTypeLoc(E->getTypeInfoAsWritten());
1970 void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1971 AddStmt(FS->getBody());
1972 AddStmt(FS->getInc());
1973 AddStmt(FS->getCond());
1974 AddDecl(FS->getConditionVariable());
1975 AddStmt(FS->getInit());
1977 void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1978 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1980 void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1981 AddStmt(If->getElse());
1982 AddStmt(If->getThen());
1983 AddStmt(If->getCond());
1984 AddDecl(If->getConditionVariable());
1986 void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1987 // We care about the syntactic form of the initializer list, only.
1988 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1990 EnqueueChildren(IE);
1992 void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1993 WL.push_back(MemberExprParts(M, Parent));
1995 // If the base of the member access expression is an implicit 'this', don't
1997 // FIXME: If we ever want to show these implicit accesses, this will be
1998 // unfortunate. However, clang_getCursor() relies on this behavior.
1999 if (!M->isImplicitAccess())
2000 AddStmt(M->getBase());
2002 void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2003 AddTypeLoc(E->getEncodedTypeSourceInfo());
2005 void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2007 AddTypeLoc(M->getClassReceiverTypeInfo());
2009 void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2010 // Visit the components of the offsetof expression.
2011 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2012 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2013 const OffsetOfNode &Node = E->getComponent(I-1);
2014 switch (Node.getKind()) {
2015 case OffsetOfNode::Array:
2016 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2018 case OffsetOfNode::Field:
2019 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2021 case OffsetOfNode::Identifier:
2022 case OffsetOfNode::Base:
2026 // Visit the type into which we're computing the offset.
2027 AddTypeLoc(E->getTypeSourceInfo());
2029 void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2030 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2031 WL.push_back(OverloadExprParts(E, Parent));
2033 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2034 UnaryExprOrTypeTraitExpr *E) {
2036 if (E->isArgumentType())
2037 AddTypeLoc(E->getArgumentTypeInfo());
2039 void EnqueueVisitor::VisitStmt(Stmt *S) {
2042 void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2043 AddStmt(S->getBody());
2044 AddStmt(S->getCond());
2045 AddDecl(S->getConditionVariable());
2048 void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2049 AddStmt(W->getBody());
2050 AddStmt(W->getCond());
2051 AddDecl(W->getConditionVariable());
2054 void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2055 AddTypeLoc(E->getQueriedTypeSourceInfo());
2058 void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2059 AddTypeLoc(E->getRhsTypeSourceInfo());
2060 AddTypeLoc(E->getLhsTypeSourceInfo());
2063 void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2064 for (unsigned I = E->getNumArgs(); I > 0; --I)
2065 AddTypeLoc(E->getArg(I-1));
2068 void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2069 AddTypeLoc(E->getQueriedTypeSourceInfo());
2072 void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2076 void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2077 VisitOverloadExpr(U);
2078 if (!U->isImplicitAccess())
2079 AddStmt(U->getBase());
2081 void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2082 AddStmt(E->getSubExpr());
2083 AddTypeLoc(E->getWrittenTypeInfo());
2085 void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2086 WL.push_back(SizeOfPackExprParts(E, Parent));
2088 void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2089 // If the opaque value has a source expression, just transparently
2090 // visit that. This is useful for (e.g.) pseudo-object expressions.
2091 if (Expr *SourceExpr = E->getSourceExpr())
2092 return Visit(SourceExpr);
2094 void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2095 AddStmt(E->getBody());
2096 WL.push_back(LambdaExprParts(E, Parent));
2098 void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2099 // Treat the expression like its syntactic form.
2100 Visit(E->getSyntacticForm());
2103 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2104 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2107 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2108 if (RegionOfInterest.isValid()) {
2109 SourceRange Range = getRawCursorExtent(C);
2110 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2116 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2117 while (!WL.empty()) {
2118 // Dequeue the worklist item.
2119 VisitorJob LI = WL.back();
2122 // Set the Parent field, then back to its old value once we're done.
2123 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2125 switch (LI.getKind()) {
2126 case VisitorJob::DeclVisitKind: {
2127 Decl *D = cast<DeclVisit>(&LI)->get();
2131 // For now, perform default visitation for Decls.
2132 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2133 cast<DeclVisit>(&LI)->isFirst())))
2138 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2139 const ASTTemplateArgumentListInfo *ArgList =
2140 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2141 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2142 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2143 Arg != ArgEnd; ++Arg) {
2144 if (VisitTemplateArgumentLoc(*Arg))
2149 case VisitorJob::TypeLocVisitKind: {
2150 // Perform default visitation for TypeLocs.
2151 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2155 case VisitorJob::LabelRefVisitKind: {
2156 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2157 if (LabelStmt *stmt = LS->getStmt()) {
2158 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2166 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2167 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2168 if (VisitNestedNameSpecifierLoc(V->get()))
2173 case VisitorJob::DeclarationNameInfoVisitKind: {
2174 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2179 case VisitorJob::MemberRefVisitKind: {
2180 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2181 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2185 case VisitorJob::StmtVisitKind: {
2186 Stmt *S = cast<StmtVisit>(&LI)->get();
2190 // Update the current cursor.
2191 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2192 if (!IsInRegionOfInterest(Cursor))
2194 switch (Visitor(Cursor, Parent, ClientData)) {
2195 case CXChildVisit_Break: return true;
2196 case CXChildVisit_Continue: break;
2197 case CXChildVisit_Recurse:
2198 EnqueueWorkList(WL, S);
2203 case VisitorJob::MemberExprPartsKind: {
2204 // Handle the other pieces in the MemberExpr besides the base.
2205 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2207 // Visit the nested-name-specifier
2208 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2209 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2212 // Visit the declaration name.
2213 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2216 // Visit the explicitly-specified template arguments, if any.
2217 if (M->hasExplicitTemplateArgs()) {
2218 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2219 *ArgEnd = Arg + M->getNumTemplateArgs();
2220 Arg != ArgEnd; ++Arg) {
2221 if (VisitTemplateArgumentLoc(*Arg))
2227 case VisitorJob::DeclRefExprPartsKind: {
2228 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2229 // Visit nested-name-specifier, if present.
2230 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2233 // Visit declaration name.
2234 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2238 case VisitorJob::OverloadExprPartsKind: {
2239 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2240 // Visit the nested-name-specifier.
2241 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2244 // Visit the declaration name.
2245 if (VisitDeclarationNameInfo(O->getNameInfo()))
2247 // Visit the overloaded declaration reference.
2248 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2252 case VisitorJob::SizeOfPackExprPartsKind: {
2253 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2254 NamedDecl *Pack = E->getPack();
2255 if (isa<TemplateTypeParmDecl>(Pack)) {
2256 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2257 E->getPackLoc(), TU)))
2263 if (isa<TemplateTemplateParmDecl>(Pack)) {
2264 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2265 E->getPackLoc(), TU)))
2271 // Non-type template parameter packs and function parameter packs are
2272 // treated like DeclRefExpr cursors.
2276 case VisitorJob::LambdaExprPartsKind: {
2278 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2279 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2280 CEnd = E->explicit_capture_end();
2282 if (C->capturesThis())
2285 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2291 // Visit parameters and return type, if present.
2292 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2293 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2294 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2295 // Visit the whole type.
2298 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2299 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2300 if (E->hasExplicitParameters()) {
2301 // Visit parameters.
2302 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2303 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2306 // Visit result type.
2307 if (Visit(Proto.getResultLoc()))
2319 bool CursorVisitor::Visit(Stmt *S) {
2320 VisitorWorkList *WL = 0;
2321 if (!WorkListFreeList.empty()) {
2322 WL = WorkListFreeList.back();
2324 WorkListFreeList.pop_back();
2327 WL = new VisitorWorkList();
2328 WorkListCache.push_back(WL);
2330 EnqueueWorkList(*WL, S);
2331 bool result = RunVisitorWorkList(*WL);
2332 WorkListFreeList.push_back(WL);
2337 typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2338 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2339 const DeclarationNameInfo &NI,
2340 const SourceRange &QLoc,
2341 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2342 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2343 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2344 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2346 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2348 RefNamePieces Pieces;
2350 if (WantQualifier && QLoc.isValid())
2351 Pieces.push_back(QLoc);
2353 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2354 Pieces.push_back(NI.getLoc());
2356 if (WantTemplateArgs && TemplateArgs)
2357 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2358 TemplateArgs->RAngleLoc));
2360 if (Kind == DeclarationName::CXXOperatorName) {
2361 Pieces.push_back(SourceLocation::getFromRawEncoding(
2362 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2363 Pieces.push_back(SourceLocation::getFromRawEncoding(
2364 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2367 if (WantSinglePiece) {
2368 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2370 Pieces.push_back(R);
2377 //===----------------------------------------------------------------------===//
2379 //===----------------------------------------------------------------------===//
2381 static llvm::sys::Mutex EnableMultithreadingMutex;
2382 static bool EnabledMultithreading;
2384 static void fatal_error_handler(void *user_data, const std::string& reason) {
2385 // Write the result out to stderr avoiding errs() because raw_ostreams can
2386 // call report_fatal_error.
2387 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2392 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2393 int displayDiagnostics) {
2394 // Disable pretty stack trace functionality, which will otherwise be a very
2395 // poor citizen of the world and set up all sorts of signal handlers.
2396 llvm::DisablePrettyStackTrace = true;
2398 // We use crash recovery to make some of our APIs more reliable, implicitly
2400 llvm::CrashRecoveryContext::Enable();
2402 // Enable support for multithreading in LLVM.
2404 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2405 if (!EnabledMultithreading) {
2406 llvm::install_fatal_error_handler(fatal_error_handler, 0);
2407 llvm::llvm_start_multithreaded();
2408 EnabledMultithreading = true;
2412 CIndexer *CIdxr = new CIndexer();
2413 if (excludeDeclarationsFromPCH)
2414 CIdxr->setOnlyLocalDecls();
2415 if (displayDiagnostics)
2416 CIdxr->setDisplayDiagnostics();
2418 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2419 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2420 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2421 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2422 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2423 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2428 void clang_disposeIndex(CXIndex CIdx) {
2430 delete static_cast<CIndexer *>(CIdx);
2433 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2435 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2438 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2440 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2444 void clang_toggleCrashRecovery(unsigned isEnabled) {
2446 llvm::CrashRecoveryContext::Enable();
2448 llvm::CrashRecoveryContext::Disable();
2451 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2452 const char *ast_filename) {
2456 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2457 FileSystemOptions FileSystemOpts;
2458 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2460 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2461 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2462 CXXIdx->getOnlyLocalDecls(),
2464 /*CaptureDiagnostics=*/true,
2465 /*AllowPCHWithCompilerErrors=*/true);
2466 return MakeCXTranslationUnit(CXXIdx, TU);
2469 unsigned clang_defaultEditingTranslationUnitOptions() {
2470 return CXTranslationUnit_PrecompiledPreamble |
2471 CXTranslationUnit_CacheCompletionResults;
2475 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2476 const char *source_filename,
2477 int num_command_line_args,
2478 const char * const *command_line_args,
2479 unsigned num_unsaved_files,
2480 struct CXUnsavedFile *unsaved_files) {
2481 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2482 return clang_parseTranslationUnit(CIdx, source_filename,
2483 command_line_args, num_command_line_args,
2484 unsaved_files, num_unsaved_files,
2488 struct ParseTranslationUnitInfo {
2490 const char *source_filename;
2491 const char *const *command_line_args;
2492 int num_command_line_args;
2493 struct CXUnsavedFile *unsaved_files;
2494 unsigned num_unsaved_files;
2496 CXTranslationUnit result;
2498 static void clang_parseTranslationUnit_Impl(void *UserData) {
2499 ParseTranslationUnitInfo *PTUI =
2500 static_cast<ParseTranslationUnitInfo*>(UserData);
2501 CXIndex CIdx = PTUI->CIdx;
2502 const char *source_filename = PTUI->source_filename;
2503 const char * const *command_line_args = PTUI->command_line_args;
2504 int num_command_line_args = PTUI->num_command_line_args;
2505 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2506 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2507 unsigned options = PTUI->options;
2513 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2515 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2516 setThreadBackgroundPriority();
2518 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2519 // FIXME: Add a flag for modules.
2520 TranslationUnitKind TUKind
2521 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2522 bool CacheCodeCompetionResults
2523 = options & CXTranslationUnit_CacheCompletionResults;
2525 // Configure the diagnostics.
2526 DiagnosticOptions DiagOpts;
2527 IntrusiveRefCntPtr<DiagnosticsEngine>
2528 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2529 command_line_args));
2531 // Recover resources if we crash before exiting this function.
2532 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2533 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2534 DiagCleanup(Diags.getPtr());
2536 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2537 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2539 // Recover resources if we crash before exiting this function.
2540 llvm::CrashRecoveryContextCleanupRegistrar<
2541 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2543 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2544 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2545 const llvm::MemoryBuffer *Buffer
2546 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2547 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2551 OwningPtr<std::vector<const char *> >
2552 Args(new std::vector<const char*>());
2554 // Recover resources if we crash before exiting this method.
2555 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2556 ArgsCleanup(Args.get());
2558 // Since the Clang C library is primarily used by batch tools dealing with
2559 // (often very broken) source code, where spell-checking can have a
2560 // significant negative impact on performance (particularly when
2561 // precompiled headers are involved), we disable it by default.
2562 // Only do this if we haven't found a spell-checking-related argument.
2563 bool FoundSpellCheckingArgument = false;
2564 for (int I = 0; I != num_command_line_args; ++I) {
2565 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2566 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2567 FoundSpellCheckingArgument = true;
2571 if (!FoundSpellCheckingArgument)
2572 Args->push_back("-fno-spell-checking");
2574 Args->insert(Args->end(), command_line_args,
2575 command_line_args + num_command_line_args);
2577 // The 'source_filename' argument is optional. If the caller does not
2578 // specify it then it is assumed that the source file is specified
2579 // in the actual argument list.
2580 // Put the source file after command_line_args otherwise if '-x' flag is
2581 // present it will be unused.
2582 if (source_filename)
2583 Args->push_back(source_filename);
2585 // Do we need the detailed preprocessing record?
2586 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2587 Args->push_back("-Xclang");
2588 Args->push_back("-detailed-preprocessing-record");
2591 unsigned NumErrors = Diags->getClient()->getNumErrors();
2592 OwningPtr<ASTUnit> ErrUnit;
2593 OwningPtr<ASTUnit> Unit(
2594 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2595 /* vector::data() not portable */,
2596 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2598 CXXIdx->getClangResourcesPath(),
2599 CXXIdx->getOnlyLocalDecls(),
2600 /*CaptureDiagnostics=*/true,
2601 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2602 RemappedFiles->size(),
2603 /*RemappedFilesKeepOriginalName=*/true,
2606 CacheCodeCompetionResults,
2607 /*AllowPCHWithCompilerErrors=*/true,
2610 if (NumErrors != Diags->getClient()->getNumErrors()) {
2611 // Make sure to check that 'Unit' is non-NULL.
2612 if (CXXIdx->getDisplayDiagnostics())
2613 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2616 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2618 CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2619 const char *source_filename,
2620 const char * const *command_line_args,
2621 int num_command_line_args,
2622 struct CXUnsavedFile *unsaved_files,
2623 unsigned num_unsaved_files,
2625 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2626 num_command_line_args, unsaved_files,
2627 num_unsaved_files, options, 0 };
2628 llvm::CrashRecoveryContext CRC;
2630 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2631 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2632 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2633 fprintf(stderr, " 'command_line_args' : [");
2634 for (int i = 0; i != num_command_line_args; ++i) {
2636 fprintf(stderr, ", ");
2637 fprintf(stderr, "'%s'", command_line_args[i]);
2639 fprintf(stderr, "],\n");
2640 fprintf(stderr, " 'unsaved_files' : [");
2641 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2643 fprintf(stderr, ", ");
2644 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2645 unsaved_files[i].Length);
2647 fprintf(stderr, "],\n");
2648 fprintf(stderr, " 'options' : %d,\n", options);
2649 fprintf(stderr, "}\n");
2652 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2653 PrintLibclangResourceUsage(PTUI.result);
2659 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2660 return CXSaveTranslationUnit_None;
2665 struct SaveTranslationUnitInfo {
2666 CXTranslationUnit TU;
2667 const char *FileName;
2674 static void clang_saveTranslationUnit_Impl(void *UserData) {
2675 SaveTranslationUnitInfo *STUI =
2676 static_cast<SaveTranslationUnitInfo*>(UserData);
2678 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2679 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2680 setThreadBackgroundPriority();
2682 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2685 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2688 return CXSaveError_InvalidTU;
2690 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2691 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2693 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2695 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2696 getenv("LIBCLANG_NOTHREADS")) {
2697 clang_saveTranslationUnit_Impl(&STUI);
2699 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2700 PrintLibclangResourceUsage(TU);
2705 // We have an AST that has invalid nodes due to compiler errors.
2706 // Use a crash recovery thread for protection.
2708 llvm::CrashRecoveryContext CRC;
2710 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2711 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2712 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2713 fprintf(stderr, " 'options' : %d,\n", options);
2714 fprintf(stderr, "}\n");
2716 return CXSaveError_Unknown;
2718 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2719 PrintLibclangResourceUsage(TU);
2725 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2727 // If the translation unit has been marked as unsafe to free, just discard
2729 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2732 delete static_cast<ASTUnit *>(CTUnit->TUData);
2733 disposeCXStringPool(CTUnit->StringPool);
2734 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2739 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2740 return CXReparse_None;
2743 struct ReparseTranslationUnitInfo {
2744 CXTranslationUnit TU;
2745 unsigned num_unsaved_files;
2746 struct CXUnsavedFile *unsaved_files;
2751 static void clang_reparseTranslationUnit_Impl(void *UserData) {
2752 ReparseTranslationUnitInfo *RTUI =
2753 static_cast<ReparseTranslationUnitInfo*>(UserData);
2754 CXTranslationUnit TU = RTUI->TU;
2756 // Reset the associated diagnostics.
2757 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2758 TU->Diagnostics = 0;
2760 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2761 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2762 unsigned options = RTUI->options;
2769 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2770 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2771 setThreadBackgroundPriority();
2773 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2774 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2776 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2777 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2779 // Recover resources if we crash before exiting this function.
2780 llvm::CrashRecoveryContextCleanupRegistrar<
2781 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2783 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2784 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2785 const llvm::MemoryBuffer *Buffer
2786 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2787 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2791 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2792 RemappedFiles->size()))
2796 int clang_reparseTranslationUnit(CXTranslationUnit TU,
2797 unsigned num_unsaved_files,
2798 struct CXUnsavedFile *unsaved_files,
2800 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2803 if (getenv("LIBCLANG_NOTHREADS")) {
2804 clang_reparseTranslationUnit_Impl(&RTUI);
2808 llvm::CrashRecoveryContext CRC;
2810 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2811 fprintf(stderr, "libclang: crash detected during reparsing\n");
2812 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2814 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2815 PrintLibclangResourceUsage(TU);
2821 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2823 return createCXString("");
2825 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2826 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2829 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2830 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
2834 } // end: extern "C"
2836 //===----------------------------------------------------------------------===//
2837 // CXFile Operations.
2838 //===----------------------------------------------------------------------===//
2841 CXString clang_getFileName(CXFile SFile) {
2843 return createCXString((const char*)NULL);
2845 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2846 return createCXString(FEnt->getName());
2849 time_t clang_getFileTime(CXFile SFile) {
2853 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2854 return FEnt->getModificationTime();
2857 CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2861 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2863 FileManager &FMgr = CXXUnit->getFileManager();
2864 return const_cast<FileEntry *>(FMgr.getFile(file_name));
2867 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2871 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2872 FileEntry *FEnt = static_cast<FileEntry *>(file);
2873 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2874 .isFileMultipleIncludeGuarded(FEnt);
2877 } // end: extern "C"
2879 //===----------------------------------------------------------------------===//
2880 // CXCursor Operations.
2881 //===----------------------------------------------------------------------===//
2883 static Decl *getDeclFromExpr(Stmt *E) {
2884 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2885 return getDeclFromExpr(CE->getSubExpr());
2887 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2888 return RefExpr->getDecl();
2889 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2890 return ME->getMemberDecl();
2891 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2892 return RE->getDecl();
2893 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2894 if (PRE->isExplicitProperty())
2895 return PRE->getExplicitProperty();
2896 // It could be messaging both getter and setter as in:
2898 // in which case prefer to associate the setter since it is less obvious
2899 // from inspecting the source that the setter is going to get called.
2900 if (PRE->isMessagingSetter())
2901 return PRE->getImplicitPropertySetter();
2902 return PRE->getImplicitPropertyGetter();
2904 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2905 return getDeclFromExpr(POE->getSyntacticForm());
2906 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2907 if (Expr *Src = OVE->getSourceExpr())
2908 return getDeclFromExpr(Src);
2910 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2911 return getDeclFromExpr(CE->getCallee());
2912 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2913 if (!CE->isElidable())
2914 return CE->getConstructor();
2915 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2916 return OME->getMethodDecl();
2918 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2919 return PE->getProtocol();
2920 if (SubstNonTypeTemplateParmPackExpr *NTTP
2921 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2922 return NTTP->getParameterPack();
2923 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2924 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2925 isa<ParmVarDecl>(SizeOfPack->getPack()))
2926 return SizeOfPack->getPack();
2931 static SourceLocation getLocationFromExpr(Expr *E) {
2932 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2933 return getLocationFromExpr(CE->getSubExpr());
2935 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2936 return /*FIXME:*/Msg->getLeftLoc();
2937 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2938 return DRE->getLocation();
2939 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2940 return Member->getMemberLoc();
2941 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2942 return Ivar->getLocation();
2943 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2944 return SizeOfPack->getPackLoc();
2945 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2946 return PropRef->getLocation();
2948 return E->getLocStart();
2953 unsigned clang_visitChildren(CXCursor parent,
2954 CXCursorVisitor visitor,
2955 CXClientData client_data) {
2956 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2957 /*VisitPreprocessorLast=*/false);
2958 return CursorVis.VisitChildren(parent);
2961 #ifndef __has_feature
2962 #define __has_feature(x) 0
2964 #if __has_feature(blocks)
2965 typedef enum CXChildVisitResult
2966 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2968 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2969 CXClientData client_data) {
2970 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2971 return block(cursor, parent);
2974 // If we are compiled with a compiler that doesn't have native blocks support,
2975 // define and call the block manually, so the
2976 typedef struct _CXChildVisitResult
2981 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2983 } *CXCursorVisitorBlock;
2985 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2986 CXClientData client_data) {
2987 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2988 return block->invoke(block, cursor, parent);
2993 unsigned clang_visitChildrenWithBlock(CXCursor parent,
2994 CXCursorVisitorBlock block) {
2995 return clang_visitChildren(parent, visitWithBlock, block);
2998 static CXString getDeclSpelling(Decl *D) {
3000 return createCXString("");
3002 NamedDecl *ND = dyn_cast<NamedDecl>(D);
3004 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3005 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3006 return createCXString(Property->getIdentifier()->getName());
3008 return createCXString("");
3011 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3012 return createCXString(OMD->getSelector().getAsString());
3014 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3015 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3016 // and returns different names. NamedDecl returns the class name and
3017 // ObjCCategoryImplDecl returns the category name.
3018 return createCXString(CIMP->getIdentifier()->getNameStart());
3020 if (isa<UsingDirectiveDecl>(D))
3021 return createCXString("");
3023 SmallString<1024> S;
3024 llvm::raw_svector_ostream os(S);
3027 return createCXString(os.str());
3030 CXString clang_getCursorSpelling(CXCursor C) {
3031 if (clang_isTranslationUnit(C.kind))
3032 return clang_getTranslationUnitSpelling(
3033 static_cast<CXTranslationUnit>(C.data[2]));
3035 if (clang_isReference(C.kind)) {
3037 case CXCursor_ObjCSuperClassRef: {
3038 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3039 return createCXString(Super->getIdentifier()->getNameStart());
3041 case CXCursor_ObjCClassRef: {
3042 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3043 return createCXString(Class->getIdentifier()->getNameStart());
3045 case CXCursor_ObjCProtocolRef: {
3046 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3047 assert(OID && "getCursorSpelling(): Missing protocol decl");
3048 return createCXString(OID->getIdentifier()->getNameStart());
3050 case CXCursor_CXXBaseSpecifier: {
3051 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3052 return createCXString(B->getType().getAsString());
3054 case CXCursor_TypeRef: {
3055 TypeDecl *Type = getCursorTypeRef(C).first;
3056 assert(Type && "Missing type decl");
3058 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3061 case CXCursor_TemplateRef: {
3062 TemplateDecl *Template = getCursorTemplateRef(C).first;
3063 assert(Template && "Missing template decl");
3065 return createCXString(Template->getNameAsString());
3068 case CXCursor_NamespaceRef: {
3069 NamedDecl *NS = getCursorNamespaceRef(C).first;
3070 assert(NS && "Missing namespace decl");
3072 return createCXString(NS->getNameAsString());
3075 case CXCursor_MemberRef: {
3076 FieldDecl *Field = getCursorMemberRef(C).first;
3077 assert(Field && "Missing member decl");
3079 return createCXString(Field->getNameAsString());
3082 case CXCursor_LabelRef: {
3083 LabelStmt *Label = getCursorLabelRef(C).first;
3084 assert(Label && "Missing label");
3086 return createCXString(Label->getName());
3089 case CXCursor_OverloadedDeclRef: {
3090 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3091 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3092 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3093 return createCXString(ND->getNameAsString());
3094 return createCXString("");
3096 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3097 return createCXString(E->getName().getAsString());
3098 OverloadedTemplateStorage *Ovl
3099 = Storage.get<OverloadedTemplateStorage*>();
3100 if (Ovl->size() == 0)
3101 return createCXString("");
3102 return createCXString((*Ovl->begin())->getNameAsString());
3105 case CXCursor_VariableRef: {
3106 VarDecl *Var = getCursorVariableRef(C).first;
3107 assert(Var && "Missing variable decl");
3109 return createCXString(Var->getNameAsString());
3113 return createCXString("<not implemented>");
3117 if (clang_isExpression(C.kind)) {
3118 Decl *D = getDeclFromExpr(getCursorExpr(C));
3120 return getDeclSpelling(D);
3121 return createCXString("");
3124 if (clang_isStatement(C.kind)) {
3125 Stmt *S = getCursorStmt(C);
3126 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3127 return createCXString(Label->getName());
3129 return createCXString("");
3132 if (C.kind == CXCursor_MacroExpansion)
3133 return createCXString(getCursorMacroExpansion(C)->getName()
3136 if (C.kind == CXCursor_MacroDefinition)
3137 return createCXString(getCursorMacroDefinition(C)->getName()
3140 if (C.kind == CXCursor_InclusionDirective)
3141 return createCXString(getCursorInclusionDirective(C)->getFileName());
3143 if (clang_isDeclaration(C.kind))
3144 return getDeclSpelling(getCursorDecl(C));
3146 if (C.kind == CXCursor_AnnotateAttr) {
3147 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3148 return createCXString(AA->getAnnotation());
3151 if (C.kind == CXCursor_AsmLabelAttr) {
3152 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3153 return createCXString(AA->getLabel());
3156 return createCXString("");
3159 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3160 unsigned pieceIndex,
3162 if (clang_Cursor_isNull(C))
3163 return clang_getNullRange();
3165 ASTContext &Ctx = getCursorContext(C);
3167 if (clang_isStatement(C.kind)) {
3168 Stmt *S = getCursorStmt(C);
3169 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3171 return clang_getNullRange();
3172 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3175 return clang_getNullRange();
3178 if (C.kind == CXCursor_ObjCMessageExpr) {
3179 if (ObjCMessageExpr *
3180 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3181 if (pieceIndex >= ME->getNumSelectorLocs())
3182 return clang_getNullRange();
3183 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3187 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3188 C.kind == CXCursor_ObjCClassMethodDecl) {
3189 if (ObjCMethodDecl *
3190 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3191 if (pieceIndex >= MD->getNumSelectorLocs())
3192 return clang_getNullRange();
3193 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3197 // FIXME: A CXCursor_InclusionDirective should give the location of the
3198 // filename, but we don't keep track of this.
3200 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3201 // but we don't keep track of this.
3203 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3204 // but we don't keep track of this.
3206 // Default handling, give the location of the cursor.
3209 return clang_getNullRange();
3211 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3212 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3213 return cxloc::translateSourceRange(Ctx, Loc);
3216 CXString clang_getCursorDisplayName(CXCursor C) {
3217 if (!clang_isDeclaration(C.kind))
3218 return clang_getCursorSpelling(C);
3220 Decl *D = getCursorDecl(C);
3222 return createCXString("");
3224 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3225 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3226 D = FunTmpl->getTemplatedDecl();
3228 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3229 SmallString<64> Str;
3230 llvm::raw_svector_ostream OS(Str);
3232 if (Function->getPrimaryTemplate())
3235 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3238 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3241 if (Function->isVariadic()) {
3242 if (Function->getNumParams())
3247 return createCXString(OS.str());
3250 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3251 SmallString<64> Str;
3252 llvm::raw_svector_ostream OS(Str);
3253 OS << *ClassTemplate;
3255 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3256 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3260 NamedDecl *Param = Params->getParam(I);
3261 if (Param->getIdentifier()) {
3262 OS << Param->getIdentifier()->getName();
3266 // There is no parameter name, which makes this tricky. Try to come up
3267 // with something useful that isn't too long.
3268 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3269 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3270 else if (NonTypeTemplateParmDecl *NTTP
3271 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3272 OS << NTTP->getType().getAsString(Policy);
3274 OS << "template<...> class";
3278 return createCXString(OS.str());
3281 if (ClassTemplateSpecializationDecl *ClassSpec
3282 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3283 // If the type was explicitly written, use that.
3284 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3285 return createCXString(TSInfo->getType().getAsString(Policy));
3287 SmallString<64> Str;
3288 llvm::raw_svector_ostream OS(Str);
3290 OS << TemplateSpecializationType::PrintTemplateArgumentList(
3291 ClassSpec->getTemplateArgs().data(),
3292 ClassSpec->getTemplateArgs().size(),
3294 return createCXString(OS.str());
3297 return clang_getCursorSpelling(C);
3300 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3302 case CXCursor_FunctionDecl:
3303 return createCXString("FunctionDecl");
3304 case CXCursor_TypedefDecl:
3305 return createCXString("TypedefDecl");
3306 case CXCursor_EnumDecl:
3307 return createCXString("EnumDecl");
3308 case CXCursor_EnumConstantDecl:
3309 return createCXString("EnumConstantDecl");
3310 case CXCursor_StructDecl:
3311 return createCXString("StructDecl");
3312 case CXCursor_UnionDecl:
3313 return createCXString("UnionDecl");
3314 case CXCursor_ClassDecl:
3315 return createCXString("ClassDecl");
3316 case CXCursor_FieldDecl:
3317 return createCXString("FieldDecl");
3318 case CXCursor_VarDecl:
3319 return createCXString("VarDecl");
3320 case CXCursor_ParmDecl:
3321 return createCXString("ParmDecl");
3322 case CXCursor_ObjCInterfaceDecl:
3323 return createCXString("ObjCInterfaceDecl");
3324 case CXCursor_ObjCCategoryDecl:
3325 return createCXString("ObjCCategoryDecl");
3326 case CXCursor_ObjCProtocolDecl:
3327 return createCXString("ObjCProtocolDecl");
3328 case CXCursor_ObjCPropertyDecl:
3329 return createCXString("ObjCPropertyDecl");
3330 case CXCursor_ObjCIvarDecl:
3331 return createCXString("ObjCIvarDecl");
3332 case CXCursor_ObjCInstanceMethodDecl:
3333 return createCXString("ObjCInstanceMethodDecl");
3334 case CXCursor_ObjCClassMethodDecl:
3335 return createCXString("ObjCClassMethodDecl");
3336 case CXCursor_ObjCImplementationDecl:
3337 return createCXString("ObjCImplementationDecl");
3338 case CXCursor_ObjCCategoryImplDecl:
3339 return createCXString("ObjCCategoryImplDecl");
3340 case CXCursor_CXXMethod:
3341 return createCXString("CXXMethod");
3342 case CXCursor_UnexposedDecl:
3343 return createCXString("UnexposedDecl");
3344 case CXCursor_ObjCSuperClassRef:
3345 return createCXString("ObjCSuperClassRef");
3346 case CXCursor_ObjCProtocolRef:
3347 return createCXString("ObjCProtocolRef");
3348 case CXCursor_ObjCClassRef:
3349 return createCXString("ObjCClassRef");
3350 case CXCursor_TypeRef:
3351 return createCXString("TypeRef");
3352 case CXCursor_TemplateRef:
3353 return createCXString("TemplateRef");
3354 case CXCursor_NamespaceRef:
3355 return createCXString("NamespaceRef");
3356 case CXCursor_MemberRef:
3357 return createCXString("MemberRef");
3358 case CXCursor_LabelRef:
3359 return createCXString("LabelRef");
3360 case CXCursor_OverloadedDeclRef:
3361 return createCXString("OverloadedDeclRef");
3362 case CXCursor_VariableRef:
3363 return createCXString("VariableRef");
3364 case CXCursor_IntegerLiteral:
3365 return createCXString("IntegerLiteral");
3366 case CXCursor_FloatingLiteral:
3367 return createCXString("FloatingLiteral");
3368 case CXCursor_ImaginaryLiteral:
3369 return createCXString("ImaginaryLiteral");
3370 case CXCursor_StringLiteral:
3371 return createCXString("StringLiteral");
3372 case CXCursor_CharacterLiteral:
3373 return createCXString("CharacterLiteral");
3374 case CXCursor_ParenExpr:
3375 return createCXString("ParenExpr");
3376 case CXCursor_UnaryOperator:
3377 return createCXString("UnaryOperator");
3378 case CXCursor_ArraySubscriptExpr:
3379 return createCXString("ArraySubscriptExpr");
3380 case CXCursor_BinaryOperator:
3381 return createCXString("BinaryOperator");
3382 case CXCursor_CompoundAssignOperator:
3383 return createCXString("CompoundAssignOperator");
3384 case CXCursor_ConditionalOperator:
3385 return createCXString("ConditionalOperator");
3386 case CXCursor_CStyleCastExpr:
3387 return createCXString("CStyleCastExpr");
3388 case CXCursor_CompoundLiteralExpr:
3389 return createCXString("CompoundLiteralExpr");
3390 case CXCursor_InitListExpr:
3391 return createCXString("InitListExpr");
3392 case CXCursor_AddrLabelExpr:
3393 return createCXString("AddrLabelExpr");
3394 case CXCursor_StmtExpr:
3395 return createCXString("StmtExpr");
3396 case CXCursor_GenericSelectionExpr:
3397 return createCXString("GenericSelectionExpr");
3398 case CXCursor_GNUNullExpr:
3399 return createCXString("GNUNullExpr");
3400 case CXCursor_CXXStaticCastExpr:
3401 return createCXString("CXXStaticCastExpr");
3402 case CXCursor_CXXDynamicCastExpr:
3403 return createCXString("CXXDynamicCastExpr");
3404 case CXCursor_CXXReinterpretCastExpr:
3405 return createCXString("CXXReinterpretCastExpr");
3406 case CXCursor_CXXConstCastExpr:
3407 return createCXString("CXXConstCastExpr");
3408 case CXCursor_CXXFunctionalCastExpr:
3409 return createCXString("CXXFunctionalCastExpr");
3410 case CXCursor_CXXTypeidExpr:
3411 return createCXString("CXXTypeidExpr");
3412 case CXCursor_CXXBoolLiteralExpr:
3413 return createCXString("CXXBoolLiteralExpr");
3414 case CXCursor_CXXNullPtrLiteralExpr:
3415 return createCXString("CXXNullPtrLiteralExpr");
3416 case CXCursor_CXXThisExpr:
3417 return createCXString("CXXThisExpr");
3418 case CXCursor_CXXThrowExpr:
3419 return createCXString("CXXThrowExpr");
3420 case CXCursor_CXXNewExpr:
3421 return createCXString("CXXNewExpr");
3422 case CXCursor_CXXDeleteExpr:
3423 return createCXString("CXXDeleteExpr");
3424 case CXCursor_UnaryExpr:
3425 return createCXString("UnaryExpr");
3426 case CXCursor_ObjCStringLiteral:
3427 return createCXString("ObjCStringLiteral");
3428 case CXCursor_ObjCBoolLiteralExpr:
3429 return createCXString("ObjCBoolLiteralExpr");
3430 case CXCursor_ObjCEncodeExpr:
3431 return createCXString("ObjCEncodeExpr");
3432 case CXCursor_ObjCSelectorExpr:
3433 return createCXString("ObjCSelectorExpr");
3434 case CXCursor_ObjCProtocolExpr:
3435 return createCXString("ObjCProtocolExpr");
3436 case CXCursor_ObjCBridgedCastExpr:
3437 return createCXString("ObjCBridgedCastExpr");
3438 case CXCursor_BlockExpr:
3439 return createCXString("BlockExpr");
3440 case CXCursor_PackExpansionExpr:
3441 return createCXString("PackExpansionExpr");
3442 case CXCursor_SizeOfPackExpr:
3443 return createCXString("SizeOfPackExpr");
3444 case CXCursor_LambdaExpr:
3445 return createCXString("LambdaExpr");
3446 case CXCursor_UnexposedExpr:
3447 return createCXString("UnexposedExpr");
3448 case CXCursor_DeclRefExpr:
3449 return createCXString("DeclRefExpr");
3450 case CXCursor_MemberRefExpr:
3451 return createCXString("MemberRefExpr");
3452 case CXCursor_CallExpr:
3453 return createCXString("CallExpr");
3454 case CXCursor_ObjCMessageExpr:
3455 return createCXString("ObjCMessageExpr");
3456 case CXCursor_UnexposedStmt:
3457 return createCXString("UnexposedStmt");
3458 case CXCursor_DeclStmt:
3459 return createCXString("DeclStmt");
3460 case CXCursor_LabelStmt:
3461 return createCXString("LabelStmt");
3462 case CXCursor_CompoundStmt:
3463 return createCXString("CompoundStmt");
3464 case CXCursor_CaseStmt:
3465 return createCXString("CaseStmt");
3466 case CXCursor_DefaultStmt:
3467 return createCXString("DefaultStmt");
3468 case CXCursor_IfStmt:
3469 return createCXString("IfStmt");
3470 case CXCursor_SwitchStmt:
3471 return createCXString("SwitchStmt");
3472 case CXCursor_WhileStmt:
3473 return createCXString("WhileStmt");
3474 case CXCursor_DoStmt:
3475 return createCXString("DoStmt");
3476 case CXCursor_ForStmt:
3477 return createCXString("ForStmt");
3478 case CXCursor_GotoStmt:
3479 return createCXString("GotoStmt");
3480 case CXCursor_IndirectGotoStmt:
3481 return createCXString("IndirectGotoStmt");
3482 case CXCursor_ContinueStmt:
3483 return createCXString("ContinueStmt");
3484 case CXCursor_BreakStmt:
3485 return createCXString("BreakStmt");
3486 case CXCursor_ReturnStmt:
3487 return createCXString("ReturnStmt");
3488 case CXCursor_AsmStmt:
3489 return createCXString("AsmStmt");
3490 case CXCursor_ObjCAtTryStmt:
3491 return createCXString("ObjCAtTryStmt");
3492 case CXCursor_ObjCAtCatchStmt:
3493 return createCXString("ObjCAtCatchStmt");
3494 case CXCursor_ObjCAtFinallyStmt:
3495 return createCXString("ObjCAtFinallyStmt");
3496 case CXCursor_ObjCAtThrowStmt:
3497 return createCXString("ObjCAtThrowStmt");
3498 case CXCursor_ObjCAtSynchronizedStmt:
3499 return createCXString("ObjCAtSynchronizedStmt");
3500 case CXCursor_ObjCAutoreleasePoolStmt:
3501 return createCXString("ObjCAutoreleasePoolStmt");
3502 case CXCursor_ObjCForCollectionStmt:
3503 return createCXString("ObjCForCollectionStmt");
3504 case CXCursor_CXXCatchStmt:
3505 return createCXString("CXXCatchStmt");
3506 case CXCursor_CXXTryStmt:
3507 return createCXString("CXXTryStmt");
3508 case CXCursor_CXXForRangeStmt:
3509 return createCXString("CXXForRangeStmt");
3510 case CXCursor_SEHTryStmt:
3511 return createCXString("SEHTryStmt");
3512 case CXCursor_SEHExceptStmt:
3513 return createCXString("SEHExceptStmt");
3514 case CXCursor_SEHFinallyStmt:
3515 return createCXString("SEHFinallyStmt");
3516 case CXCursor_NullStmt:
3517 return createCXString("NullStmt");
3518 case CXCursor_InvalidFile:
3519 return createCXString("InvalidFile");
3520 case CXCursor_InvalidCode:
3521 return createCXString("InvalidCode");
3522 case CXCursor_NoDeclFound:
3523 return createCXString("NoDeclFound");
3524 case CXCursor_NotImplemented:
3525 return createCXString("NotImplemented");
3526 case CXCursor_TranslationUnit:
3527 return createCXString("TranslationUnit");
3528 case CXCursor_UnexposedAttr:
3529 return createCXString("UnexposedAttr");
3530 case CXCursor_IBActionAttr:
3531 return createCXString("attribute(ibaction)");
3532 case CXCursor_IBOutletAttr:
3533 return createCXString("attribute(iboutlet)");
3534 case CXCursor_IBOutletCollectionAttr:
3535 return createCXString("attribute(iboutletcollection)");
3536 case CXCursor_CXXFinalAttr:
3537 return createCXString("attribute(final)");
3538 case CXCursor_CXXOverrideAttr:
3539 return createCXString("attribute(override)");
3540 case CXCursor_AnnotateAttr:
3541 return createCXString("attribute(annotate)");
3542 case CXCursor_AsmLabelAttr:
3543 return createCXString("asm label");
3544 case CXCursor_PreprocessingDirective:
3545 return createCXString("preprocessing directive");
3546 case CXCursor_MacroDefinition:
3547 return createCXString("macro definition");
3548 case CXCursor_MacroExpansion:
3549 return createCXString("macro expansion");
3550 case CXCursor_InclusionDirective:
3551 return createCXString("inclusion directive");
3552 case CXCursor_Namespace:
3553 return createCXString("Namespace");
3554 case CXCursor_LinkageSpec:
3555 return createCXString("LinkageSpec");
3556 case CXCursor_CXXBaseSpecifier:
3557 return createCXString("C++ base class specifier");
3558 case CXCursor_Constructor:
3559 return createCXString("CXXConstructor");
3560 case CXCursor_Destructor:
3561 return createCXString("CXXDestructor");
3562 case CXCursor_ConversionFunction:
3563 return createCXString("CXXConversion");
3564 case CXCursor_TemplateTypeParameter:
3565 return createCXString("TemplateTypeParameter");
3566 case CXCursor_NonTypeTemplateParameter:
3567 return createCXString("NonTypeTemplateParameter");
3568 case CXCursor_TemplateTemplateParameter:
3569 return createCXString("TemplateTemplateParameter");
3570 case CXCursor_FunctionTemplate:
3571 return createCXString("FunctionTemplate");
3572 case CXCursor_ClassTemplate:
3573 return createCXString("ClassTemplate");
3574 case CXCursor_ClassTemplatePartialSpecialization:
3575 return createCXString("ClassTemplatePartialSpecialization");
3576 case CXCursor_NamespaceAlias:
3577 return createCXString("NamespaceAlias");
3578 case CXCursor_UsingDirective:
3579 return createCXString("UsingDirective");
3580 case CXCursor_UsingDeclaration:
3581 return createCXString("UsingDeclaration");
3582 case CXCursor_TypeAliasDecl:
3583 return createCXString("TypeAliasDecl");
3584 case CXCursor_ObjCSynthesizeDecl:
3585 return createCXString("ObjCSynthesizeDecl");
3586 case CXCursor_ObjCDynamicDecl:
3587 return createCXString("ObjCDynamicDecl");
3588 case CXCursor_CXXAccessSpecifier:
3589 return createCXString("CXXAccessSpecifier");
3592 llvm_unreachable("Unhandled CXCursorKind");
3595 struct GetCursorData {
3596 SourceLocation TokenBeginLoc;
3597 bool PointsAtMacroArgExpansion;
3598 CXCursor &BestCursor;
3600 GetCursorData(SourceManager &SM,
3601 SourceLocation tokenBegin, CXCursor &outputCursor)
3602 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3603 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3607 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3609 CXClientData client_data) {
3610 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3611 CXCursor *BestCursor = &Data->BestCursor;
3613 // If we point inside a macro argument we should provide info of what the
3614 // token is so use the actual cursor, don't replace it with a macro expansion
3616 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3617 return CXChildVisit_Recurse;
3619 if (clang_isDeclaration(cursor.kind)) {
3620 // Avoid having the implicit methods override the property decls.
3621 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
3622 if (MD->isImplicit())
3623 return CXChildVisit_Break;
3626 if (clang_isExpression(cursor.kind) &&
3627 clang_isDeclaration(BestCursor->kind)) {
3628 if (Decl *D = getCursorDecl(*BestCursor)) {
3629 // Avoid having the cursor of an expression replace the declaration cursor
3630 // when the expression source range overlaps the declaration range.
3631 // This can happen for C++ constructor expressions whose range generally
3632 // include the variable declaration, e.g.:
3633 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3634 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3635 D->getLocation() == Data->TokenBeginLoc)
3636 return CXChildVisit_Break;
3640 // If our current best cursor is the construction of a temporary object,
3641 // don't replace that cursor with a type reference, because we want
3642 // clang_getCursor() to point at the constructor.
3643 if (clang_isExpression(BestCursor->kind) &&
3644 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3645 cursor.kind == CXCursor_TypeRef) {
3646 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3647 // as having the actual point on the type reference.
3648 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3649 return CXChildVisit_Recurse;
3652 *BestCursor = cursor;
3653 return CXChildVisit_Recurse;
3656 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3658 return clang_getNullCursor();
3660 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3661 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3663 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3664 CXCursor Result = cxcursor::getCursor(TU, SLoc);
3666 bool Logging = getenv("LIBCLANG_LOGGING");
3669 unsigned SearchLine, SearchColumn;
3671 unsigned ResultLine, ResultColumn;
3672 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3673 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3674 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3676 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3677 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3679 SearchFileName = clang_getFileName(SearchFile);
3680 ResultFileName = clang_getFileName(ResultFile);
3681 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3682 USR = clang_getCursorUSR(Result);
3683 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3684 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3685 clang_getCString(KindSpelling),
3686 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3687 clang_getCString(USR), IsDef);
3688 clang_disposeString(SearchFileName);
3689 clang_disposeString(ResultFileName);
3690 clang_disposeString(KindSpelling);
3691 clang_disposeString(USR);
3693 CXCursor Definition = clang_getCursorDefinition(Result);
3694 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3695 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3696 CXString DefinitionKindSpelling
3697 = clang_getCursorKindSpelling(Definition.kind);
3698 CXFile DefinitionFile;
3699 unsigned DefinitionLine, DefinitionColumn;
3700 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3701 &DefinitionLine, &DefinitionColumn, 0);
3702 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3703 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3704 clang_getCString(DefinitionKindSpelling),
3705 clang_getCString(DefinitionFileName),
3706 DefinitionLine, DefinitionColumn);
3707 clang_disposeString(DefinitionFileName);
3708 clang_disposeString(DefinitionKindSpelling);
3715 CXCursor clang_getNullCursor(void) {
3716 return MakeCXCursorInvalid(CXCursor_InvalidFile);
3719 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3723 unsigned clang_hashCursor(CXCursor C) {
3725 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3728 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3729 std::make_pair(C.kind, C.data[Index]));
3732 unsigned clang_isInvalid(enum CXCursorKind K) {
3733 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3736 unsigned clang_isDeclaration(enum CXCursorKind K) {
3737 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3740 unsigned clang_isReference(enum CXCursorKind K) {
3741 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3744 unsigned clang_isExpression(enum CXCursorKind K) {
3745 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3748 unsigned clang_isStatement(enum CXCursorKind K) {
3749 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3752 unsigned clang_isAttribute(enum CXCursorKind K) {
3753 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3756 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3757 return K == CXCursor_TranslationUnit;
3760 unsigned clang_isPreprocessing(enum CXCursorKind K) {
3761 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3764 unsigned clang_isUnexposed(enum CXCursorKind K) {
3766 case CXCursor_UnexposedDecl:
3767 case CXCursor_UnexposedExpr:
3768 case CXCursor_UnexposedStmt:
3769 case CXCursor_UnexposedAttr:
3776 CXCursorKind clang_getCursorKind(CXCursor C) {
3780 CXSourceLocation clang_getCursorLocation(CXCursor C) {
3781 if (clang_isReference(C.kind)) {
3783 case CXCursor_ObjCSuperClassRef: {
3784 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3785 = getCursorObjCSuperClassRef(C);
3786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3789 case CXCursor_ObjCProtocolRef: {
3790 std::pair<ObjCProtocolDecl *, SourceLocation> P
3791 = getCursorObjCProtocolRef(C);
3792 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3795 case CXCursor_ObjCClassRef: {
3796 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3797 = getCursorObjCClassRef(C);
3798 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3801 case CXCursor_TypeRef: {
3802 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3803 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3806 case CXCursor_TemplateRef: {
3807 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3808 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3811 case CXCursor_NamespaceRef: {
3812 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3813 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3816 case CXCursor_MemberRef: {
3817 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3818 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3821 case CXCursor_VariableRef: {
3822 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3826 case CXCursor_CXXBaseSpecifier: {
3827 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3829 return clang_getNullLocation();
3831 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3832 return cxloc::translateSourceLocation(getCursorContext(C),
3833 TSInfo->getTypeLoc().getBeginLoc());
3835 return cxloc::translateSourceLocation(getCursorContext(C),
3836 BaseSpec->getLocStart());
3839 case CXCursor_LabelRef: {
3840 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3841 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3844 case CXCursor_OverloadedDeclRef:
3845 return cxloc::translateSourceLocation(getCursorContext(C),
3846 getCursorOverloadedDeclRef(C).second);
3849 // FIXME: Need a way to enumerate all non-reference cases.
3850 llvm_unreachable("Missed a reference kind");
3854 if (clang_isExpression(C.kind))
3855 return cxloc::translateSourceLocation(getCursorContext(C),
3856 getLocationFromExpr(getCursorExpr(C)));
3858 if (clang_isStatement(C.kind))
3859 return cxloc::translateSourceLocation(getCursorContext(C),
3860 getCursorStmt(C)->getLocStart());
3862 if (C.kind == CXCursor_PreprocessingDirective) {
3863 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3864 return cxloc::translateSourceLocation(getCursorContext(C), L);
3867 if (C.kind == CXCursor_MacroExpansion) {
3869 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3870 return cxloc::translateSourceLocation(getCursorContext(C), L);
3873 if (C.kind == CXCursor_MacroDefinition) {
3874 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3875 return cxloc::translateSourceLocation(getCursorContext(C), L);
3878 if (C.kind == CXCursor_InclusionDirective) {
3880 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3881 return cxloc::translateSourceLocation(getCursorContext(C), L);
3884 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3885 return clang_getNullLocation();
3887 Decl *D = getCursorDecl(C);
3889 return clang_getNullLocation();
3891 SourceLocation Loc = D->getLocation();
3892 // FIXME: Multiple variables declared in a single declaration
3893 // currently lack the information needed to correctly determine their
3894 // ranges when accounting for the type-specifier. We use context
3895 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3896 // and if so, whether it is the first decl.
3897 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3898 if (!cxcursor::isFirstInDeclGroup(C))
3899 Loc = VD->getLocation();
3902 // For ObjC methods, give the start location of the method name.
3903 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3904 Loc = MD->getSelectorStartLoc();
3906 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3911 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3914 // Guard against an invalid SourceLocation, or we may assert in one
3915 // of the following calls.
3916 if (SLoc.isInvalid())
3917 return clang_getNullCursor();
3919 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3921 // Translate the given source location to make it point at the beginning of
3922 // the token under the cursor.
3923 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3924 CXXUnit->getASTContext().getLangOpts());
3926 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3927 if (SLoc.isValid()) {
3928 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3929 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3930 /*VisitPreprocessorLast=*/true,
3931 /*VisitIncludedEntities=*/false,
3932 SourceLocation(SLoc));
3933 CursorVis.visitFileRegion();
3939 static SourceRange getRawCursorExtent(CXCursor C) {
3940 if (clang_isReference(C.kind)) {
3942 case CXCursor_ObjCSuperClassRef:
3943 return getCursorObjCSuperClassRef(C).second;
3945 case CXCursor_ObjCProtocolRef:
3946 return getCursorObjCProtocolRef(C).second;
3948 case CXCursor_ObjCClassRef:
3949 return getCursorObjCClassRef(C).second;
3951 case CXCursor_TypeRef:
3952 return getCursorTypeRef(C).second;
3954 case CXCursor_TemplateRef:
3955 return getCursorTemplateRef(C).second;
3957 case CXCursor_NamespaceRef:
3958 return getCursorNamespaceRef(C).second;
3960 case CXCursor_MemberRef:
3961 return getCursorMemberRef(C).second;
3963 case CXCursor_CXXBaseSpecifier:
3964 return getCursorCXXBaseSpecifier(C)->getSourceRange();
3966 case CXCursor_LabelRef:
3967 return getCursorLabelRef(C).second;
3969 case CXCursor_OverloadedDeclRef:
3970 return getCursorOverloadedDeclRef(C).second;
3972 case CXCursor_VariableRef:
3973 return getCursorVariableRef(C).second;
3976 // FIXME: Need a way to enumerate all non-reference cases.
3977 llvm_unreachable("Missed a reference kind");
3981 if (clang_isExpression(C.kind))
3982 return getCursorExpr(C)->getSourceRange();
3984 if (clang_isStatement(C.kind))
3985 return getCursorStmt(C)->getSourceRange();
3987 if (clang_isAttribute(C.kind))
3988 return getCursorAttr(C)->getRange();
3990 if (C.kind == CXCursor_PreprocessingDirective)
3991 return cxcursor::getCursorPreprocessingDirective(C);
3993 if (C.kind == CXCursor_MacroExpansion) {
3994 ASTUnit *TU = getCursorASTUnit(C);
3995 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3996 return TU->mapRangeFromPreamble(Range);
3999 if (C.kind == CXCursor_MacroDefinition) {
4000 ASTUnit *TU = getCursorASTUnit(C);
4001 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4002 return TU->mapRangeFromPreamble(Range);
4005 if (C.kind == CXCursor_InclusionDirective) {
4006 ASTUnit *TU = getCursorASTUnit(C);
4007 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4008 return TU->mapRangeFromPreamble(Range);
4011 if (C.kind == CXCursor_TranslationUnit) {
4012 ASTUnit *TU = getCursorASTUnit(C);
4013 FileID MainID = TU->getSourceManager().getMainFileID();
4014 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4015 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4016 return SourceRange(Start, End);
4019 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4020 Decl *D = cxcursor::getCursorDecl(C);
4022 return SourceRange();
4024 SourceRange R = D->getSourceRange();
4025 // FIXME: Multiple variables declared in a single declaration
4026 // currently lack the information needed to correctly determine their
4027 // ranges when accounting for the type-specifier. We use context
4028 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4029 // and if so, whether it is the first decl.
4030 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4031 if (!cxcursor::isFirstInDeclGroup(C))
4032 R.setBegin(VD->getLocation());
4036 return SourceRange();
4039 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
4040 /// the decl-specifier-seq for declarations.
4041 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4042 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4043 Decl *D = cxcursor::getCursorDecl(C);
4045 return SourceRange();
4047 SourceRange R = D->getSourceRange();
4049 // Adjust the start of the location for declarations preceded by
4050 // declaration specifiers.
4051 SourceLocation StartLoc;
4052 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4053 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4054 StartLoc = TI->getTypeLoc().getLocStart();
4055 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4056 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4057 StartLoc = TI->getTypeLoc().getLocStart();
4060 if (StartLoc.isValid() && R.getBegin().isValid() &&
4061 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4062 R.setBegin(StartLoc);
4064 // FIXME: Multiple variables declared in a single declaration
4065 // currently lack the information needed to correctly determine their
4066 // ranges when accounting for the type-specifier. We use context
4067 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4068 // and if so, whether it is the first decl.
4069 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4070 if (!cxcursor::isFirstInDeclGroup(C))
4071 R.setBegin(VD->getLocation());
4077 return getRawCursorExtent(C);
4082 CXSourceRange clang_getCursorExtent(CXCursor C) {
4083 SourceRange R = getRawCursorExtent(C);
4085 return clang_getNullRange();
4087 return cxloc::translateSourceRange(getCursorContext(C), R);
4090 CXCursor clang_getCursorReferenced(CXCursor C) {
4091 if (clang_isInvalid(C.kind))
4092 return clang_getNullCursor();
4094 CXTranslationUnit tu = getCursorTU(C);
4095 if (clang_isDeclaration(C.kind)) {
4096 Decl *D = getCursorDecl(C);
4098 return clang_getNullCursor();
4099 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4100 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4101 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4102 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4103 return MakeCXCursor(Property, tu);
4108 if (clang_isExpression(C.kind)) {
4109 Expr *E = getCursorExpr(C);
4110 Decl *D = getDeclFromExpr(E);
4112 CXCursor declCursor = MakeCXCursor(D, tu);
4113 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4118 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4119 return MakeCursorOverloadedDeclRef(Ovl, tu);
4121 return clang_getNullCursor();
4124 if (clang_isStatement(C.kind)) {
4125 Stmt *S = getCursorStmt(C);
4126 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4127 if (LabelDecl *label = Goto->getLabel())
4128 if (LabelStmt *labelS = label->getStmt())
4129 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4131 return clang_getNullCursor();
4134 if (C.kind == CXCursor_MacroExpansion) {
4135 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
4136 return MakeMacroDefinitionCursor(Def, tu);
4139 if (!clang_isReference(C.kind))
4140 return clang_getNullCursor();
4143 case CXCursor_ObjCSuperClassRef:
4144 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4146 case CXCursor_ObjCProtocolRef: {
4147 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4148 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4149 return MakeCXCursor(Def, tu);
4151 return MakeCXCursor(Prot, tu);
4154 case CXCursor_ObjCClassRef: {
4155 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4156 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4157 return MakeCXCursor(Def, tu);
4159 return MakeCXCursor(Class, tu);
4162 case CXCursor_TypeRef:
4163 return MakeCXCursor(getCursorTypeRef(C).first, tu );
4165 case CXCursor_TemplateRef:
4166 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4168 case CXCursor_NamespaceRef:
4169 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4171 case CXCursor_MemberRef:
4172 return MakeCXCursor(getCursorMemberRef(C).first, tu );
4174 case CXCursor_CXXBaseSpecifier: {
4175 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4176 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4180 case CXCursor_LabelRef:
4181 // FIXME: We end up faking the "parent" declaration here because we
4182 // don't want to make CXCursor larger.
4183 return MakeCXCursor(getCursorLabelRef(C).first,
4184 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4185 .getTranslationUnitDecl(),
4188 case CXCursor_OverloadedDeclRef:
4191 case CXCursor_VariableRef:
4192 return MakeCXCursor(getCursorVariableRef(C).first, tu);
4195 // We would prefer to enumerate all non-reference cursor kinds here.
4196 llvm_unreachable("Unhandled reference cursor kind");
4200 CXCursor clang_getCursorDefinition(CXCursor C) {
4201 if (clang_isInvalid(C.kind))
4202 return clang_getNullCursor();
4204 CXTranslationUnit TU = getCursorTU(C);
4206 bool WasReference = false;
4207 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4208 C = clang_getCursorReferenced(C);
4209 WasReference = true;
4212 if (C.kind == CXCursor_MacroExpansion)
4213 return clang_getCursorReferenced(C);
4215 if (!clang_isDeclaration(C.kind))
4216 return clang_getNullCursor();
4218 Decl *D = getCursorDecl(C);
4220 return clang_getNullCursor();
4222 switch (D->getKind()) {
4223 // Declaration kinds that don't really separate the notions of
4224 // declaration and definition.
4225 case Decl::Namespace:
4227 case Decl::TypeAlias:
4228 case Decl::TypeAliasTemplate:
4229 case Decl::TemplateTypeParm:
4230 case Decl::EnumConstant:
4232 case Decl::IndirectField:
4233 case Decl::ObjCIvar:
4234 case Decl::ObjCAtDefsField:
4235 case Decl::ImplicitParam:
4237 case Decl::NonTypeTemplateParm:
4238 case Decl::TemplateTemplateParm:
4239 case Decl::ObjCCategoryImpl:
4240 case Decl::ObjCImplementation:
4241 case Decl::AccessSpec:
4242 case Decl::LinkageSpec:
4243 case Decl::ObjCPropertyImpl:
4244 case Decl::FileScopeAsm:
4245 case Decl::StaticAssert:
4247 case Decl::Label: // FIXME: Is this right??
4248 case Decl::ClassScopeFunctionSpecialization:
4252 // Declaration kinds that don't make any sense here, but are
4253 // nonetheless harmless.
4254 case Decl::TranslationUnit:
4257 // Declaration kinds for which the definition is not resolvable.
4258 case Decl::UnresolvedUsingTypename:
4259 case Decl::UnresolvedUsingValue:
4262 case Decl::UsingDirective:
4263 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4266 case Decl::NamespaceAlias:
4267 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4271 case Decl::CXXRecord:
4272 case Decl::ClassTemplateSpecialization:
4273 case Decl::ClassTemplatePartialSpecialization:
4274 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4275 return MakeCXCursor(Def, TU);
4276 return clang_getNullCursor();
4278 case Decl::Function:
4279 case Decl::CXXMethod:
4280 case Decl::CXXConstructor:
4281 case Decl::CXXDestructor:
4282 case Decl::CXXConversion: {
4283 const FunctionDecl *Def = 0;
4284 if (cast<FunctionDecl>(D)->getBody(Def))
4285 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4286 return clang_getNullCursor();
4290 // Ask the variable if it has a definition.
4291 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4292 return MakeCXCursor(Def, TU);
4293 return clang_getNullCursor();
4296 case Decl::FunctionTemplate: {
4297 const FunctionDecl *Def = 0;
4298 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4299 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4300 return clang_getNullCursor();
4303 case Decl::ClassTemplate: {
4304 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4306 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4308 return clang_getNullCursor();
4312 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4313 D->getLocation(), TU);
4315 case Decl::UsingShadow:
4316 return clang_getCursorDefinition(
4317 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4320 case Decl::ObjCMethod: {
4321 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4322 if (Method->isThisDeclarationADefinition())
4325 // Dig out the method definition in the associated
4326 // @implementation, if we have it.
4327 // FIXME: The ASTs should make finding the definition easier.
4328 if (ObjCInterfaceDecl *Class
4329 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4330 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4331 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4332 Method->isInstanceMethod()))
4333 if (Def->isThisDeclarationADefinition())
4334 return MakeCXCursor(Def, TU);
4336 return clang_getNullCursor();
4339 case Decl::ObjCCategory:
4340 if (ObjCCategoryImplDecl *Impl
4341 = cast<ObjCCategoryDecl>(D)->getImplementation())
4342 return MakeCXCursor(Impl, TU);
4343 return clang_getNullCursor();
4345 case Decl::ObjCProtocol:
4346 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4347 return MakeCXCursor(Def, TU);
4348 return clang_getNullCursor();
4350 case Decl::ObjCInterface: {
4351 // There are two notions of a "definition" for an Objective-C
4352 // class: the interface and its implementation. When we resolved a
4353 // reference to an Objective-C class, produce the @interface as
4354 // the definition; when we were provided with the interface,
4355 // produce the @implementation as the definition.
4356 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4358 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4359 return MakeCXCursor(Def, TU);
4360 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4361 return MakeCXCursor(Impl, TU);
4362 return clang_getNullCursor();
4365 case Decl::ObjCProperty:
4366 // FIXME: We don't really know where to find the
4367 // ObjCPropertyImplDecls that implement this property.
4368 return clang_getNullCursor();
4370 case Decl::ObjCCompatibleAlias:
4371 if (ObjCInterfaceDecl *Class
4372 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4373 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4374 return MakeCXCursor(Def, TU);
4376 return clang_getNullCursor();
4379 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4380 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4381 return clang_getNullCursor();
4383 case Decl::FriendTemplate:
4384 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4385 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4386 return clang_getNullCursor();
4389 return clang_getNullCursor();
4392 unsigned clang_isCursorDefinition(CXCursor C) {
4393 if (!clang_isDeclaration(C.kind))
4396 return clang_getCursorDefinition(C) == C;
4399 CXCursor clang_getCanonicalCursor(CXCursor C) {
4400 if (!clang_isDeclaration(C.kind))
4403 if (Decl *D = getCursorDecl(C)) {
4404 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4405 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4406 return MakeCXCursor(CatD, getCursorTU(C));
4408 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4409 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4410 return MakeCXCursor(IFD, getCursorTU(C));
4412 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4418 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4419 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4422 unsigned clang_getNumOverloadedDecls(CXCursor C) {
4423 if (C.kind != CXCursor_OverloadedDeclRef)
4426 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4427 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4428 return E->getNumDecls();
4430 if (OverloadedTemplateStorage *S
4431 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4434 Decl *D = Storage.get<Decl*>();
4435 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4436 return Using->shadow_size();
4441 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4442 if (cursor.kind != CXCursor_OverloadedDeclRef)
4443 return clang_getNullCursor();
4445 if (index >= clang_getNumOverloadedDecls(cursor))
4446 return clang_getNullCursor();
4448 CXTranslationUnit TU = getCursorTU(cursor);
4449 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4450 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4451 return MakeCXCursor(E->decls_begin()[index], TU);
4453 if (OverloadedTemplateStorage *S
4454 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4455 return MakeCXCursor(S->begin()[index], TU);
4457 Decl *D = Storage.get<Decl*>();
4458 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4459 // FIXME: This is, unfortunately, linear time.
4460 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4461 std::advance(Pos, index);
4462 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4465 return clang_getNullCursor();
4468 void clang_getDefinitionSpellingAndExtent(CXCursor C,
4469 const char **startBuf,
4470 const char **endBuf,
4471 unsigned *startLine,
4472 unsigned *startColumn,
4474 unsigned *endColumn) {
4475 assert(getCursorDecl(C) && "CXCursor has null decl");
4476 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4477 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4478 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4480 SourceManager &SM = FD->getASTContext().getSourceManager();
4481 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4482 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4483 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4484 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4485 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4486 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4490 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4491 unsigned PieceIndex) {
4492 RefNamePieces Pieces;
4495 case CXCursor_MemberRefExpr:
4496 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4497 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4498 E->getQualifierLoc().getSourceRange());
4501 case CXCursor_DeclRefExpr:
4502 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4503 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4504 E->getQualifierLoc().getSourceRange(),
4505 E->getOptionalExplicitTemplateArgs());
4508 case CXCursor_CallExpr:
4509 if (CXXOperatorCallExpr *OCE =
4510 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4511 Expr *Callee = OCE->getCallee();
4512 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4513 Callee = ICE->getSubExpr();
4515 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4516 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4517 DRE->getQualifierLoc().getSourceRange());
4525 if (Pieces.empty()) {
4526 if (PieceIndex == 0)
4527 return clang_getCursorExtent(C);
4528 } else if (PieceIndex < Pieces.size()) {
4529 SourceRange R = Pieces[PieceIndex];
4531 return cxloc::translateSourceRange(getCursorContext(C), R);
4534 return clang_getNullRange();
4537 void clang_enableStackTraces(void) {
4538 llvm::sys::PrintStackTraceOnErrorSignal();
4541 void clang_executeOnThread(void (*fn)(void*), void *user_data,
4542 unsigned stack_size) {
4543 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4546 } // end: extern "C"
4548 //===----------------------------------------------------------------------===//
4549 // Token-based Operations.
4550 //===----------------------------------------------------------------------===//
4553 * int_data[0]: a CXTokenKind
4554 * int_data[1]: starting token location
4555 * int_data[2]: token length
4556 * int_data[3]: reserved
4557 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
4562 CXTokenKind clang_getTokenKind(CXToken CXTok) {
4563 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4566 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4567 switch (clang_getTokenKind(CXTok)) {
4568 case CXToken_Identifier:
4569 case CXToken_Keyword:
4570 // We know we have an IdentifierInfo*, so use that.
4571 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4574 case CXToken_Literal: {
4575 // We have stashed the starting pointer in the ptr_data field. Use it.
4576 const char *Text = static_cast<const char *>(CXTok.ptr_data);
4577 return createCXString(StringRef(Text, CXTok.int_data[2]));
4580 case CXToken_Punctuation:
4581 case CXToken_Comment:
4585 // We have to find the starting buffer pointer the hard way, by
4586 // deconstructing the source location.
4587 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4589 return createCXString("");
4591 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4592 std::pair<FileID, unsigned> LocInfo
4593 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4594 bool Invalid = false;
4596 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4598 return createCXString("");
4600 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4603 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4604 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4606 return clang_getNullLocation();
4608 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4609 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4612 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4613 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4615 return clang_getNullRange();
4617 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4618 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4621 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4622 SmallVectorImpl<CXToken> &CXTokens) {
4623 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4624 std::pair<FileID, unsigned> BeginLocInfo
4625 = SourceMgr.getDecomposedLoc(Range.getBegin());
4626 std::pair<FileID, unsigned> EndLocInfo
4627 = SourceMgr.getDecomposedLoc(Range.getEnd());
4629 // Cannot tokenize across files.
4630 if (BeginLocInfo.first != EndLocInfo.first)
4634 bool Invalid = false;
4636 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4640 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4641 CXXUnit->getASTContext().getLangOpts(),
4642 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4643 Lex.SetCommentRetentionState(true);
4645 // Lex tokens until we hit the end of the range.
4646 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4648 bool previousWasAt = false;
4650 // Lex the next token
4651 Lex.LexFromRawLexer(Tok);
4652 if (Tok.is(tok::eof))
4655 // Initialize the CXToken.
4659 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4660 CXTok.int_data[2] = Tok.getLength();
4661 CXTok.int_data[3] = 0;
4663 // - Kind-specific fields
4664 if (Tok.isLiteral()) {
4665 CXTok.int_data[0] = CXToken_Literal;
4666 CXTok.ptr_data = (void *)Tok.getLiteralData();
4667 } else if (Tok.is(tok::raw_identifier)) {
4668 // Lookup the identifier to determine whether we have a keyword.
4670 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4672 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4673 CXTok.int_data[0] = CXToken_Keyword;
4676 CXTok.int_data[0] = Tok.is(tok::identifier)
4677 ? CXToken_Identifier
4680 CXTok.ptr_data = II;
4681 } else if (Tok.is(tok::comment)) {
4682 CXTok.int_data[0] = CXToken_Comment;
4685 CXTok.int_data[0] = CXToken_Punctuation;
4688 CXTokens.push_back(CXTok);
4689 previousWasAt = Tok.is(tok::at);
4690 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4693 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4694 CXToken **Tokens, unsigned *NumTokens) {
4700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4701 if (!CXXUnit || !Tokens || !NumTokens)
4704 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4706 SourceRange R = cxloc::translateCXSourceRange(Range);
4710 SmallVector<CXToken, 32> CXTokens;
4711 getTokens(CXXUnit, R, CXTokens);
4713 if (CXTokens.empty())
4716 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4717 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4718 *NumTokens = CXTokens.size();
4721 void clang_disposeTokens(CXTranslationUnit TU,
4722 CXToken *Tokens, unsigned NumTokens) {
4726 } // end: extern "C"
4728 //===----------------------------------------------------------------------===//
4729 // Token annotation APIs.
4730 //===----------------------------------------------------------------------===//
4732 typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4733 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4735 CXClientData client_data);
4737 class AnnotateTokensWorker {
4738 AnnotateTokensData &Annotated;
4743 unsigned PreprocessingTokIdx;
4744 CursorVisitor AnnotateVis;
4745 SourceManager &SrcMgr;
4746 bool HasContextSensitiveKeywords;
4748 bool MoreTokens() const { return TokIdx < NumTokens; }
4749 unsigned NextToken() const { return TokIdx; }
4750 void AdvanceToken() { ++TokIdx; }
4751 SourceLocation GetTokenLoc(unsigned tokI) {
4752 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4754 bool isFunctionMacroToken(unsigned tokI) const {
4755 return Tokens[tokI].int_data[3] != 0;
4757 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4758 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4761 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4762 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4766 AnnotateTokensWorker(AnnotateTokensData &annotated,
4767 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4768 CXTranslationUnit tu, SourceRange RegionOfInterest)
4769 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4770 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4772 AnnotateTokensVisitor, this,
4773 /*VisitPreprocessorLast=*/true,
4774 /*VisitIncludedEntities=*/false,
4776 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4777 HasContextSensitiveKeywords(false) { }
4779 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4780 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4781 void AnnotateTokens();
4783 /// \brief Determine whether the annotator saw any cursors that have
4784 /// context-sensitive keywords.
4785 bool hasContextSensitiveKeywords() const {
4786 return HasContextSensitiveKeywords;
4791 void AnnotateTokensWorker::AnnotateTokens() {
4792 // Walk the AST within the region of interest, annotating tokens
4794 AnnotateVis.visitFileRegion();
4796 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4797 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4798 if (Pos != Annotated.end() &&
4799 (clang_isInvalid(Cursors[I].kind) ||
4800 Pos->second.kind != CXCursor_PreprocessingDirective))
4801 Cursors[I] = Pos->second;
4804 // Finish up annotating any tokens left.
4808 const CXCursor &C = clang_getNullCursor();
4809 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4810 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4813 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4814 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4818 /// \brief It annotates and advances tokens with a cursor until the comparison
4819 //// between the cursor location and the source range is the same as
4820 /// \arg compResult.
4822 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4823 /// Pass RangeOverlap to annotate tokens inside a range.
4824 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4825 RangeComparisonResult compResult,
4826 SourceRange range) {
4827 while (MoreTokens()) {
4828 const unsigned I = NextToken();
4829 if (isFunctionMacroToken(I))
4830 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4832 SourceLocation TokLoc = GetTokenLoc(I);
4833 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4834 Cursors[I] = updateC;
4842 /// \brief Special annotation handling for macro argument tokens.
4843 void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4845 RangeComparisonResult compResult,
4846 SourceRange range) {
4847 assert(MoreTokens());
4848 assert(isFunctionMacroToken(NextToken()) &&
4849 "Should be called only for macro arg tokens");
4851 // This works differently than annotateAndAdvanceTokens; because expanded
4852 // macro arguments can have arbitrary translation-unit source order, we do not
4853 // advance the token index one by one until a token fails the range test.
4854 // We only advance once past all of the macro arg tokens if all of them
4855 // pass the range test. If one of them fails we keep the token index pointing
4856 // at the start of the macro arg tokens so that the failing token will be
4857 // annotated by a subsequent annotation try.
4859 bool atLeastOneCompFail = false;
4861 unsigned I = NextToken();
4862 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4863 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4864 if (TokLoc.isFileID())
4865 continue; // not macro arg token, it's parens or comma.
4866 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4867 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4868 Cursors[I] = updateC;
4870 atLeastOneCompFail = true;
4873 if (!atLeastOneCompFail)
4874 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4877 enum CXChildVisitResult
4878 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4879 CXSourceLocation Loc = clang_getCursorLocation(cursor);
4880 SourceRange cursorRange = getRawCursorExtent(cursor);
4881 if (cursorRange.isInvalid())
4882 return CXChildVisit_Recurse;
4884 if (!HasContextSensitiveKeywords) {
4885 // Objective-C properties can have context-sensitive keywords.
4886 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4887 if (ObjCPropertyDecl *Property
4888 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4889 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4891 // Objective-C methods can have context-sensitive keywords.
4892 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4893 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4894 if (ObjCMethodDecl *Method
4895 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4896 if (Method->getObjCDeclQualifier())
4897 HasContextSensitiveKeywords = true;
4899 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4900 PEnd = Method->param_end();
4902 if ((*P)->getObjCDeclQualifier()) {
4903 HasContextSensitiveKeywords = true;
4910 // C++ methods can have context-sensitive keywords.
4911 else if (cursor.kind == CXCursor_CXXMethod) {
4912 if (CXXMethodDecl *Method
4913 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4914 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4915 HasContextSensitiveKeywords = true;
4918 // C++ classes can have context-sensitive keywords.
4919 else if (cursor.kind == CXCursor_StructDecl ||
4920 cursor.kind == CXCursor_ClassDecl ||
4921 cursor.kind == CXCursor_ClassTemplate ||
4922 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4923 if (Decl *D = getCursorDecl(cursor))
4924 if (D->hasAttr<FinalAttr>())
4925 HasContextSensitiveKeywords = true;
4929 if (clang_isPreprocessing(cursor.kind)) {
4930 // For macro expansions, just note where the beginning of the macro
4931 // expansion occurs.
4932 if (cursor.kind == CXCursor_MacroExpansion) {
4933 Annotated[Loc.int_data] = cursor;
4934 return CXChildVisit_Recurse;
4937 // Items in the preprocessing record are kept separate from items in
4938 // declarations, so we keep a separate token index.
4939 unsigned SavedTokIdx = TokIdx;
4940 TokIdx = PreprocessingTokIdx;
4942 // Skip tokens up until we catch up to the beginning of the preprocessing
4944 while (MoreTokens()) {
4945 const unsigned I = NextToken();
4946 SourceLocation TokLoc = GetTokenLoc(I);
4947 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4958 // Look at all of the tokens within this range.
4959 while (MoreTokens()) {
4960 const unsigned I = NextToken();
4961 SourceLocation TokLoc = GetTokenLoc(I);
4962 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4964 llvm_unreachable("Infeasible");
4968 Cursors[I] = cursor;
4975 // Save the preprocessing token index; restore the non-preprocessing
4977 PreprocessingTokIdx = TokIdx;
4978 TokIdx = SavedTokIdx;
4979 return CXChildVisit_Recurse;
4982 if (cursorRange.isInvalid())
4983 return CXChildVisit_Continue;
4985 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4987 // Adjust the annotated range based specific declarations.
4988 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4989 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4990 Decl *D = cxcursor::getCursorDecl(cursor);
4992 SourceLocation StartLoc;
4993 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
4994 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4995 StartLoc = TI->getTypeLoc().getLocStart();
4996 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
4997 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4998 StartLoc = TI->getTypeLoc().getLocStart();
5001 if (StartLoc.isValid() && L.isValid() &&
5002 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5003 cursorRange.setBegin(StartLoc);
5006 // If the location of the cursor occurs within a macro instantiation, record
5007 // the spelling location of the cursor in our annotation map. We can then
5008 // paper over the token labelings during a post-processing step to try and
5009 // get cursor mappings for tokens that are the *arguments* of a macro
5011 if (L.isMacroID()) {
5012 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5013 // Only invalidate the old annotation if it isn't part of a preprocessing
5014 // directive. Here we assume that the default construction of CXCursor
5015 // results in CXCursor.kind being an initialized value (i.e., 0). If
5016 // this isn't the case, we can fix by doing lookup + insertion.
5018 CXCursor &oldC = Annotated[rawEncoding];
5019 if (!clang_isPreprocessing(oldC.kind))
5023 const enum CXCursorKind K = clang_getCursorKind(parent);
5024 const CXCursor updateC =
5025 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5026 ? clang_getNullCursor() : parent;
5028 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5030 // Avoid having the cursor of an expression "overwrite" the annotation of the
5031 // variable declaration that it belongs to.
5032 // This can happen for C++ constructor expressions whose range generally
5033 // include the variable declaration, e.g.:
5034 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5035 if (clang_isExpression(cursorK)) {
5036 Expr *E = getCursorExpr(cursor);
5037 if (Decl *D = getCursorParentDecl(cursor)) {
5038 const unsigned I = NextToken();
5039 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5040 E->getLocStart() == D->getLocation() &&
5041 E->getLocStart() == GetTokenLoc(I)) {
5042 Cursors[I] = updateC;
5048 // Visit children to get their cursor information.
5049 const unsigned BeforeChildren = NextToken();
5050 VisitChildren(cursor);
5051 const unsigned AfterChildren = NextToken();
5053 // Scan the tokens that are at the end of the cursor, but are not captured
5054 // but the child cursors.
5055 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5057 // Scan the tokens that are at the beginning of the cursor, but are not
5058 // capture by the child cursors.
5059 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5060 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5063 Cursors[I] = cursor;
5066 return CXChildVisit_Continue;
5069 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5071 CXClientData client_data) {
5072 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5077 /// \brief Uses the macro expansions in the preprocessing record to find
5078 /// and mark tokens that are macro arguments. This info is used by the
5079 /// AnnotateTokensWorker.
5080 class MarkMacroArgTokensVisitor {
5087 MarkMacroArgTokensVisitor(SourceManager &SM,
5088 CXToken *tokens, unsigned numTokens)
5089 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5091 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5092 if (cursor.kind != CXCursor_MacroExpansion)
5093 return CXChildVisit_Continue;
5095 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5096 if (macroRange.getBegin() == macroRange.getEnd())
5097 return CXChildVisit_Continue; // it's not a function macro.
5099 for (; CurIdx < NumTokens; ++CurIdx) {
5100 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5101 macroRange.getBegin()))
5105 if (CurIdx == NumTokens)
5106 return CXChildVisit_Break;
5108 for (; CurIdx < NumTokens; ++CurIdx) {
5109 SourceLocation tokLoc = getTokenLoc(CurIdx);
5110 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5113 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5116 if (CurIdx == NumTokens)
5117 return CXChildVisit_Break;
5119 return CXChildVisit_Continue;
5123 SourceLocation getTokenLoc(unsigned tokI) {
5124 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5127 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5128 // The third field is reserved and currently not used. Use it here
5129 // to mark macro arg expanded tokens with their expanded locations.
5130 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5134 } // end anonymous namespace
5136 static CXChildVisitResult
5137 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5138 CXClientData client_data) {
5139 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5144 struct clang_annotateTokens_Data {
5145 CXTranslationUnit TU;
5153 static void annotatePreprocessorTokens(CXTranslationUnit TU,
5154 SourceRange RegionOfInterest,
5155 AnnotateTokensData &Annotated) {
5156 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5158 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5159 std::pair<FileID, unsigned> BeginLocInfo
5160 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5161 std::pair<FileID, unsigned> EndLocInfo
5162 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5164 if (BeginLocInfo.first != EndLocInfo.first)
5168 bool Invalid = false;
5169 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5170 if (Buffer.empty() || Invalid)
5173 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5174 CXXUnit->getASTContext().getLangOpts(),
5175 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5177 Lex.SetCommentRetentionState(true);
5179 // Lex tokens in raw mode until we hit the end of the range, to avoid
5180 // entering #includes or expanding macros.
5183 Lex.LexFromRawLexer(Tok);
5186 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5187 // We have found a preprocessing directive. Gobble it up so that we
5188 // don't see it while preprocessing these tokens later, but keep track
5189 // of all of the token locations inside this preprocessing directive so
5190 // that we can annotate them appropriately.
5192 // FIXME: Some simple tests here could identify macro definitions and
5193 // #undefs, to provide specific cursor kinds for those.
5194 SmallVector<SourceLocation, 32> Locations;
5196 Locations.push_back(Tok.getLocation());
5197 Lex.LexFromRawLexer(Tok);
5198 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5200 using namespace cxcursor;
5202 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5205 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5206 Annotated[Locations[I].getRawEncoding()] = Cursor;
5209 if (Tok.isAtStartOfLine())
5215 if (Tok.is(tok::eof))
5220 // This gets run a separate thread to avoid stack blowout.
5221 static void clang_annotateTokensImpl(void *UserData) {
5222 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5223 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5224 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5225 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5226 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5228 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5229 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5230 setThreadBackgroundPriority();
5232 // Determine the region of interest, which contains all of the tokens.
5233 SourceRange RegionOfInterest;
5234 RegionOfInterest.setBegin(
5235 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5236 RegionOfInterest.setEnd(
5237 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5238 Tokens[NumTokens-1])));
5240 // A mapping from the source locations found when re-lexing or traversing the
5241 // region of interest to the corresponding cursors.
5242 AnnotateTokensData Annotated;
5244 // Relex the tokens within the source range to look for preprocessing
5246 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5248 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5249 // Search and mark tokens that are macro argument expansions.
5250 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5252 CursorVisitor MacroArgMarker(TU,
5253 MarkMacroArgTokensVisitorDelegate, &Visitor,
5254 /*VisitPreprocessorLast=*/true,
5255 /*VisitIncludedEntities=*/false,
5257 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5260 // Annotate all of the source locations in the region of interest that map to
5261 // a specific cursor.
5262 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5263 TU, RegionOfInterest);
5265 // FIXME: We use a ridiculous stack size here because the data-recursion
5266 // algorithm uses a large stack frame than the non-data recursive version,
5267 // and AnnotationTokensWorker currently transforms the data-recursion
5268 // algorithm back into a traditional recursion by explicitly calling
5269 // VisitChildren(). We will need to remove this explicit recursive call.
5272 // If we ran into any entities that involve context-sensitive keywords,
5273 // take another pass through the tokens to mark them as such.
5274 if (W.hasContextSensitiveKeywords()) {
5275 for (unsigned I = 0; I != NumTokens; ++I) {
5276 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5279 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5280 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5281 if (ObjCPropertyDecl *Property
5282 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5283 if (Property->getPropertyAttributesAsWritten() != 0 &&
5284 llvm::StringSwitch<bool>(II->getName())
5285 .Case("readonly", true)
5286 .Case("assign", true)
5287 .Case("unsafe_unretained", true)
5288 .Case("readwrite", true)
5289 .Case("retain", true)
5291 .Case("nonatomic", true)
5292 .Case("atomic", true)
5293 .Case("getter", true)
5294 .Case("setter", true)
5295 .Case("strong", true)
5298 Tokens[I].int_data[0] = CXToken_Keyword;
5303 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5304 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5305 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5306 if (llvm::StringSwitch<bool>(II->getName())
5309 .Case("inout", true)
5310 .Case("oneway", true)
5311 .Case("bycopy", true)
5312 .Case("byref", true)
5314 Tokens[I].int_data[0] = CXToken_Keyword;
5318 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5319 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5320 Tokens[I].int_data[0] = CXToken_Keyword;
5329 void clang_annotateTokens(CXTranslationUnit TU,
5330 CXToken *Tokens, unsigned NumTokens,
5331 CXCursor *Cursors) {
5333 if (NumTokens == 0 || !Tokens || !Cursors)
5336 // Any token we don't specifically annotate will have a NULL cursor.
5337 CXCursor C = clang_getNullCursor();
5338 for (unsigned I = 0; I != NumTokens; ++I)
5341 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5345 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5347 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5348 llvm::CrashRecoveryContext CRC;
5349 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5350 GetSafetyThreadStackSize() * 2)) {
5351 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5355 } // end: extern "C"
5357 //===----------------------------------------------------------------------===//
5358 // Operations for querying linkage of a cursor.
5359 //===----------------------------------------------------------------------===//
5362 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5363 if (!clang_isDeclaration(cursor.kind))
5364 return CXLinkage_Invalid;
5366 Decl *D = cxcursor::getCursorDecl(cursor);
5367 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5368 switch (ND->getLinkage()) {
5369 case NoLinkage: return CXLinkage_NoLinkage;
5370 case InternalLinkage: return CXLinkage_Internal;
5371 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5372 case ExternalLinkage: return CXLinkage_External;
5375 return CXLinkage_Invalid;
5377 } // end: extern "C"
5379 //===----------------------------------------------------------------------===//
5380 // Operations for querying language of a cursor.
5381 //===----------------------------------------------------------------------===//
5383 static CXLanguageKind getDeclLanguage(const Decl *D) {
5385 return CXLanguage_C;
5387 switch (D->getKind()) {
5390 case Decl::ImplicitParam:
5391 case Decl::ObjCAtDefsField:
5392 case Decl::ObjCCategory:
5393 case Decl::ObjCCategoryImpl:
5394 case Decl::ObjCCompatibleAlias:
5395 case Decl::ObjCImplementation:
5396 case Decl::ObjCInterface:
5397 case Decl::ObjCIvar:
5398 case Decl::ObjCMethod:
5399 case Decl::ObjCProperty:
5400 case Decl::ObjCPropertyImpl:
5401 case Decl::ObjCProtocol:
5402 return CXLanguage_ObjC;
5403 case Decl::CXXConstructor:
5404 case Decl::CXXConversion:
5405 case Decl::CXXDestructor:
5406 case Decl::CXXMethod:
5407 case Decl::CXXRecord:
5408 case Decl::ClassTemplate:
5409 case Decl::ClassTemplatePartialSpecialization:
5410 case Decl::ClassTemplateSpecialization:
5412 case Decl::FriendTemplate:
5413 case Decl::FunctionTemplate:
5414 case Decl::LinkageSpec:
5415 case Decl::Namespace:
5416 case Decl::NamespaceAlias:
5417 case Decl::NonTypeTemplateParm:
5418 case Decl::StaticAssert:
5419 case Decl::TemplateTemplateParm:
5420 case Decl::TemplateTypeParm:
5421 case Decl::UnresolvedUsingTypename:
5422 case Decl::UnresolvedUsingValue:
5424 case Decl::UsingDirective:
5425 case Decl::UsingShadow:
5426 return CXLanguage_CPlusPlus;
5429 return CXLanguage_C;
5434 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5435 if (clang_isDeclaration(cursor.kind))
5436 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5437 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5438 return CXAvailability_Available;
5440 switch (D->getAvailability()) {
5442 case AR_NotYetIntroduced:
5443 return CXAvailability_Available;
5446 return CXAvailability_Deprecated;
5448 case AR_Unavailable:
5449 return CXAvailability_NotAvailable;
5453 return CXAvailability_Available;
5456 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5457 if (clang_isDeclaration(cursor.kind))
5458 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5460 return CXLanguage_Invalid;
5463 /// \brief If the given cursor is the "templated" declaration
5464 /// descibing a class or function template, return the class or
5465 /// function template.
5466 static Decl *maybeGetTemplateCursor(Decl *D) {
5470 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5471 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5474 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5475 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5481 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5482 if (clang_isDeclaration(cursor.kind)) {
5483 if (Decl *D = getCursorDecl(cursor)) {
5484 DeclContext *DC = D->getDeclContext();
5486 return clang_getNullCursor();
5488 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5489 getCursorTU(cursor));
5493 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5494 if (Decl *D = getCursorDecl(cursor))
5495 return MakeCXCursor(D, getCursorTU(cursor));
5498 return clang_getNullCursor();
5501 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5502 if (clang_isDeclaration(cursor.kind)) {
5503 if (Decl *D = getCursorDecl(cursor)) {
5504 DeclContext *DC = D->getLexicalDeclContext();
5506 return clang_getNullCursor();
5508 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5509 getCursorTU(cursor));
5513 // FIXME: Note that we can't easily compute the lexical context of a
5514 // statement or expression, so we return nothing.
5515 return clang_getNullCursor();
5518 void clang_getOverriddenCursors(CXCursor cursor,
5519 CXCursor **overridden,
5520 unsigned *num_overridden) {
5524 *num_overridden = 0;
5525 if (!overridden || !num_overridden)
5527 if (!clang_isDeclaration(cursor.kind))
5530 SmallVector<CXCursor, 8> Overridden;
5531 cxcursor::getOverriddenCursors(cursor, Overridden);
5533 // Don't allocate memory if we have no overriden cursors.
5534 if (Overridden.size() == 0)
5537 *num_overridden = Overridden.size();
5538 *overridden = new CXCursor [Overridden.size()];
5539 std::copy(Overridden.begin(), Overridden.end(), *overridden);
5542 void clang_disposeOverriddenCursors(CXCursor *overridden) {
5543 delete [] overridden;
5546 CXFile clang_getIncludedFile(CXCursor cursor) {
5547 if (cursor.kind != CXCursor_InclusionDirective)
5550 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5551 return (void *)ID->getFile();
5554 } // end: extern "C"
5557 //===----------------------------------------------------------------------===//
5558 // C++ AST instrospection.
5559 //===----------------------------------------------------------------------===//
5562 unsigned clang_CXXMethod_isStatic(CXCursor C) {
5563 if (!clang_isDeclaration(C.kind))
5566 CXXMethodDecl *Method = 0;
5567 Decl *D = cxcursor::getCursorDecl(C);
5568 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5569 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5571 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5572 return (Method && Method->isStatic()) ? 1 : 0;
5575 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5576 if (!clang_isDeclaration(C.kind))
5579 CXXMethodDecl *Method = 0;
5580 Decl *D = cxcursor::getCursorDecl(C);
5581 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5582 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5584 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5585 return (Method && Method->isVirtual()) ? 1 : 0;
5587 } // end: extern "C"
5589 //===----------------------------------------------------------------------===//
5590 // Attribute introspection.
5591 //===----------------------------------------------------------------------===//
5594 CXType clang_getIBOutletCollectionType(CXCursor C) {
5595 if (C.kind != CXCursor_IBOutletCollectionAttr)
5596 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5598 IBOutletCollectionAttr *A =
5599 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5601 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5603 } // end: extern "C"
5605 //===----------------------------------------------------------------------===//
5606 // Inspecting memory usage.
5607 //===----------------------------------------------------------------------===//
5609 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5611 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5612 enum CXTUResourceUsageKind k,
5613 unsigned long amount) {
5614 CXTUResourceUsageEntry entry = { k, amount };
5615 entries.push_back(entry);
5620 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5621 const char *str = "";
5623 case CXTUResourceUsage_AST:
5624 str = "ASTContext: expressions, declarations, and types";
5626 case CXTUResourceUsage_Identifiers:
5627 str = "ASTContext: identifiers";
5629 case CXTUResourceUsage_Selectors:
5630 str = "ASTContext: selectors";
5632 case CXTUResourceUsage_GlobalCompletionResults:
5633 str = "Code completion: cached global results";
5635 case CXTUResourceUsage_SourceManagerContentCache:
5636 str = "SourceManager: content cache allocator";
5638 case CXTUResourceUsage_AST_SideTables:
5639 str = "ASTContext: side tables";
5641 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5642 str = "SourceManager: malloc'ed memory buffers";
5644 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5645 str = "SourceManager: mmap'ed memory buffers";
5647 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5648 str = "ExternalASTSource: malloc'ed memory buffers";
5650 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5651 str = "ExternalASTSource: mmap'ed memory buffers";
5653 case CXTUResourceUsage_Preprocessor:
5654 str = "Preprocessor: malloc'ed memory";
5656 case CXTUResourceUsage_PreprocessingRecord:
5657 str = "Preprocessor: PreprocessingRecord";
5659 case CXTUResourceUsage_SourceManager_DataStructures:
5660 str = "SourceManager: data structures and tables";
5662 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5663 str = "Preprocessor: header search tables";
5669 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5671 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5675 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5676 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5677 ASTContext &astContext = astUnit->getASTContext();
5679 // How much memory is used by AST nodes and types?
5680 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5681 (unsigned long) astContext.getASTAllocatedMemory());
5683 // How much memory is used by identifiers?
5684 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5685 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5687 // How much memory is used for selectors?
5688 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5689 (unsigned long) astContext.Selectors.getTotalMemory());
5691 // How much memory is used by ASTContext's side tables?
5692 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5693 (unsigned long) astContext.getSideTableAllocatedMemory());
5695 // How much memory is used for caching global code completion results?
5696 unsigned long completionBytes = 0;
5697 if (GlobalCodeCompletionAllocator *completionAllocator =
5698 astUnit->getCachedCompletionAllocator().getPtr()) {
5699 completionBytes = completionAllocator->getTotalMemory();
5701 createCXTUResourceUsageEntry(*entries,
5702 CXTUResourceUsage_GlobalCompletionResults,
5705 // How much memory is being used by SourceManager's content cache?
5706 createCXTUResourceUsageEntry(*entries,
5707 CXTUResourceUsage_SourceManagerContentCache,
5708 (unsigned long) astContext.getSourceManager().getContentCacheSize());
5710 // How much memory is being used by the MemoryBuffer's in SourceManager?
5711 const SourceManager::MemoryBufferSizes &srcBufs =
5712 astUnit->getSourceManager().getMemoryBufferSizes();
5714 createCXTUResourceUsageEntry(*entries,
5715 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5716 (unsigned long) srcBufs.malloc_bytes);
5717 createCXTUResourceUsageEntry(*entries,
5718 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5719 (unsigned long) srcBufs.mmap_bytes);
5720 createCXTUResourceUsageEntry(*entries,
5721 CXTUResourceUsage_SourceManager_DataStructures,
5722 (unsigned long) astContext.getSourceManager()
5723 .getDataStructureSizes());
5725 // How much memory is being used by the ExternalASTSource?
5726 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5727 const ExternalASTSource::MemoryBufferSizes &sizes =
5728 esrc->getMemoryBufferSizes();
5730 createCXTUResourceUsageEntry(*entries,
5731 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5732 (unsigned long) sizes.malloc_bytes);
5733 createCXTUResourceUsageEntry(*entries,
5734 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5735 (unsigned long) sizes.mmap_bytes);
5738 // How much memory is being used by the Preprocessor?
5739 Preprocessor &pp = astUnit->getPreprocessor();
5740 createCXTUResourceUsageEntry(*entries,
5741 CXTUResourceUsage_Preprocessor,
5742 pp.getTotalMemory());
5744 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5745 createCXTUResourceUsageEntry(*entries,
5746 CXTUResourceUsage_PreprocessingRecord,
5747 pRec->getTotalMemory());
5750 createCXTUResourceUsageEntry(*entries,
5751 CXTUResourceUsage_Preprocessor_HeaderSearch,
5752 pp.getHeaderSearchInfo().getTotalMemory());
5754 CXTUResourceUsage usage = { (void*) entries.get(),
5755 (unsigned) entries->size(),
5756 entries->size() ? &(*entries)[0] : 0 };
5761 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5763 delete (MemUsageEntries*) usage.data;
5768 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5769 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5770 for (unsigned I = 0; I != Usage.numEntries; ++I)
5771 fprintf(stderr, " %s: %lu\n",
5772 clang_getTUResourceUsageName(Usage.entries[I].kind),
5773 Usage.entries[I].amount);
5775 clang_disposeCXTUResourceUsage(Usage);
5778 //===----------------------------------------------------------------------===//
5779 // Misc. utility functions.
5780 //===----------------------------------------------------------------------===//
5782 /// Default to using an 8 MB stack size on "safety" threads.
5783 static unsigned SafetyStackThreadSize = 8 << 20;
5787 bool RunSafely(llvm::CrashRecoveryContext &CRC,
5788 void (*Fn)(void*), void *UserData,
5791 Size = GetSafetyThreadStackSize();
5793 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5794 return CRC.RunSafely(Fn, UserData);
5797 unsigned GetSafetyThreadStackSize() {
5798 return SafetyStackThreadSize;
5801 void SetSafetyThreadStackSize(unsigned Value) {
5802 SafetyStackThreadSize = Value;
5807 void clang::setThreadBackgroundPriority() {
5808 // FIXME: Move to llvm/Support and make it cross-platform.
5810 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5814 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5818 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5819 DEnd = Unit->stored_diag_end();
5821 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5822 CXString Msg = clang_formatDiagnostic(&Diag,
5823 clang_defaultDiagnosticDisplayOptions());
5824 fprintf(stderr, "%s\n", clang_getCString(Msg));
5825 clang_disposeString(Msg);
5827 #ifdef LLVM_ON_WIN32
5828 // On Windows, force a flush, since there may be multiple copies of
5829 // stderr and stdout in the file system, all with different buffers
5830 // but writing to the same device.
5837 CXString clang_getClangVersion() {
5838 return createCXString(getClangFullVersion());
5841 } // end: extern "C"