CIndex.cpp revision b8dd1cad52be63b18092bd9d9335cbeee3f5de9f
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// The LLVM Compiler Infrastructure 45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source 65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details. 75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===// 95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file implements the main API hooks in the Clang-C Source Indexing 115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// library. 12116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch// 135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===// 145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CIndexer.h" 165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CXCursor.h" 175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CXString.h" 185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CXType.h" 19c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "CXSourceLocation.h" 205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "CIndexDiagnostic.h" 215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Version.h" 235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclVisitor.h" 255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/StmtVisitor.h" 265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/TypeLocVisitor.h" 275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Diagnostic.h" 285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Frontend/ASTUnit.h" 29f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Frontend/CompilerInstance.h" 305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Frontend/FrontendDiagnostic.h" 315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/Lexer.h" 325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/PreprocessingRecord.h" 335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/Preprocessor.h" 345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/STLExtras.h" 355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/Optional.h" 365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Analysis/Support/SaveAndRestore.h" 375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/CrashRecoveryContext.h" 38c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "llvm/Support/PrettyStackTrace.h" 395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/MemoryBuffer.h" 40c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "llvm/Support/raw_ostream.h" 41c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "llvm/Support/Timer.h" 42c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "llvm/System/Mutex.h" 435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/System/Program.h" 445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/System/Signals.h" 45010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/System/Threading.h" 465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/Compiler.h" 475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang; 49f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)using namespace clang::cxcursor; 505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang::cxstring; 515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) { 535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (!TU) 54c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles) return 0; 55f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) CXTranslationUnit D = new CXTranslationUnitImpl(); 565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) D->TUData = TU; 575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) D->StringPool = createCXStringPool(); 585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return D; 59} 60 61/// \brief The result of comparing two source ranges. 62enum RangeComparisonResult { 63 /// \brief Either the ranges overlap or one of the ranges is invalid. 64 RangeOverlap, 65 66 /// \brief The first range ends before the second range starts. 67 RangeBefore, 68 69 /// \brief The first range starts after the second range ends. 70 RangeAfter 71}; 72 73/// \brief Compare two source ranges to determine their relative position in 74/// the translation unit. 75static RangeComparisonResult RangeCompare(SourceManager &SM, 76 SourceRange R1, 77 SourceRange R2) { 78 assert(R1.isValid() && "First range is invalid?"); 79 assert(R2.isValid() && "Second range is invalid?"); 80 if (R1.getEnd() != R2.getBegin() && 81 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 82 return RangeBefore; 83 if (R2.getEnd() != R1.getBegin() && 84 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 85 return RangeAfter; 86 return RangeOverlap; 87} 88 89/// \brief Determine if a source location falls within, before, or after a 90/// a given source range. 91static RangeComparisonResult LocationCompare(SourceManager &SM, 92 SourceLocation L, SourceRange R) { 93 assert(R.isValid() && "First range is invalid?"); 94 assert(L.isValid() && "Second range is invalid?"); 95 if (L == R.getBegin() || L == R.getEnd()) 96 return RangeOverlap; 97 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 98 return RangeBefore; 99 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 100 return RangeAfter; 101 return RangeOverlap; 102} 103 104/// \brief Translate a Clang source range into a CIndex source range. 105/// 106/// Clang internally represents ranges where the end location points to the 107/// start of the token at the end. However, for external clients it is more 108/// useful to have a CXSourceRange be a proper half-open interval. This routine 109/// does the appropriate translation. 110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 111 const LangOptions &LangOpts, 112 const CharSourceRange &R) { 113 // We want the last character in this location, so we will adjust the 114 // location accordingly. 115 SourceLocation EndLoc = R.getEnd(); 116 if (EndLoc.isValid() && EndLoc.isMacroID()) 117 EndLoc = SM.getSpellingLoc(EndLoc); 118 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) { 119 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts); 120 EndLoc = EndLoc.getFileLocWithOffset(Length); 121 } 122 123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, 124 R.getBegin().getRawEncoding(), 125 EndLoc.getRawEncoding() }; 126 return Result; 127} 128 129//===----------------------------------------------------------------------===// 130// Cursor visitor. 131//===----------------------------------------------------------------------===// 132 133namespace { 134 135class VisitorJob { 136public: 137 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind, 138 TypeLocVisitKind, OverloadExprPartsKind, 139 DeclRefExprPartsKind }; 140protected: 141 void *dataA; 142 void *dataB; 143 CXCursor parent; 144 Kind K; 145 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0) 146 : dataA(d1), dataB(d2), parent(C), K(k) {} 147public: 148 Kind getKind() const { return K; } 149 const CXCursor &getParent() const { return parent; } 150 static bool classof(VisitorJob *VJ) { return true; } 151}; 152 153typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList; 154 155// Cursor visitor. 156class CursorVisitor : public DeclVisitor<CursorVisitor, bool>, 157 public TypeLocVisitor<CursorVisitor, bool>, 158 public StmtVisitor<CursorVisitor, bool> 159{ 160 /// \brief The translation unit we are traversing. 161 CXTranslationUnit TU; 162 ASTUnit *AU; 163 164 /// \brief The parent cursor whose children we are traversing. 165 CXCursor Parent; 166 167 /// \brief The declaration that serves at the parent of any statement or 168 /// expression nodes. 169 Decl *StmtParent; 170 171 /// \brief The visitor function. 172 CXCursorVisitor Visitor; 173 174 /// \brief The opaque client data, to be passed along to the visitor. 175 CXClientData ClientData; 176 177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on 178 // to the visitor. Declarations with a PCH level greater than this value will 179 // be suppressed. 180 unsigned MaxPCHLevel; 181 182 /// \brief When valid, a source range to which the cursor should restrict 183 /// its search. 184 SourceRange RegionOfInterest; 185 186 // FIXME: Eventually remove. This part of a hack to support proper 187 // iteration over all Decls contained lexically within an ObjC container. 188 DeclContext::decl_iterator *DI_current; 189 DeclContext::decl_iterator DE_current; 190 191 // Cache of pre-allocated worklists for data-recursion walk of Stmts. 192 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList; 193 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache; 194 195 using DeclVisitor<CursorVisitor, bool>::Visit; 196 using TypeLocVisitor<CursorVisitor, bool>::Visit; 197 using StmtVisitor<CursorVisitor, bool>::Visit; 198 199 /// \brief Determine whether this particular source range comes before, comes 200 /// after, or overlaps the region of interest. 201 /// 202 /// \param R a half-open source range retrieved from the abstract syntax tree. 203 RangeComparisonResult CompareRegionOfInterest(SourceRange R); 204 205 class SetParentRAII { 206 CXCursor &Parent; 207 Decl *&StmtParent; 208 CXCursor OldParent; 209 210 public: 211 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent) 212 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) 213 { 214 Parent = NewParent; 215 if (clang_isDeclaration(Parent.kind)) 216 StmtParent = getCursorDecl(Parent); 217 } 218 219 ~SetParentRAII() { 220 Parent = OldParent; 221 if (clang_isDeclaration(Parent.kind)) 222 StmtParent = getCursorDecl(Parent); 223 } 224 }; 225 226public: 227 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor, 228 CXClientData ClientData, 229 unsigned MaxPCHLevel, 230 SourceRange RegionOfInterest = SourceRange()) 231 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)), 232 Visitor(Visitor), ClientData(ClientData), 233 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest), 234 DI_current(0) 235 { 236 Parent.kind = CXCursor_NoDeclFound; 237 Parent.data[0] = 0; 238 Parent.data[1] = 0; 239 Parent.data[2] = 0; 240 StmtParent = 0; 241 } 242 243 ~CursorVisitor() { 244 // Free the pre-allocated worklists for data-recursion. 245 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator 246 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) { 247 delete *I; 248 } 249 } 250 251 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); } 252 CXTranslationUnit getTU() const { return TU; } 253 254 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); 255 256 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 257 getPreprocessedEntities(); 258 259 bool VisitChildren(CXCursor Parent); 260 261 // Declaration visitors 262 bool VisitAttributes(Decl *D); 263 bool VisitBlockDecl(BlockDecl *B); 264 bool VisitCXXRecordDecl(CXXRecordDecl *D); 265 llvm::Optional<bool> shouldVisitCursor(CXCursor C); 266 bool VisitDeclContext(DeclContext *DC); 267 bool VisitTranslationUnitDecl(TranslationUnitDecl *D); 268 bool VisitTypedefDecl(TypedefDecl *D); 269 bool VisitTagDecl(TagDecl *D); 270 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); 271 bool VisitClassTemplatePartialSpecializationDecl( 272 ClassTemplatePartialSpecializationDecl *D); 273 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 274 bool VisitEnumConstantDecl(EnumConstantDecl *D); 275 bool VisitDeclaratorDecl(DeclaratorDecl *DD); 276 bool VisitFunctionDecl(FunctionDecl *ND); 277 bool VisitFieldDecl(FieldDecl *D); 278 bool VisitVarDecl(VarDecl *); 279 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 280 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 281 bool VisitClassTemplateDecl(ClassTemplateDecl *D); 282 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 283 bool VisitObjCMethodDecl(ObjCMethodDecl *ND); 284 bool VisitObjCContainerDecl(ObjCContainerDecl *D); 285 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); 286 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); 287 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD); 288 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 289 bool VisitObjCImplDecl(ObjCImplDecl *D); 290 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 291 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); 292 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. 293 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D); 294 bool VisitObjCClassDecl(ObjCClassDecl *D); 295 bool VisitLinkageSpecDecl(LinkageSpecDecl *D); 296 bool VisitNamespaceDecl(NamespaceDecl *D); 297 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 298 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 299 bool VisitUsingDecl(UsingDecl *D); 300 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 301 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 302 303 // Name visitor 304 bool VisitDeclarationNameInfo(DeclarationNameInfo Name); 305 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range); 306 307 // Template visitors 308 bool VisitTemplateParameters(const TemplateParameterList *Params); 309 bool VisitTemplateName(TemplateName Name, SourceLocation Loc); 310 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL); 311 312 // Type visitors 313 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL); 314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL); 315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL); 316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL); 317 bool VisitTagTypeLoc(TagTypeLoc TL); 318 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL); 319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL); 320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL); 321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL); 322 bool VisitPointerTypeLoc(PointerTypeLoc TL); 323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL); 324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL); 325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL); 326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL); 327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); 328 bool VisitArrayTypeLoc(ArrayTypeLoc TL); 329 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL); 330 // FIXME: Implement visitors here when the unimplemented TypeLocs get 331 // implemented 332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL); 333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL); 334 335 // Statement visitors 336 bool VisitStmt(Stmt *S); 337 338 // Expression visitors 339 bool VisitOffsetOfExpr(OffsetOfExpr *E); 340 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); 341 bool VisitAddrLabelExpr(AddrLabelExpr *E); 342 bool VisitVAArgExpr(VAArgExpr *E); 343 bool VisitDesignatedInitExpr(DesignatedInitExpr *E); 344 bool VisitCXXUuidofExpr(CXXUuidofExpr *E); 345 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 346 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 347 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); 348 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 349 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 350 351 // Data-recursive visitor functions. 352 bool IsInRegionOfInterest(CXCursor C); 353 bool RunVisitorWorkList(VisitorWorkList &WL); 354 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S); 355 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S); 356}; 357 358} // end anonymous namespace 359 360static SourceRange getRawCursorExtent(CXCursor C); 361 362RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 363 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 364} 365 366/// \brief Visit the given cursor and, if requested by the visitor, 367/// its children. 368/// 369/// \param Cursor the cursor to visit. 370/// 371/// \param CheckRegionOfInterest if true, then the caller already checked that 372/// this cursor is within the region of interest. 373/// 374/// \returns true if the visitation should be aborted, false if it 375/// should continue. 376bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 377 if (clang_isInvalid(Cursor.kind)) 378 return false; 379 380 if (clang_isDeclaration(Cursor.kind)) { 381 Decl *D = getCursorDecl(Cursor); 382 assert(D && "Invalid declaration cursor"); 383 if (D->getPCHLevel() > MaxPCHLevel) 384 return false; 385 386 if (D->isImplicit()) 387 return false; 388 } 389 390 // If we have a range of interest, and this cursor doesn't intersect with it, 391 // we're done. 392 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 393 SourceRange Range = getRawCursorExtent(Cursor); 394 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 395 return false; 396 } 397 398 switch (Visitor(Cursor, Parent, ClientData)) { 399 case CXChildVisit_Break: 400 return true; 401 402 case CXChildVisit_Continue: 403 return false; 404 405 case CXChildVisit_Recurse: 406 return VisitChildren(Cursor); 407 } 408 409 return false; 410} 411 412std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 413CursorVisitor::getPreprocessedEntities() { 414 PreprocessingRecord &PPRec 415 = *AU->getPreprocessor().getPreprocessingRecord(); 416 417 bool OnlyLocalDecls 418 = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 419 420 // There is no region of interest; we have to walk everything. 421 if (RegionOfInterest.isInvalid()) 422 return std::make_pair(PPRec.begin(OnlyLocalDecls), 423 PPRec.end(OnlyLocalDecls)); 424 425 // Find the file in which the region of interest lands. 426 SourceManager &SM = AU->getSourceManager(); 427 std::pair<FileID, unsigned> Begin 428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin()); 429 std::pair<FileID, unsigned> End 430 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd()); 431 432 // The region of interest spans files; we have to walk everything. 433 if (Begin.first != End.first) 434 return std::make_pair(PPRec.begin(OnlyLocalDecls), 435 PPRec.end(OnlyLocalDecls)); 436 437 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap 438 = AU->getPreprocessedEntitiesByFile(); 439 if (ByFileMap.empty()) { 440 // Build the mapping from files to sets of preprocessed entities. 441 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls), 442 EEnd = PPRec.end(OnlyLocalDecls); 443 E != EEnd; ++E) { 444 std::pair<FileID, unsigned> P 445 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin()); 446 ByFileMap[P.first].push_back(*E); 447 } 448 } 449 450 return std::make_pair(ByFileMap[Begin.first].begin(), 451 ByFileMap[Begin.first].end()); 452} 453 454/// \brief Visit the children of the given cursor. 455/// 456/// \returns true if the visitation should be aborted, false if it 457/// should continue. 458bool CursorVisitor::VisitChildren(CXCursor Cursor) { 459 if (clang_isReference(Cursor.kind)) { 460 // By definition, references have no children. 461 return false; 462 } 463 464 // Set the Parent field to Cursor, then back to its old value once we're 465 // done. 466 SetParentRAII SetParent(Parent, StmtParent, Cursor); 467 468 if (clang_isDeclaration(Cursor.kind)) { 469 Decl *D = getCursorDecl(Cursor); 470 assert(D && "Invalid declaration cursor"); 471 return VisitAttributes(D) || Visit(D); 472 } 473 474 if (clang_isStatement(Cursor.kind)) 475 return Visit(getCursorStmt(Cursor)); 476 if (clang_isExpression(Cursor.kind)) 477 return Visit(getCursorExpr(Cursor)); 478 479 if (clang_isTranslationUnit(Cursor.kind)) { 480 CXTranslationUnit tu = getCursorTU(Cursor); 481 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData); 482 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 483 RegionOfInterest.isInvalid()) { 484 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 485 TLEnd = CXXUnit->top_level_end(); 486 TL != TLEnd; ++TL) { 487 if (Visit(MakeCXCursor(*TL, tu), true)) 488 return true; 489 } 490 } else if (VisitDeclContext( 491 CXXUnit->getASTContext().getTranslationUnitDecl())) 492 return true; 493 494 // Walk the preprocessing record. 495 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 496 // FIXME: Once we have the ability to deserialize a preprocessing record, 497 // do so. 498 PreprocessingRecord::iterator E, EEnd; 499 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) { 500 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) { 501 if (Visit(MakeMacroInstantiationCursor(MI, tu))) 502 return true; 503 504 continue; 505 } 506 507 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 508 if (Visit(MakeMacroDefinitionCursor(MD, tu))) 509 return true; 510 511 continue; 512 } 513 514 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 515 if (Visit(MakeInclusionDirectiveCursor(ID, tu))) 516 return true; 517 518 continue; 519 } 520 } 521 } 522 return false; 523 } 524 525 // Nothing to visit at the moment. 526 return false; 527} 528 529bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 530 if (Visit(B->getSignatureAsWritten()->getTypeLoc())) 531 return true; 532 533 if (Stmt *Body = B->getBody()) 534 return Visit(MakeCXCursor(Body, StmtParent, TU)); 535 536 return false; 537} 538 539llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 540 if (RegionOfInterest.isValid()) { 541 SourceRange Range = getRawCursorExtent(Cursor); 542 if (Range.isInvalid()) 543 return llvm::Optional<bool>(); 544 545 switch (CompareRegionOfInterest(Range)) { 546 case RangeBefore: 547 // This declaration comes before the region of interest; skip it. 548 return llvm::Optional<bool>(); 549 550 case RangeAfter: 551 // This declaration comes after the region of interest; we're done. 552 return false; 553 554 case RangeOverlap: 555 // This declaration overlaps the region of interest; visit it. 556 break; 557 } 558 } 559 return true; 560} 561 562bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 563 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 564 565 // FIXME: Eventually remove. This part of a hack to support proper 566 // iteration over all Decls contained lexically within an ObjC container. 567 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 568 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 569 570 for ( ; I != E; ++I) { 571 Decl *D = *I; 572 if (D->getLexicalDeclContext() != DC) 573 continue; 574 CXCursor Cursor = MakeCXCursor(D, TU); 575 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 576 if (!V.hasValue()) 577 continue; 578 if (!V.getValue()) 579 return false; 580 if (Visit(Cursor, true)) 581 return true; 582 } 583 return false; 584} 585 586bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 587 llvm_unreachable("Translation units are visited directly by Visit()"); 588 return false; 589} 590 591bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 593 return Visit(TSInfo->getTypeLoc()); 594 595 return false; 596} 597 598bool CursorVisitor::VisitTagDecl(TagDecl *D) { 599 return VisitDeclContext(D); 600} 601 602bool CursorVisitor::VisitClassTemplateSpecializationDecl( 603 ClassTemplateSpecializationDecl *D) { 604 bool ShouldVisitBody = false; 605 switch (D->getSpecializationKind()) { 606 case TSK_Undeclared: 607 case TSK_ImplicitInstantiation: 608 // Nothing to visit 609 return false; 610 611 case TSK_ExplicitInstantiationDeclaration: 612 case TSK_ExplicitInstantiationDefinition: 613 break; 614 615 case TSK_ExplicitSpecialization: 616 ShouldVisitBody = true; 617 break; 618 } 619 620 // Visit the template arguments used in the specialization. 621 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 622 TypeLoc TL = SpecType->getTypeLoc(); 623 if (TemplateSpecializationTypeLoc *TSTLoc 624 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) { 625 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I) 626 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I))) 627 return true; 628 } 629 } 630 631 if (ShouldVisitBody && VisitCXXRecordDecl(D)) 632 return true; 633 634 return false; 635} 636 637bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 638 ClassTemplatePartialSpecializationDecl *D) { 639 // FIXME: Visit the "outer" template parameter lists on the TagDecl 640 // before visiting these template parameters. 641 if (VisitTemplateParameters(D->getTemplateParameters())) 642 return true; 643 644 // Visit the partial specialization arguments. 645 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten(); 646 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I) 647 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 648 return true; 649 650 return VisitCXXRecordDecl(D); 651} 652 653bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 654 // Visit the default argument. 655 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 656 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 657 if (Visit(DefArg->getTypeLoc())) 658 return true; 659 660 return false; 661} 662 663bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 664 if (Expr *Init = D->getInitExpr()) 665 return Visit(MakeCXCursor(Init, StmtParent, TU)); 666 return false; 667} 668 669bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 670 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 671 if (Visit(TSInfo->getTypeLoc())) 672 return true; 673 674 return false; 675} 676 677/// \brief Compare two base or member initializers based on their source order. 678static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) { 679 CXXBaseOrMemberInitializer const * const *X 680 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp); 681 CXXBaseOrMemberInitializer const * const *Y 682 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp); 683 684 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder()) 685 return -1; 686 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder()) 687 return 1; 688 else 689 return 0; 690} 691 692bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 693 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 694 // Visit the function declaration's syntactic components in the order 695 // written. This requires a bit of work. 696 TypeLoc TL = TSInfo->getTypeLoc(); 697 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL); 698 699 // If we have a function declared directly (without the use of a typedef), 700 // visit just the return type. Otherwise, just visit the function's type 701 // now. 702 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) || 703 (!FTL && Visit(TL))) 704 return true; 705 706 // Visit the nested-name-specifier, if present. 707 if (NestedNameSpecifier *Qualifier = ND->getQualifier()) 708 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange())) 709 return true; 710 711 // Visit the declaration name. 712 if (VisitDeclarationNameInfo(ND->getNameInfo())) 713 return true; 714 715 // FIXME: Visit explicitly-specified template arguments! 716 717 // Visit the function parameters, if we have a function type. 718 if (FTL && VisitFunctionTypeLoc(*FTL, true)) 719 return true; 720 721 // FIXME: Attributes? 722 } 723 724 if (ND->isThisDeclarationADefinition()) { 725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 726 // Find the initializers that were written in the source. 727 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits; 728 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(), 729 IEnd = Constructor->init_end(); 730 I != IEnd; ++I) { 731 if (!(*I)->isWritten()) 732 continue; 733 734 WrittenInits.push_back(*I); 735 } 736 737 // Sort the initializers in source order 738 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 739 &CompareCXXBaseOrMemberInitializers); 740 741 // Visit the initializers in source order 742 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 743 CXXBaseOrMemberInitializer *Init = WrittenInits[I]; 744 if (Init->isMemberInitializer()) { 745 if (Visit(MakeCursorMemberRef(Init->getMember(), 746 Init->getMemberLocation(), TU))) 747 return true; 748 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) { 749 if (Visit(BaseInfo->getTypeLoc())) 750 return true; 751 } 752 753 // Visit the initializer value. 754 if (Expr *Initializer = Init->getInit()) 755 if (Visit(MakeCXCursor(Initializer, ND, TU))) 756 return true; 757 } 758 } 759 760 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) 761 return true; 762 } 763 764 return false; 765} 766 767bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 768 if (VisitDeclaratorDecl(D)) 769 return true; 770 771 if (Expr *BitWidth = D->getBitWidth()) 772 return Visit(MakeCXCursor(BitWidth, StmtParent, TU)); 773 774 return false; 775} 776 777bool CursorVisitor::VisitVarDecl(VarDecl *D) { 778 if (VisitDeclaratorDecl(D)) 779 return true; 780 781 if (Expr *Init = D->getInit()) 782 return Visit(MakeCXCursor(Init, StmtParent, TU)); 783 784 return false; 785} 786 787bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 788 if (VisitDeclaratorDecl(D)) 789 return true; 790 791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 792 if (Expr *DefArg = D->getDefaultArgument()) 793 return Visit(MakeCXCursor(DefArg, StmtParent, TU)); 794 795 return false; 796} 797 798bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 799 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 800 // before visiting these template parameters. 801 if (VisitTemplateParameters(D->getTemplateParameters())) 802 return true; 803 804 return VisitFunctionDecl(D->getTemplatedDecl()); 805} 806 807bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 808 // FIXME: Visit the "outer" template parameter lists on the TagDecl 809 // before visiting these template parameters. 810 if (VisitTemplateParameters(D->getTemplateParameters())) 811 return true; 812 813 return VisitCXXRecordDecl(D->getTemplatedDecl()); 814} 815 816bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 817 if (VisitTemplateParameters(D->getTemplateParameters())) 818 return true; 819 820 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 821 VisitTemplateArgumentLoc(D->getDefaultArgument())) 822 return true; 823 824 return false; 825} 826 827bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 828 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) 829 if (Visit(TSInfo->getTypeLoc())) 830 return true; 831 832 for (ObjCMethodDecl::param_iterator P = ND->param_begin(), 833 PEnd = ND->param_end(); 834 P != PEnd; ++P) { 835 if (Visit(MakeCXCursor(*P, TU))) 836 return true; 837 } 838 839 if (ND->isThisDeclarationADefinition() && 840 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) 841 return true; 842 843 return false; 844} 845 846namespace { 847 struct ContainerDeclsSort { 848 SourceManager &SM; 849 ContainerDeclsSort(SourceManager &sm) : SM(sm) {} 850 bool operator()(Decl *A, Decl *B) { 851 SourceLocation L_A = A->getLocStart(); 852 SourceLocation L_B = B->getLocStart(); 853 assert(L_A.isValid() && L_B.isValid()); 854 return SM.isBeforeInTranslationUnit(L_A, L_B); 855 } 856 }; 857} 858 859bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 860 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 861 // an @implementation can lexically contain Decls that are not properly 862 // nested in the AST. When we identify such cases, we need to retrofit 863 // this nesting here. 864 if (!DI_current) 865 return VisitDeclContext(D); 866 867 // Scan the Decls that immediately come after the container 868 // in the current DeclContext. If any fall within the 869 // container's lexical region, stash them into a vector 870 // for later processing. 871 llvm::SmallVector<Decl *, 24> DeclsInContainer; 872 SourceLocation EndLoc = D->getSourceRange().getEnd(); 873 SourceManager &SM = AU->getSourceManager(); 874 if (EndLoc.isValid()) { 875 DeclContext::decl_iterator next = *DI_current; 876 while (++next != DE_current) { 877 Decl *D_next = *next; 878 if (!D_next) 879 break; 880 SourceLocation L = D_next->getLocStart(); 881 if (!L.isValid()) 882 break; 883 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 884 *DI_current = next; 885 DeclsInContainer.push_back(D_next); 886 continue; 887 } 888 break; 889 } 890 } 891 892 // The common case. 893 if (DeclsInContainer.empty()) 894 return VisitDeclContext(D); 895 896 // Get all the Decls in the DeclContext, and sort them with the 897 // additional ones we've collected. Then visit them. 898 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 899 I!=E; ++I) { 900 Decl *subDecl = *I; 901 if (!subDecl || subDecl->getLexicalDeclContext() != D || 902 subDecl->getLocStart().isInvalid()) 903 continue; 904 DeclsInContainer.push_back(subDecl); 905 } 906 907 // Now sort the Decls so that they appear in lexical order. 908 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), 909 ContainerDeclsSort(SM)); 910 911 // Now visit the decls. 912 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 913 E = DeclsInContainer.end(); I != E; ++I) { 914 CXCursor Cursor = MakeCXCursor(*I, TU); 915 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 916 if (!V.hasValue()) 917 continue; 918 if (!V.getValue()) 919 return false; 920 if (Visit(Cursor, true)) 921 return true; 922 } 923 return false; 924} 925 926bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 927 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 928 TU))) 929 return true; 930 931 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 932 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 933 E = ND->protocol_end(); I != E; ++I, ++PL) 934 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 935 return true; 936 937 return VisitObjCContainerDecl(ND); 938} 939 940bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 941 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 942 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 943 E = PID->protocol_end(); I != E; ++I, ++PL) 944 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 945 return true; 946 947 return VisitObjCContainerDecl(PID); 948} 949 950bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 951 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 952 return true; 953 954 // FIXME: This implements a workaround with @property declarations also being 955 // installed in the DeclContext for the @interface. Eventually this code 956 // should be removed. 957 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 958 if (!CDecl || !CDecl->IsClassExtension()) 959 return false; 960 961 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 962 if (!ID) 963 return false; 964 965 IdentifierInfo *PropertyId = PD->getIdentifier(); 966 ObjCPropertyDecl *prevDecl = 967 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId); 968 969 if (!prevDecl) 970 return false; 971 972 // Visit synthesized methods since they will be skipped when visiting 973 // the @interface. 974 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 975 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl) 976 if (Visit(MakeCXCursor(MD, TU))) 977 return true; 978 979 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 980 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl) 981 if (Visit(MakeCXCursor(MD, TU))) 982 return true; 983 984 return false; 985} 986 987bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 988 // Issue callbacks for super class. 989 if (D->getSuperClass() && 990 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 991 D->getSuperClassLoc(), 992 TU))) 993 return true; 994 995 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 996 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 997 E = D->protocol_end(); I != E; ++I, ++PL) 998 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 999 return true; 1000 1001 return VisitObjCContainerDecl(D); 1002} 1003 1004bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1005 return VisitObjCContainerDecl(D); 1006} 1007 1008bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1009 // 'ID' could be null when dealing with invalid code. 1010 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1011 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1012 return true; 1013 1014 return VisitObjCImplDecl(D); 1015} 1016 1017bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1018#if 0 1019 // Issue callbacks for super class. 1020 // FIXME: No source location information! 1021 if (D->getSuperClass() && 1022 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1023 D->getSuperClassLoc(), 1024 TU))) 1025 return true; 1026#endif 1027 1028 return VisitObjCImplDecl(D); 1029} 1030 1031bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { 1032 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1033 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), 1034 E = D->protocol_end(); 1035 I != E; ++I, ++PL) 1036 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1037 return true; 1038 1039 return false; 1040} 1041 1042bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) { 1043 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C) 1044 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU))) 1045 return true; 1046 1047 return false; 1048} 1049 1050bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1051 return VisitDeclContext(D); 1052} 1053 1054bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1055 // Visit nested-name-specifier. 1056 if (NestedNameSpecifier *Qualifier = D->getQualifier()) 1057 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange())) 1058 return true; 1059 1060 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1061 D->getTargetNameLoc(), TU)); 1062} 1063 1064bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1065 // Visit nested-name-specifier. 1066 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl()) 1067 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange())) 1068 return true; 1069 1070 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1071 return true; 1072 1073 return VisitDeclarationNameInfo(D->getNameInfo()); 1074} 1075 1076bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1077 // Visit nested-name-specifier. 1078 if (NestedNameSpecifier *Qualifier = D->getQualifier()) 1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange())) 1080 return true; 1081 1082 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1083 D->getIdentLocation(), TU)); 1084} 1085 1086bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1087 // Visit nested-name-specifier. 1088 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1089 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1090 return true; 1091 1092 return VisitDeclarationNameInfo(D->getNameInfo()); 1093} 1094 1095bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1096 UnresolvedUsingTypenameDecl *D) { 1097 // Visit nested-name-specifier. 1098 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1099 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1100 return true; 1101 1102 return false; 1103} 1104 1105bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1106 switch (Name.getName().getNameKind()) { 1107 case clang::DeclarationName::Identifier: 1108 case clang::DeclarationName::CXXLiteralOperatorName: 1109 case clang::DeclarationName::CXXOperatorName: 1110 case clang::DeclarationName::CXXUsingDirective: 1111 return false; 1112 1113 case clang::DeclarationName::CXXConstructorName: 1114 case clang::DeclarationName::CXXDestructorName: 1115 case clang::DeclarationName::CXXConversionFunctionName: 1116 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1117 return Visit(TSInfo->getTypeLoc()); 1118 return false; 1119 1120 case clang::DeclarationName::ObjCZeroArgSelector: 1121 case clang::DeclarationName::ObjCOneArgSelector: 1122 case clang::DeclarationName::ObjCMultiArgSelector: 1123 // FIXME: Per-identifier location info? 1124 return false; 1125 } 1126 1127 return false; 1128} 1129 1130bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1131 SourceRange Range) { 1132 // FIXME: This whole routine is a hack to work around the lack of proper 1133 // source information in nested-name-specifiers (PR5791). Since we do have 1134 // a beginning source location, we can visit the first component of the 1135 // nested-name-specifier, if it's a single-token component. 1136 if (!NNS) 1137 return false; 1138 1139 // Get the first component in the nested-name-specifier. 1140 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1141 NNS = Prefix; 1142 1143 switch (NNS->getKind()) { 1144 case NestedNameSpecifier::Namespace: 1145 // FIXME: The token at this source location might actually have been a 1146 // namespace alias, but we don't model that. Lame! 1147 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1148 TU)); 1149 1150 case NestedNameSpecifier::TypeSpec: { 1151 // If the type has a form where we know that the beginning of the source 1152 // range matches up with a reference cursor. Visit the appropriate reference 1153 // cursor. 1154 Type *T = NNS->getAsType(); 1155 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1156 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1157 if (const TagType *Tag = dyn_cast<TagType>(T)) 1158 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1159 if (const TemplateSpecializationType *TST 1160 = dyn_cast<TemplateSpecializationType>(T)) 1161 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1162 break; 1163 } 1164 1165 case NestedNameSpecifier::TypeSpecWithTemplate: 1166 case NestedNameSpecifier::Global: 1167 case NestedNameSpecifier::Identifier: 1168 break; 1169 } 1170 1171 return false; 1172} 1173 1174bool CursorVisitor::VisitTemplateParameters( 1175 const TemplateParameterList *Params) { 1176 if (!Params) 1177 return false; 1178 1179 for (TemplateParameterList::const_iterator P = Params->begin(), 1180 PEnd = Params->end(); 1181 P != PEnd; ++P) { 1182 if (Visit(MakeCXCursor(*P, TU))) 1183 return true; 1184 } 1185 1186 return false; 1187} 1188 1189bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1190 switch (Name.getKind()) { 1191 case TemplateName::Template: 1192 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1193 1194 case TemplateName::OverloadedTemplate: 1195 // Visit the overloaded template set. 1196 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1197 return true; 1198 1199 return false; 1200 1201 case TemplateName::DependentTemplate: 1202 // FIXME: Visit nested-name-specifier. 1203 return false; 1204 1205 case TemplateName::QualifiedTemplate: 1206 // FIXME: Visit nested-name-specifier. 1207 return Visit(MakeCursorTemplateRef( 1208 Name.getAsQualifiedTemplateName()->getDecl(), 1209 Loc, TU)); 1210 } 1211 1212 return false; 1213} 1214 1215bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1216 switch (TAL.getArgument().getKind()) { 1217 case TemplateArgument::Null: 1218 case TemplateArgument::Integral: 1219 return false; 1220 1221 case TemplateArgument::Pack: 1222 // FIXME: Implement when variadic templates come along. 1223 return false; 1224 1225 case TemplateArgument::Type: 1226 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1227 return Visit(TSInfo->getTypeLoc()); 1228 return false; 1229 1230 case TemplateArgument::Declaration: 1231 if (Expr *E = TAL.getSourceDeclExpression()) 1232 return Visit(MakeCXCursor(E, StmtParent, TU)); 1233 return false; 1234 1235 case TemplateArgument::Expression: 1236 if (Expr *E = TAL.getSourceExpression()) 1237 return Visit(MakeCXCursor(E, StmtParent, TU)); 1238 return false; 1239 1240 case TemplateArgument::Template: 1241 return VisitTemplateName(TAL.getArgument().getAsTemplate(), 1242 TAL.getTemplateNameLoc()); 1243 } 1244 1245 return false; 1246} 1247 1248bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1249 return VisitDeclContext(D); 1250} 1251 1252bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1253 return Visit(TL.getUnqualifiedLoc()); 1254} 1255 1256bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1257 ASTContext &Context = AU->getASTContext(); 1258 1259 // Some builtin types (such as Objective-C's "id", "sel", and 1260 // "Class") have associated declarations. Create cursors for those. 1261 QualType VisitType; 1262 switch (TL.getType()->getAs<BuiltinType>()->getKind()) { 1263 case BuiltinType::Void: 1264 case BuiltinType::Bool: 1265 case BuiltinType::Char_U: 1266 case BuiltinType::UChar: 1267 case BuiltinType::Char16: 1268 case BuiltinType::Char32: 1269 case BuiltinType::UShort: 1270 case BuiltinType::UInt: 1271 case BuiltinType::ULong: 1272 case BuiltinType::ULongLong: 1273 case BuiltinType::UInt128: 1274 case BuiltinType::Char_S: 1275 case BuiltinType::SChar: 1276 case BuiltinType::WChar: 1277 case BuiltinType::Short: 1278 case BuiltinType::Int: 1279 case BuiltinType::Long: 1280 case BuiltinType::LongLong: 1281 case BuiltinType::Int128: 1282 case BuiltinType::Float: 1283 case BuiltinType::Double: 1284 case BuiltinType::LongDouble: 1285 case BuiltinType::NullPtr: 1286 case BuiltinType::Overload: 1287 case BuiltinType::Dependent: 1288 break; 1289 1290 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor? 1291 break; 1292 1293 case BuiltinType::ObjCId: 1294 VisitType = Context.getObjCIdType(); 1295 break; 1296 1297 case BuiltinType::ObjCClass: 1298 VisitType = Context.getObjCClassType(); 1299 break; 1300 1301 case BuiltinType::ObjCSel: 1302 VisitType = Context.getObjCSelType(); 1303 break; 1304 } 1305 1306 if (!VisitType.isNull()) { 1307 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1308 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1309 TU)); 1310 } 1311 1312 return false; 1313} 1314 1315bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1316 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); 1317} 1318 1319bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1320 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1321} 1322 1323bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1325} 1326 1327bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1328 // FIXME: We can't visit the template type parameter, because there's 1329 // no context information with which we can match up the depth/index in the 1330 // type to the appropriate 1331 return false; 1332} 1333 1334bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1335 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1336 return true; 1337 1338 return false; 1339} 1340 1341bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1342 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1343 return true; 1344 1345 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1346 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1347 TU))) 1348 return true; 1349 } 1350 1351 return false; 1352} 1353 1354bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1355 return Visit(TL.getPointeeLoc()); 1356} 1357 1358bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1359 return Visit(TL.getPointeeLoc()); 1360} 1361 1362bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1363 return Visit(TL.getPointeeLoc()); 1364} 1365 1366bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1367 return Visit(TL.getPointeeLoc()); 1368} 1369 1370bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1371 return Visit(TL.getPointeeLoc()); 1372} 1373 1374bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1375 return Visit(TL.getPointeeLoc()); 1376} 1377 1378bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1379 bool SkipResultType) { 1380 if (!SkipResultType && Visit(TL.getResultLoc())) 1381 return true; 1382 1383 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1384 if (Decl *D = TL.getArg(I)) 1385 if (Visit(MakeCXCursor(D, TU))) 1386 return true; 1387 1388 return false; 1389} 1390 1391bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1392 if (Visit(TL.getElementLoc())) 1393 return true; 1394 1395 if (Expr *Size = TL.getSizeExpr()) 1396 return Visit(MakeCXCursor(Size, StmtParent, TU)); 1397 1398 return false; 1399} 1400 1401bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1402 TemplateSpecializationTypeLoc TL) { 1403 // Visit the template name. 1404 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1405 TL.getTemplateNameLoc())) 1406 return true; 1407 1408 // Visit the template arguments. 1409 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1410 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1411 return true; 1412 1413 return false; 1414} 1415 1416bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1417 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1418} 1419 1420bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1421 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1422 return Visit(TSInfo->getTypeLoc()); 1423 1424 return false; 1425} 1426 1427bool CursorVisitor::VisitStmt(Stmt *S) { 1428 return VisitDataRecursive(S); 1429} 1430 1431bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1432 if (D->isDefinition()) { 1433 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1434 E = D->bases_end(); I != E; ++I) { 1435 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1436 return true; 1437 } 1438 } 1439 1440 return VisitTagDecl(D); 1441} 1442 1443bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 1444 // Visit the type into which we're computing an offset. 1445 if (Visit(E->getTypeSourceInfo()->getTypeLoc())) 1446 return true; 1447 1448 // Visit the components of the offsetof expression. 1449 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) { 1450 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 1451 const OffsetOfNode &Node = E->getComponent(I); 1452 switch (Node.getKind()) { 1453 case OffsetOfNode::Array: 1454 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()), 1455 StmtParent, TU))) 1456 return true; 1457 break; 1458 1459 case OffsetOfNode::Field: 1460 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(), 1461 TU))) 1462 return true; 1463 break; 1464 1465 case OffsetOfNode::Identifier: 1466 case OffsetOfNode::Base: 1467 continue; 1468 } 1469 } 1470 1471 return false; 1472} 1473 1474bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { 1475 if (E->isArgumentType()) { 1476 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo()) 1477 return Visit(TSInfo->getTypeLoc()); 1478 1479 return false; 1480 } 1481 1482 return VisitExpr(E); 1483} 1484 1485bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1486 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU)); 1487} 1488 1489bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) { 1490 if (Visit(E->getWrittenTypeInfo()->getTypeLoc())) 1491 return true; 1492 1493 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU)); 1494} 1495 1496bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1497 // Visit the designators. 1498 typedef DesignatedInitExpr::Designator Designator; 1499 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(), 1500 DEnd = E->designators_end(); 1501 D != DEnd; ++D) { 1502 if (D->isFieldDesignator()) { 1503 if (FieldDecl *Field = D->getField()) 1504 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU))) 1505 return true; 1506 1507 continue; 1508 } 1509 1510 if (D->isArrayDesignator()) { 1511 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU))) 1512 return true; 1513 1514 continue; 1515 } 1516 1517 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 1518 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) || 1519 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU))) 1520 return true; 1521 } 1522 1523 // Visit the initializer value itself. 1524 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU)); 1525} 1526 1527bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1528 if (E->isTypeOperand()) { 1529 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo()) 1530 return Visit(TSInfo->getTypeLoc()); 1531 1532 return false; 1533 } 1534 1535 return VisitExpr(E); 1536} 1537 1538bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1539 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1540 return Visit(TSInfo->getTypeLoc()); 1541 1542 return false; 1543} 1544 1545bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1546 // Visit base expression. 1547 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1548 return true; 1549 1550 // Visit the nested-name-specifier. 1551 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1552 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1553 return true; 1554 1555 // Visit the scope type that looks disturbingly like the nested-name-specifier 1556 // but isn't. 1557 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo()) 1558 if (Visit(TSInfo->getTypeLoc())) 1559 return true; 1560 1561 // Visit the name of the type being destroyed. 1562 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo()) 1563 if (Visit(TSInfo->getTypeLoc())) 1564 return true; 1565 1566 return false; 1567} 1568 1569bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 1570 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc()); 1571} 1572 1573bool CursorVisitor::VisitDependentScopeDeclRefExpr( 1574 DependentScopeDeclRefExpr *E) { 1575 // Visit the nested-name-specifier. 1576 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1577 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1578 return true; 1579 1580 // Visit the declaration name. 1581 if (VisitDeclarationNameInfo(E->getNameInfo())) 1582 return true; 1583 1584 // Visit the explicitly-specified template arguments. 1585 if (const ExplicitTemplateArgumentList *ArgList 1586 = E->getOptionalExplicitTemplateArgs()) { 1587 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1588 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1589 Arg != ArgEnd; ++Arg) { 1590 if (VisitTemplateArgumentLoc(*Arg)) 1591 return true; 1592 } 1593 } 1594 1595 return false; 1596} 1597 1598bool CursorVisitor::VisitCXXDependentScopeMemberExpr( 1599 CXXDependentScopeMemberExpr *E) { 1600 // Visit the base expression, if there is one. 1601 if (!E->isImplicitAccess() && 1602 Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1603 return true; 1604 1605 // Visit the nested-name-specifier. 1606 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1607 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1608 return true; 1609 1610 // Visit the declaration name. 1611 if (VisitDeclarationNameInfo(E->getMemberNameInfo())) 1612 return true; 1613 1614 // Visit the explicitly-specified template arguments. 1615 if (const ExplicitTemplateArgumentList *ArgList 1616 = E->getOptionalExplicitTemplateArgs()) { 1617 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1618 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1619 Arg != ArgEnd; ++Arg) { 1620 if (VisitTemplateArgumentLoc(*Arg)) 1621 return true; 1622 } 1623 } 1624 1625 return false; 1626} 1627 1628bool CursorVisitor::VisitAttributes(Decl *D) { 1629 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1630 i != e; ++i) 1631 if (Visit(MakeCXCursor(*i, D, TU))) 1632 return true; 1633 1634 return false; 1635} 1636 1637//===----------------------------------------------------------------------===// 1638// Data-recursive visitor methods. 1639//===----------------------------------------------------------------------===// 1640 1641namespace { 1642#define DEF_JOB(NAME, DATA, KIND)\ 1643class NAME : public VisitorJob {\ 1644public:\ 1645 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1646 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1647 DATA *get() const { return static_cast<DATA*>(dataA); }\ 1648}; 1649 1650DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1651DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1652DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1653DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1654#undef DEF_JOB 1655 1656class DeclVisit : public VisitorJob { 1657public: 1658 DeclVisit(Decl *d, CXCursor parent, bool isFirst) : 1659 VisitorJob(parent, VisitorJob::DeclVisitKind, 1660 d, isFirst ? (void*) 1 : (void*) 0) {} 1661 static bool classof(const VisitorJob *VJ) { 1662 return VJ->getKind() == DeclVisitKind; 1663 } 1664 Decl *get() const { return static_cast<Decl*>(dataA); } 1665 bool isFirst() const { return dataB ? true : false; } 1666}; 1667 1668class TypeLocVisit : public VisitorJob { 1669public: 1670 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1671 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1672 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1673 1674 static bool classof(const VisitorJob *VJ) { 1675 return VJ->getKind() == TypeLocVisitKind; 1676 } 1677 1678 TypeLoc get() const { 1679 QualType T = QualType::getFromOpaquePtr(dataA); 1680 return TypeLoc(T, dataB); 1681 } 1682}; 1683 1684class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> { 1685 VisitorWorkList &WL; 1686 CXCursor Parent; 1687public: 1688 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1689 : WL(wl), Parent(parent) {} 1690 1691 void VisitBlockExpr(BlockExpr *B); 1692 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1693 void VisitCompoundStmt(CompoundStmt *S); 1694 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ } 1695 void VisitCXXNewExpr(CXXNewExpr *E); 1696 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 1697 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 1698 void VisitCXXTypeidExpr(CXXTypeidExpr *E); 1699 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 1700 void VisitDeclRefExpr(DeclRefExpr *D); 1701 void VisitDeclStmt(DeclStmt *S); 1702 void VisitExplicitCastExpr(ExplicitCastExpr *E); 1703 void VisitForStmt(ForStmt *FS); 1704 void VisitIfStmt(IfStmt *If); 1705 void VisitInitListExpr(InitListExpr *IE); 1706 void VisitMemberExpr(MemberExpr *M); 1707 void VisitObjCEncodeExpr(ObjCEncodeExpr *E); 1708 void VisitObjCMessageExpr(ObjCMessageExpr *M); 1709 void VisitOverloadExpr(OverloadExpr *E); 1710 void VisitStmt(Stmt *S); 1711 void VisitSwitchStmt(SwitchStmt *S); 1712 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E); 1713 void VisitWhileStmt(WhileStmt *W); 1714 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U); 1715 1716private: 1717 void AddStmt(Stmt *S); 1718 void AddDecl(Decl *D, bool isFirst = true); 1719 void AddTypeLoc(TypeSourceInfo *TI); 1720 void EnqueueChildren(Stmt *S); 1721}; 1722} // end anonyous namespace 1723 1724void EnqueueVisitor::AddStmt(Stmt *S) { 1725 if (S) 1726 WL.push_back(StmtVisit(S, Parent)); 1727} 1728void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) { 1729 if (D) 1730 WL.push_back(DeclVisit(D, Parent, isFirst)); 1731} 1732void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 1733 if (TI) 1734 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 1735 } 1736void EnqueueVisitor::EnqueueChildren(Stmt *S) { 1737 unsigned size = WL.size(); 1738 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end(); 1739 Child != ChildEnd; ++Child) { 1740 AddStmt(*Child); 1741 } 1742 if (size == WL.size()) 1743 return; 1744 // Now reverse the entries we just added. This will match the DFS 1745 // ordering performed by the worklist. 1746 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1747 std::reverse(I, E); 1748} 1749void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) { 1750 AddDecl(B->getBlockDecl()); 1751} 1752void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1753 EnqueueChildren(E); 1754 AddTypeLoc(E->getTypeSourceInfo()); 1755} 1756void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) { 1757 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(), 1758 E = S->body_rend(); I != E; ++I) { 1759 AddStmt(*I); 1760 } 1761} 1762void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1763 // Enqueue the initializer or constructor arguments. 1764 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I) 1765 AddStmt(E->getConstructorArg(I-1)); 1766 // Enqueue the array size, if any. 1767 AddStmt(E->getArraySize()); 1768 // Enqueue the allocated type. 1769 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 1770 // Enqueue the placement arguments. 1771 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 1772 AddStmt(E->getPlacementArg(I-1)); 1773} 1774void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { 1775 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 1776 AddStmt(CE->getArg(I-1)); 1777 AddStmt(CE->getCallee()); 1778 AddStmt(CE->getArg(0)); 1779} 1780void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1781 EnqueueChildren(E); 1782 AddTypeLoc(E->getTypeSourceInfo()); 1783} 1784void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1785 EnqueueChildren(E); 1786 if (E->isTypeOperand()) 1787 AddTypeLoc(E->getTypeOperandSourceInfo()); 1788} 1789 1790void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr 1791 *E) { 1792 EnqueueChildren(E); 1793 AddTypeLoc(E->getTypeSourceInfo()); 1794} 1795void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) { 1796 WL.push_back(DeclRefExprParts(DR, Parent)); 1797} 1798void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) { 1799 unsigned size = WL.size(); 1800 bool isFirst = true; 1801 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1802 D != DEnd; ++D) { 1803 AddDecl(*D, isFirst); 1804 isFirst = false; 1805 } 1806 if (size == WL.size()) 1807 return; 1808 // Now reverse the entries we just added. This will match the DFS 1809 // ordering performed by the worklist. 1810 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1811 std::reverse(I, E); 1812} 1813void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 1814 EnqueueChildren(E); 1815 AddTypeLoc(E->getTypeInfoAsWritten()); 1816} 1817void EnqueueVisitor::VisitForStmt(ForStmt *FS) { 1818 AddStmt(FS->getBody()); 1819 AddStmt(FS->getInc()); 1820 AddStmt(FS->getCond()); 1821 AddDecl(FS->getConditionVariable()); 1822 AddStmt(FS->getInit()); 1823} 1824void EnqueueVisitor::VisitIfStmt(IfStmt *If) { 1825 AddStmt(If->getElse()); 1826 AddStmt(If->getThen()); 1827 AddStmt(If->getCond()); 1828 AddDecl(If->getConditionVariable()); 1829} 1830void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) { 1831 // We care about the syntactic form of the initializer list, only. 1832 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 1833 IE = Syntactic; 1834 EnqueueChildren(IE); 1835} 1836void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) { 1837 WL.push_back(MemberExprParts(M, Parent)); 1838 AddStmt(M->getBase()); 1839} 1840void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 1841 AddTypeLoc(E->getEncodedTypeSourceInfo()); 1842} 1843void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) { 1844 EnqueueChildren(M); 1845 AddTypeLoc(M->getClassReceiverTypeInfo()); 1846} 1847void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) { 1848 WL.push_back(OverloadExprParts(E, Parent)); 1849} 1850void EnqueueVisitor::VisitStmt(Stmt *S) { 1851 EnqueueChildren(S); 1852} 1853void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) { 1854 AddStmt(S->getBody()); 1855 AddStmt(S->getCond()); 1856 AddDecl(S->getConditionVariable()); 1857} 1858void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) { 1859 AddTypeLoc(E->getArgTInfo2()); 1860 AddTypeLoc(E->getArgTInfo1()); 1861} 1862 1863void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) { 1864 AddStmt(W->getBody()); 1865 AddStmt(W->getCond()); 1866 AddDecl(W->getConditionVariable()); 1867} 1868void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) { 1869 VisitOverloadExpr(U); 1870 if (!U->isImplicitAccess()) 1871 AddStmt(U->getBase()); 1872} 1873 1874void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) { 1875 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S); 1876} 1877 1878bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 1879 if (RegionOfInterest.isValid()) { 1880 SourceRange Range = getRawCursorExtent(C); 1881 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 1882 return false; 1883 } 1884 return true; 1885} 1886 1887bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 1888 while (!WL.empty()) { 1889 // Dequeue the worklist item. 1890 VisitorJob LI = WL.back(); 1891 WL.pop_back(); 1892 1893 // Set the Parent field, then back to its old value once we're done. 1894 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 1895 1896 switch (LI.getKind()) { 1897 case VisitorJob::DeclVisitKind: { 1898 Decl *D = cast<DeclVisit>(&LI)->get(); 1899 if (!D) 1900 continue; 1901 1902 // For now, perform default visitation for Decls. 1903 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst()))) 1904 return true; 1905 1906 continue; 1907 } 1908 case VisitorJob::TypeLocVisitKind: { 1909 // Perform default visitation for TypeLocs. 1910 if (Visit(cast<TypeLocVisit>(&LI)->get())) 1911 return true; 1912 continue; 1913 } 1914 case VisitorJob::StmtVisitKind: { 1915 Stmt *S = cast<StmtVisit>(&LI)->get(); 1916 if (!S) 1917 continue; 1918 1919 // Update the current cursor. 1920 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU); 1921 1922 switch (S->getStmtClass()) { 1923 case Stmt::GotoStmtClass: { 1924 GotoStmt *GS = cast<GotoStmt>(S); 1925 if (Visit(MakeCursorLabelRef(GS->getLabel(), 1926 GS->getLabelLoc(), TU))) { 1927 return true; 1928 } 1929 continue; 1930 } 1931 // Cases not yet handled by the data-recursion 1932 // algorithm. 1933 case Stmt::OffsetOfExprClass: 1934 case Stmt::SizeOfAlignOfExprClass: 1935 case Stmt::AddrLabelExprClass: 1936 case Stmt::TypesCompatibleExprClass: 1937 case Stmt::VAArgExprClass: 1938 case Stmt::DesignatedInitExprClass: 1939 case Stmt::CXXTypeidExprClass: 1940 case Stmt::CXXUuidofExprClass: 1941 case Stmt::CXXScalarValueInitExprClass: 1942 case Stmt::CXXPseudoDestructorExprClass: 1943 case Stmt::UnaryTypeTraitExprClass: 1944 case Stmt::DependentScopeDeclRefExprClass: 1945 case Stmt::CXXUnresolvedConstructExprClass: 1946 case Stmt::CXXDependentScopeMemberExprClass: 1947 if (Visit(Cursor)) 1948 return true; 1949 break; 1950 default: 1951 if (!IsInRegionOfInterest(Cursor)) 1952 continue; 1953 switch (Visitor(Cursor, Parent, ClientData)) { 1954 case CXChildVisit_Break: 1955 return true; 1956 case CXChildVisit_Continue: 1957 break; 1958 case CXChildVisit_Recurse: 1959 EnqueueWorkList(WL, S); 1960 break; 1961 } 1962 break; 1963 } 1964 continue; 1965 } 1966 case VisitorJob::MemberExprPartsKind: { 1967 // Handle the other pieces in the MemberExpr besides the base. 1968 MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 1969 1970 // Visit the nested-name-specifier 1971 if (NestedNameSpecifier *Qualifier = M->getQualifier()) 1972 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange())) 1973 return true; 1974 1975 // Visit the declaration name. 1976 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 1977 return true; 1978 1979 // Visit the explicitly-specified template arguments, if any. 1980 if (M->hasExplicitTemplateArgs()) { 1981 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 1982 *ArgEnd = Arg + M->getNumTemplateArgs(); 1983 Arg != ArgEnd; ++Arg) { 1984 if (VisitTemplateArgumentLoc(*Arg)) 1985 return true; 1986 } 1987 } 1988 continue; 1989 } 1990 case VisitorJob::DeclRefExprPartsKind: { 1991 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 1992 // Visit nested-name-specifier, if present. 1993 if (NestedNameSpecifier *Qualifier = DR->getQualifier()) 1994 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange())) 1995 return true; 1996 // Visit declaration name. 1997 if (VisitDeclarationNameInfo(DR->getNameInfo())) 1998 return true; 1999 // Visit explicitly-specified template arguments. 2000 if (DR->hasExplicitTemplateArgs()) { 2001 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs(); 2002 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(), 2003 *ArgEnd = Arg + Args.NumTemplateArgs; 2004 Arg != ArgEnd; ++Arg) 2005 if (VisitTemplateArgumentLoc(*Arg)) 2006 return true; 2007 } 2008 continue; 2009 } 2010 case VisitorJob::OverloadExprPartsKind: { 2011 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 2012 // Visit the nested-name-specifier. 2013 if (NestedNameSpecifier *Qualifier = O->getQualifier()) 2014 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange())) 2015 return true; 2016 // Visit the declaration name. 2017 if (VisitDeclarationNameInfo(O->getNameInfo())) 2018 return true; 2019 // Visit the overloaded declaration reference. 2020 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 2021 return true; 2022 // Visit the explicitly-specified template arguments. 2023 if (const ExplicitTemplateArgumentList *ArgList 2024 = O->getOptionalExplicitTemplateArgs()) { 2025 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 2026 *ArgEnd = Arg + ArgList->NumTemplateArgs; 2027 Arg != ArgEnd; ++Arg) { 2028 if (VisitTemplateArgumentLoc(*Arg)) 2029 return true; 2030 } 2031 } 2032 continue; 2033 } 2034 } 2035 } 2036 return false; 2037} 2038 2039bool CursorVisitor::VisitDataRecursive(Stmt *S) { 2040 VisitorWorkList *WL = 0; 2041 if (!WorkListFreeList.empty()) { 2042 WL = WorkListFreeList.back(); 2043 WL->clear(); 2044 WorkListFreeList.pop_back(); 2045 } 2046 else { 2047 WL = new VisitorWorkList(); 2048 WorkListCache.push_back(WL); 2049 } 2050 EnqueueWorkList(*WL, S); 2051 bool result = RunVisitorWorkList(*WL); 2052 WorkListFreeList.push_back(WL); 2053 return result; 2054} 2055 2056//===----------------------------------------------------------------------===// 2057// Misc. API hooks. 2058//===----------------------------------------------------------------------===// 2059 2060static llvm::sys::Mutex EnableMultithreadingMutex; 2061static bool EnabledMultithreading; 2062 2063extern "C" { 2064CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 2065 int displayDiagnostics) { 2066 // Disable pretty stack trace functionality, which will otherwise be a very 2067 // poor citizen of the world and set up all sorts of signal handlers. 2068 llvm::DisablePrettyStackTrace = true; 2069 2070 // We use crash recovery to make some of our APIs more reliable, implicitly 2071 // enable it. 2072 llvm::CrashRecoveryContext::Enable(); 2073 2074 // Enable support for multithreading in LLVM. 2075 { 2076 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 2077 if (!EnabledMultithreading) { 2078 llvm::llvm_start_multithreaded(); 2079 EnabledMultithreading = true; 2080 } 2081 } 2082 2083 CIndexer *CIdxr = new CIndexer(); 2084 if (excludeDeclarationsFromPCH) 2085 CIdxr->setOnlyLocalDecls(); 2086 if (displayDiagnostics) 2087 CIdxr->setDisplayDiagnostics(); 2088 return CIdxr; 2089} 2090 2091void clang_disposeIndex(CXIndex CIdx) { 2092 if (CIdx) 2093 delete static_cast<CIndexer *>(CIdx); 2094} 2095 2096CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 2097 const char *ast_filename) { 2098 if (!CIdx) 2099 return 0; 2100 2101 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2102 FileSystemOptions FileSystemOpts; 2103 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory(); 2104 2105 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2106 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts, 2107 CXXIdx->getOnlyLocalDecls(), 2108 0, 0, true); 2109 return MakeCXTranslationUnit(TU); 2110} 2111 2112unsigned clang_defaultEditingTranslationUnitOptions() { 2113 return CXTranslationUnit_PrecompiledPreamble | 2114 CXTranslationUnit_CacheCompletionResults | 2115 CXTranslationUnit_CXXPrecompiledPreamble; 2116} 2117 2118CXTranslationUnit 2119clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 2120 const char *source_filename, 2121 int num_command_line_args, 2122 const char * const *command_line_args, 2123 unsigned num_unsaved_files, 2124 struct CXUnsavedFile *unsaved_files) { 2125 return clang_parseTranslationUnit(CIdx, source_filename, 2126 command_line_args, num_command_line_args, 2127 unsaved_files, num_unsaved_files, 2128 CXTranslationUnit_DetailedPreprocessingRecord); 2129} 2130 2131struct ParseTranslationUnitInfo { 2132 CXIndex CIdx; 2133 const char *source_filename; 2134 const char *const *command_line_args; 2135 int num_command_line_args; 2136 struct CXUnsavedFile *unsaved_files; 2137 unsigned num_unsaved_files; 2138 unsigned options; 2139 CXTranslationUnit result; 2140}; 2141static void clang_parseTranslationUnit_Impl(void *UserData) { 2142 ParseTranslationUnitInfo *PTUI = 2143 static_cast<ParseTranslationUnitInfo*>(UserData); 2144 CXIndex CIdx = PTUI->CIdx; 2145 const char *source_filename = PTUI->source_filename; 2146 const char * const *command_line_args = PTUI->command_line_args; 2147 int num_command_line_args = PTUI->num_command_line_args; 2148 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 2149 unsigned num_unsaved_files = PTUI->num_unsaved_files; 2150 unsigned options = PTUI->options; 2151 PTUI->result = 0; 2152 2153 if (!CIdx) 2154 return; 2155 2156 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2157 2158 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 2159 bool CompleteTranslationUnit 2160 = ((options & CXTranslationUnit_Incomplete) == 0); 2161 bool CacheCodeCompetionResults 2162 = options & CXTranslationUnit_CacheCompletionResults; 2163 bool CXXPrecompilePreamble 2164 = options & CXTranslationUnit_CXXPrecompiledPreamble; 2165 bool CXXChainedPCH 2166 = options & CXTranslationUnit_CXXChainedPCH; 2167 2168 // Configure the diagnostics. 2169 DiagnosticOptions DiagOpts; 2170 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2171 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 2172 2173 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2174 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2175 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2176 const llvm::MemoryBuffer *Buffer 2177 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2178 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2179 Buffer)); 2180 } 2181 2182 llvm::SmallVector<const char *, 16> Args; 2183 2184 // The 'source_filename' argument is optional. If the caller does not 2185 // specify it then it is assumed that the source file is specified 2186 // in the actual argument list. 2187 if (source_filename) 2188 Args.push_back(source_filename); 2189 2190 // Since the Clang C library is primarily used by batch tools dealing with 2191 // (often very broken) source code, where spell-checking can have a 2192 // significant negative impact on performance (particularly when 2193 // precompiled headers are involved), we disable it by default. 2194 // Only do this if we haven't found a spell-checking-related argument. 2195 bool FoundSpellCheckingArgument = false; 2196 for (int I = 0; I != num_command_line_args; ++I) { 2197 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 2198 strcmp(command_line_args[I], "-fspell-checking") == 0) { 2199 FoundSpellCheckingArgument = true; 2200 break; 2201 } 2202 } 2203 if (!FoundSpellCheckingArgument) 2204 Args.push_back("-fno-spell-checking"); 2205 2206 Args.insert(Args.end(), command_line_args, 2207 command_line_args + num_command_line_args); 2208 2209 // Do we need the detailed preprocessing record? 2210 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2211 Args.push_back("-Xclang"); 2212 Args.push_back("-detailed-preprocessing-record"); 2213 } 2214 2215 unsigned NumErrors = Diags->getNumErrors(); 2216 llvm::OwningPtr<ASTUnit> Unit( 2217 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), 2218 Diags, 2219 CXXIdx->getClangResourcesPath(), 2220 CXXIdx->getOnlyLocalDecls(), 2221 /*CaptureDiagnostics=*/true, 2222 RemappedFiles.data(), 2223 RemappedFiles.size(), 2224 PrecompilePreamble, 2225 CompleteTranslationUnit, 2226 CacheCodeCompetionResults, 2227 CXXPrecompilePreamble, 2228 CXXChainedPCH)); 2229 2230 if (NumErrors != Diags->getNumErrors()) { 2231 // Make sure to check that 'Unit' is non-NULL. 2232 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { 2233 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 2234 DEnd = Unit->stored_diag_end(); 2235 D != DEnd; ++D) { 2236 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); 2237 CXString Msg = clang_formatDiagnostic(&Diag, 2238 clang_defaultDiagnosticDisplayOptions()); 2239 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2240 clang_disposeString(Msg); 2241 } 2242#ifdef LLVM_ON_WIN32 2243 // On Windows, force a flush, since there may be multiple copies of 2244 // stderr and stdout in the file system, all with different buffers 2245 // but writing to the same device. 2246 fflush(stderr); 2247#endif 2248 } 2249 } 2250 2251 PTUI->result = MakeCXTranslationUnit(Unit.take()); 2252} 2253CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2254 const char *source_filename, 2255 const char * const *command_line_args, 2256 int num_command_line_args, 2257 struct CXUnsavedFile *unsaved_files, 2258 unsigned num_unsaved_files, 2259 unsigned options) { 2260 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2261 num_command_line_args, unsaved_files, 2262 num_unsaved_files, options, 0 }; 2263 llvm::CrashRecoveryContext CRC; 2264 2265 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) { 2266 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2267 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2268 fprintf(stderr, " 'command_line_args' : ["); 2269 for (int i = 0; i != num_command_line_args; ++i) { 2270 if (i) 2271 fprintf(stderr, ", "); 2272 fprintf(stderr, "'%s'", command_line_args[i]); 2273 } 2274 fprintf(stderr, "],\n"); 2275 fprintf(stderr, " 'unsaved_files' : ["); 2276 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2277 if (i) 2278 fprintf(stderr, ", "); 2279 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2280 unsaved_files[i].Length); 2281 } 2282 fprintf(stderr, "],\n"); 2283 fprintf(stderr, " 'options' : %d,\n", options); 2284 fprintf(stderr, "}\n"); 2285 2286 return 0; 2287 } 2288 2289 return PTUI.result; 2290} 2291 2292unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2293 return CXSaveTranslationUnit_None; 2294} 2295 2296int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2297 unsigned options) { 2298 if (!TU) 2299 return 1; 2300 2301 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName); 2302} 2303 2304void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2305 if (CTUnit) { 2306 // If the translation unit has been marked as unsafe to free, just discard 2307 // it. 2308 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree()) 2309 return; 2310 2311 delete static_cast<ASTUnit *>(CTUnit->TUData); 2312 disposeCXStringPool(CTUnit->StringPool); 2313 delete CTUnit; 2314 } 2315} 2316 2317unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2318 return CXReparse_None; 2319} 2320 2321struct ReparseTranslationUnitInfo { 2322 CXTranslationUnit TU; 2323 unsigned num_unsaved_files; 2324 struct CXUnsavedFile *unsaved_files; 2325 unsigned options; 2326 int result; 2327}; 2328 2329static void clang_reparseTranslationUnit_Impl(void *UserData) { 2330 ReparseTranslationUnitInfo *RTUI = 2331 static_cast<ReparseTranslationUnitInfo*>(UserData); 2332 CXTranslationUnit TU = RTUI->TU; 2333 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2334 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2335 unsigned options = RTUI->options; 2336 (void) options; 2337 RTUI->result = 1; 2338 2339 if (!TU) 2340 return; 2341 2342 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2343 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2344 2345 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2346 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2347 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2348 const llvm::MemoryBuffer *Buffer 2349 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2350 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2351 Buffer)); 2352 } 2353 2354 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size())) 2355 RTUI->result = 0; 2356} 2357 2358int clang_reparseTranslationUnit(CXTranslationUnit TU, 2359 unsigned num_unsaved_files, 2360 struct CXUnsavedFile *unsaved_files, 2361 unsigned options) { 2362 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2363 options, 0 }; 2364 llvm::CrashRecoveryContext CRC; 2365 2366 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { 2367 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2368 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true); 2369 return 1; 2370 } 2371 2372 2373 return RTUI.result; 2374} 2375 2376 2377CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2378 if (!CTUnit) 2379 return createCXString(""); 2380 2381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData); 2382 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2383} 2384 2385CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2386 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; 2387 return Result; 2388} 2389 2390} // end: extern "C" 2391 2392//===----------------------------------------------------------------------===// 2393// CXSourceLocation and CXSourceRange Operations. 2394//===----------------------------------------------------------------------===// 2395 2396extern "C" { 2397CXSourceLocation clang_getNullLocation() { 2398 CXSourceLocation Result = { { 0, 0 }, 0 }; 2399 return Result; 2400} 2401 2402unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { 2403 return (loc1.ptr_data[0] == loc2.ptr_data[0] && 2404 loc1.ptr_data[1] == loc2.ptr_data[1] && 2405 loc1.int_data == loc2.int_data); 2406} 2407 2408CXSourceLocation clang_getLocation(CXTranslationUnit tu, 2409 CXFile file, 2410 unsigned line, 2411 unsigned column) { 2412 if (!tu || !file) 2413 return clang_getNullLocation(); 2414 2415 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2416 SourceLocation SLoc 2417 = CXXUnit->getSourceManager().getLocation( 2418 static_cast<const FileEntry *>(file), 2419 line, column); 2420 if (SLoc.isInvalid()) return clang_getNullLocation(); 2421 2422 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2423} 2424 2425CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, 2426 CXFile file, 2427 unsigned offset) { 2428 if (!tu || !file) 2429 return clang_getNullLocation(); 2430 2431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2432 SourceLocation Start 2433 = CXXUnit->getSourceManager().getLocation( 2434 static_cast<const FileEntry *>(file), 2435 1, 1); 2436 if (Start.isInvalid()) return clang_getNullLocation(); 2437 2438 SourceLocation SLoc = Start.getFileLocWithOffset(offset); 2439 2440 if (SLoc.isInvalid()) return clang_getNullLocation(); 2441 2442 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2443} 2444 2445CXSourceRange clang_getNullRange() { 2446 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2447 return Result; 2448} 2449 2450CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2451 if (begin.ptr_data[0] != end.ptr_data[0] || 2452 begin.ptr_data[1] != end.ptr_data[1]) 2453 return clang_getNullRange(); 2454 2455 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2456 begin.int_data, end.int_data }; 2457 return Result; 2458} 2459 2460void clang_getInstantiationLocation(CXSourceLocation location, 2461 CXFile *file, 2462 unsigned *line, 2463 unsigned *column, 2464 unsigned *offset) { 2465 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2466 2467 if (!location.ptr_data[0] || Loc.isInvalid()) { 2468 if (file) 2469 *file = 0; 2470 if (line) 2471 *line = 0; 2472 if (column) 2473 *column = 0; 2474 if (offset) 2475 *offset = 0; 2476 return; 2477 } 2478 2479 const SourceManager &SM = 2480 *static_cast<const SourceManager*>(location.ptr_data[0]); 2481 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2482 2483 if (file) 2484 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2485 if (line) 2486 *line = SM.getInstantiationLineNumber(InstLoc); 2487 if (column) 2488 *column = SM.getInstantiationColumnNumber(InstLoc); 2489 if (offset) 2490 *offset = SM.getDecomposedLoc(InstLoc).second; 2491} 2492 2493void clang_getSpellingLocation(CXSourceLocation location, 2494 CXFile *file, 2495 unsigned *line, 2496 unsigned *column, 2497 unsigned *offset) { 2498 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2499 2500 if (!location.ptr_data[0] || Loc.isInvalid()) { 2501 if (file) 2502 *file = 0; 2503 if (line) 2504 *line = 0; 2505 if (column) 2506 *column = 0; 2507 if (offset) 2508 *offset = 0; 2509 return; 2510 } 2511 2512 const SourceManager &SM = 2513 *static_cast<const SourceManager*>(location.ptr_data[0]); 2514 SourceLocation SpellLoc = Loc; 2515 if (SpellLoc.isMacroID()) { 2516 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc); 2517 if (SimpleSpellingLoc.isFileID() && 2518 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first)) 2519 SpellLoc = SimpleSpellingLoc; 2520 else 2521 SpellLoc = SM.getInstantiationLoc(SpellLoc); 2522 } 2523 2524 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); 2525 FileID FID = LocInfo.first; 2526 unsigned FileOffset = LocInfo.second; 2527 2528 if (file) 2529 *file = (void *)SM.getFileEntryForID(FID); 2530 if (line) 2531 *line = SM.getLineNumber(FID, FileOffset); 2532 if (column) 2533 *column = SM.getColumnNumber(FID, FileOffset); 2534 if (offset) 2535 *offset = FileOffset; 2536} 2537 2538CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2539 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2540 range.begin_int_data }; 2541 return Result; 2542} 2543 2544CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2545 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2546 range.end_int_data }; 2547 return Result; 2548} 2549 2550} // end: extern "C" 2551 2552//===----------------------------------------------------------------------===// 2553// CXFile Operations. 2554//===----------------------------------------------------------------------===// 2555 2556extern "C" { 2557CXString clang_getFileName(CXFile SFile) { 2558 if (!SFile) 2559 return createCXString((const char*)NULL); 2560 2561 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2562 return createCXString(FEnt->getName()); 2563} 2564 2565time_t clang_getFileTime(CXFile SFile) { 2566 if (!SFile) 2567 return 0; 2568 2569 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2570 return FEnt->getModificationTime(); 2571} 2572 2573CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2574 if (!tu) 2575 return 0; 2576 2577 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2578 2579 FileManager &FMgr = CXXUnit->getFileManager(); 2580 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name), 2581 CXXUnit->getFileSystemOpts()); 2582 return const_cast<FileEntry *>(File); 2583} 2584 2585} // end: extern "C" 2586 2587//===----------------------------------------------------------------------===// 2588// CXCursor Operations. 2589//===----------------------------------------------------------------------===// 2590 2591static Decl *getDeclFromExpr(Stmt *E) { 2592 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2593 return getDeclFromExpr(CE->getSubExpr()); 2594 2595 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2596 return RefExpr->getDecl(); 2597 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2598 return RefExpr->getDecl(); 2599 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2600 return ME->getMemberDecl(); 2601 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2602 return RE->getDecl(); 2603 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2604 return PRE->getProperty(); 2605 2606 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2607 return getDeclFromExpr(CE->getCallee()); 2608 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E)) 2609 if (!CE->isElidable()) 2610 return CE->getConstructor(); 2611 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2612 return OME->getMethodDecl(); 2613 2614 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2615 return PE->getProtocol(); 2616 2617 return 0; 2618} 2619 2620static SourceLocation getLocationFromExpr(Expr *E) { 2621 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2622 return /*FIXME:*/Msg->getLeftLoc(); 2623 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2624 return DRE->getLocation(); 2625 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2626 return RefExpr->getLocation(); 2627 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2628 return Member->getMemberLoc(); 2629 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2630 return Ivar->getLocation(); 2631 return E->getLocStart(); 2632} 2633 2634extern "C" { 2635 2636unsigned clang_visitChildren(CXCursor parent, 2637 CXCursorVisitor visitor, 2638 CXClientData client_data) { 2639 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 2640 getCursorASTUnit(parent)->getMaxPCHLevel()); 2641 return CursorVis.VisitChildren(parent); 2642} 2643 2644#ifndef __has_feature 2645#define __has_feature(x) 0 2646#endif 2647#if __has_feature(blocks) 2648typedef enum CXChildVisitResult 2649 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 2650 2651static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2652 CXClientData client_data) { 2653 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2654 return block(cursor, parent); 2655} 2656#else 2657// If we are compiled with a compiler that doesn't have native blocks support, 2658// define and call the block manually, so the 2659typedef struct _CXChildVisitResult 2660{ 2661 void *isa; 2662 int flags; 2663 int reserved; 2664 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 2665 CXCursor); 2666} *CXCursorVisitorBlock; 2667 2668static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2669 CXClientData client_data) { 2670 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2671 return block->invoke(block, cursor, parent); 2672} 2673#endif 2674 2675 2676unsigned clang_visitChildrenWithBlock(CXCursor parent, 2677 CXCursorVisitorBlock block) { 2678 return clang_visitChildren(parent, visitWithBlock, block); 2679} 2680 2681static CXString getDeclSpelling(Decl *D) { 2682 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2683 if (!ND) { 2684 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 2685 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 2686 return createCXString(Property->getIdentifier()->getName()); 2687 2688 return createCXString(""); 2689 } 2690 2691 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2692 return createCXString(OMD->getSelector().getAsString()); 2693 2694 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2695 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2696 // and returns different names. NamedDecl returns the class name and 2697 // ObjCCategoryImplDecl returns the category name. 2698 return createCXString(CIMP->getIdentifier()->getNameStart()); 2699 2700 if (isa<UsingDirectiveDecl>(D)) 2701 return createCXString(""); 2702 2703 llvm::SmallString<1024> S; 2704 llvm::raw_svector_ostream os(S); 2705 ND->printName(os); 2706 2707 return createCXString(os.str()); 2708} 2709 2710CXString clang_getCursorSpelling(CXCursor C) { 2711 if (clang_isTranslationUnit(C.kind)) 2712 return clang_getTranslationUnitSpelling( 2713 static_cast<CXTranslationUnit>(C.data[2])); 2714 2715 if (clang_isReference(C.kind)) { 2716 switch (C.kind) { 2717 case CXCursor_ObjCSuperClassRef: { 2718 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2719 return createCXString(Super->getIdentifier()->getNameStart()); 2720 } 2721 case CXCursor_ObjCClassRef: { 2722 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2723 return createCXString(Class->getIdentifier()->getNameStart()); 2724 } 2725 case CXCursor_ObjCProtocolRef: { 2726 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2727 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2728 return createCXString(OID->getIdentifier()->getNameStart()); 2729 } 2730 case CXCursor_CXXBaseSpecifier: { 2731 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2732 return createCXString(B->getType().getAsString()); 2733 } 2734 case CXCursor_TypeRef: { 2735 TypeDecl *Type = getCursorTypeRef(C).first; 2736 assert(Type && "Missing type decl"); 2737 2738 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2739 getAsString()); 2740 } 2741 case CXCursor_TemplateRef: { 2742 TemplateDecl *Template = getCursorTemplateRef(C).first; 2743 assert(Template && "Missing template decl"); 2744 2745 return createCXString(Template->getNameAsString()); 2746 } 2747 2748 case CXCursor_NamespaceRef: { 2749 NamedDecl *NS = getCursorNamespaceRef(C).first; 2750 assert(NS && "Missing namespace decl"); 2751 2752 return createCXString(NS->getNameAsString()); 2753 } 2754 2755 case CXCursor_MemberRef: { 2756 FieldDecl *Field = getCursorMemberRef(C).first; 2757 assert(Field && "Missing member decl"); 2758 2759 return createCXString(Field->getNameAsString()); 2760 } 2761 2762 case CXCursor_LabelRef: { 2763 LabelStmt *Label = getCursorLabelRef(C).first; 2764 assert(Label && "Missing label"); 2765 2766 return createCXString(Label->getID()->getName()); 2767 } 2768 2769 case CXCursor_OverloadedDeclRef: { 2770 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 2771 if (Decl *D = Storage.dyn_cast<Decl *>()) { 2772 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 2773 return createCXString(ND->getNameAsString()); 2774 return createCXString(""); 2775 } 2776 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 2777 return createCXString(E->getName().getAsString()); 2778 OverloadedTemplateStorage *Ovl 2779 = Storage.get<OverloadedTemplateStorage*>(); 2780 if (Ovl->size() == 0) 2781 return createCXString(""); 2782 return createCXString((*Ovl->begin())->getNameAsString()); 2783 } 2784 2785 default: 2786 return createCXString("<not implemented>"); 2787 } 2788 } 2789 2790 if (clang_isExpression(C.kind)) { 2791 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2792 if (D) 2793 return getDeclSpelling(D); 2794 return createCXString(""); 2795 } 2796 2797 if (clang_isStatement(C.kind)) { 2798 Stmt *S = getCursorStmt(C); 2799 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 2800 return createCXString(Label->getID()->getName()); 2801 2802 return createCXString(""); 2803 } 2804 2805 if (C.kind == CXCursor_MacroInstantiation) 2806 return createCXString(getCursorMacroInstantiation(C)->getName() 2807 ->getNameStart()); 2808 2809 if (C.kind == CXCursor_MacroDefinition) 2810 return createCXString(getCursorMacroDefinition(C)->getName() 2811 ->getNameStart()); 2812 2813 if (C.kind == CXCursor_InclusionDirective) 2814 return createCXString(getCursorInclusionDirective(C)->getFileName()); 2815 2816 if (clang_isDeclaration(C.kind)) 2817 return getDeclSpelling(getCursorDecl(C)); 2818 2819 return createCXString(""); 2820} 2821 2822CXString clang_getCursorDisplayName(CXCursor C) { 2823 if (!clang_isDeclaration(C.kind)) 2824 return clang_getCursorSpelling(C); 2825 2826 Decl *D = getCursorDecl(C); 2827 if (!D) 2828 return createCXString(""); 2829 2830 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 2831 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 2832 D = FunTmpl->getTemplatedDecl(); 2833 2834 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 2835 llvm::SmallString<64> Str; 2836 llvm::raw_svector_ostream OS(Str); 2837 OS << Function->getNameAsString(); 2838 if (Function->getPrimaryTemplate()) 2839 OS << "<>"; 2840 OS << "("; 2841 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 2842 if (I) 2843 OS << ", "; 2844 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 2845 } 2846 2847 if (Function->isVariadic()) { 2848 if (Function->getNumParams()) 2849 OS << ", "; 2850 OS << "..."; 2851 } 2852 OS << ")"; 2853 return createCXString(OS.str()); 2854 } 2855 2856 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 2857 llvm::SmallString<64> Str; 2858 llvm::raw_svector_ostream OS(Str); 2859 OS << ClassTemplate->getNameAsString(); 2860 OS << "<"; 2861 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 2862 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2863 if (I) 2864 OS << ", "; 2865 2866 NamedDecl *Param = Params->getParam(I); 2867 if (Param->getIdentifier()) { 2868 OS << Param->getIdentifier()->getName(); 2869 continue; 2870 } 2871 2872 // There is no parameter name, which makes this tricky. Try to come up 2873 // with something useful that isn't too long. 2874 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2875 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 2876 else if (NonTypeTemplateParmDecl *NTTP 2877 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2878 OS << NTTP->getType().getAsString(Policy); 2879 else 2880 OS << "template<...> class"; 2881 } 2882 2883 OS << ">"; 2884 return createCXString(OS.str()); 2885 } 2886 2887 if (ClassTemplateSpecializationDecl *ClassSpec 2888 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 2889 // If the type was explicitly written, use that. 2890 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 2891 return createCXString(TSInfo->getType().getAsString(Policy)); 2892 2893 llvm::SmallString<64> Str; 2894 llvm::raw_svector_ostream OS(Str); 2895 OS << ClassSpec->getNameAsString(); 2896 OS << TemplateSpecializationType::PrintTemplateArgumentList( 2897 ClassSpec->getTemplateArgs().data(), 2898 ClassSpec->getTemplateArgs().size(), 2899 Policy); 2900 return createCXString(OS.str()); 2901 } 2902 2903 return clang_getCursorSpelling(C); 2904} 2905 2906CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2907 switch (Kind) { 2908 case CXCursor_FunctionDecl: 2909 return createCXString("FunctionDecl"); 2910 case CXCursor_TypedefDecl: 2911 return createCXString("TypedefDecl"); 2912 case CXCursor_EnumDecl: 2913 return createCXString("EnumDecl"); 2914 case CXCursor_EnumConstantDecl: 2915 return createCXString("EnumConstantDecl"); 2916 case CXCursor_StructDecl: 2917 return createCXString("StructDecl"); 2918 case CXCursor_UnionDecl: 2919 return createCXString("UnionDecl"); 2920 case CXCursor_ClassDecl: 2921 return createCXString("ClassDecl"); 2922 case CXCursor_FieldDecl: 2923 return createCXString("FieldDecl"); 2924 case CXCursor_VarDecl: 2925 return createCXString("VarDecl"); 2926 case CXCursor_ParmDecl: 2927 return createCXString("ParmDecl"); 2928 case CXCursor_ObjCInterfaceDecl: 2929 return createCXString("ObjCInterfaceDecl"); 2930 case CXCursor_ObjCCategoryDecl: 2931 return createCXString("ObjCCategoryDecl"); 2932 case CXCursor_ObjCProtocolDecl: 2933 return createCXString("ObjCProtocolDecl"); 2934 case CXCursor_ObjCPropertyDecl: 2935 return createCXString("ObjCPropertyDecl"); 2936 case CXCursor_ObjCIvarDecl: 2937 return createCXString("ObjCIvarDecl"); 2938 case CXCursor_ObjCInstanceMethodDecl: 2939 return createCXString("ObjCInstanceMethodDecl"); 2940 case CXCursor_ObjCClassMethodDecl: 2941 return createCXString("ObjCClassMethodDecl"); 2942 case CXCursor_ObjCImplementationDecl: 2943 return createCXString("ObjCImplementationDecl"); 2944 case CXCursor_ObjCCategoryImplDecl: 2945 return createCXString("ObjCCategoryImplDecl"); 2946 case CXCursor_CXXMethod: 2947 return createCXString("CXXMethod"); 2948 case CXCursor_UnexposedDecl: 2949 return createCXString("UnexposedDecl"); 2950 case CXCursor_ObjCSuperClassRef: 2951 return createCXString("ObjCSuperClassRef"); 2952 case CXCursor_ObjCProtocolRef: 2953 return createCXString("ObjCProtocolRef"); 2954 case CXCursor_ObjCClassRef: 2955 return createCXString("ObjCClassRef"); 2956 case CXCursor_TypeRef: 2957 return createCXString("TypeRef"); 2958 case CXCursor_TemplateRef: 2959 return createCXString("TemplateRef"); 2960 case CXCursor_NamespaceRef: 2961 return createCXString("NamespaceRef"); 2962 case CXCursor_MemberRef: 2963 return createCXString("MemberRef"); 2964 case CXCursor_LabelRef: 2965 return createCXString("LabelRef"); 2966 case CXCursor_OverloadedDeclRef: 2967 return createCXString("OverloadedDeclRef"); 2968 case CXCursor_UnexposedExpr: 2969 return createCXString("UnexposedExpr"); 2970 case CXCursor_BlockExpr: 2971 return createCXString("BlockExpr"); 2972 case CXCursor_DeclRefExpr: 2973 return createCXString("DeclRefExpr"); 2974 case CXCursor_MemberRefExpr: 2975 return createCXString("MemberRefExpr"); 2976 case CXCursor_CallExpr: 2977 return createCXString("CallExpr"); 2978 case CXCursor_ObjCMessageExpr: 2979 return createCXString("ObjCMessageExpr"); 2980 case CXCursor_UnexposedStmt: 2981 return createCXString("UnexposedStmt"); 2982 case CXCursor_LabelStmt: 2983 return createCXString("LabelStmt"); 2984 case CXCursor_InvalidFile: 2985 return createCXString("InvalidFile"); 2986 case CXCursor_InvalidCode: 2987 return createCXString("InvalidCode"); 2988 case CXCursor_NoDeclFound: 2989 return createCXString("NoDeclFound"); 2990 case CXCursor_NotImplemented: 2991 return createCXString("NotImplemented"); 2992 case CXCursor_TranslationUnit: 2993 return createCXString("TranslationUnit"); 2994 case CXCursor_UnexposedAttr: 2995 return createCXString("UnexposedAttr"); 2996 case CXCursor_IBActionAttr: 2997 return createCXString("attribute(ibaction)"); 2998 case CXCursor_IBOutletAttr: 2999 return createCXString("attribute(iboutlet)"); 3000 case CXCursor_IBOutletCollectionAttr: 3001 return createCXString("attribute(iboutletcollection)"); 3002 case CXCursor_PreprocessingDirective: 3003 return createCXString("preprocessing directive"); 3004 case CXCursor_MacroDefinition: 3005 return createCXString("macro definition"); 3006 case CXCursor_MacroInstantiation: 3007 return createCXString("macro instantiation"); 3008 case CXCursor_InclusionDirective: 3009 return createCXString("inclusion directive"); 3010 case CXCursor_Namespace: 3011 return createCXString("Namespace"); 3012 case CXCursor_LinkageSpec: 3013 return createCXString("LinkageSpec"); 3014 case CXCursor_CXXBaseSpecifier: 3015 return createCXString("C++ base class specifier"); 3016 case CXCursor_Constructor: 3017 return createCXString("CXXConstructor"); 3018 case CXCursor_Destructor: 3019 return createCXString("CXXDestructor"); 3020 case CXCursor_ConversionFunction: 3021 return createCXString("CXXConversion"); 3022 case CXCursor_TemplateTypeParameter: 3023 return createCXString("TemplateTypeParameter"); 3024 case CXCursor_NonTypeTemplateParameter: 3025 return createCXString("NonTypeTemplateParameter"); 3026 case CXCursor_TemplateTemplateParameter: 3027 return createCXString("TemplateTemplateParameter"); 3028 case CXCursor_FunctionTemplate: 3029 return createCXString("FunctionTemplate"); 3030 case CXCursor_ClassTemplate: 3031 return createCXString("ClassTemplate"); 3032 case CXCursor_ClassTemplatePartialSpecialization: 3033 return createCXString("ClassTemplatePartialSpecialization"); 3034 case CXCursor_NamespaceAlias: 3035 return createCXString("NamespaceAlias"); 3036 case CXCursor_UsingDirective: 3037 return createCXString("UsingDirective"); 3038 case CXCursor_UsingDeclaration: 3039 return createCXString("UsingDeclaration"); 3040 } 3041 3042 llvm_unreachable("Unhandled CXCursorKind"); 3043 return createCXString((const char*) 0); 3044} 3045 3046enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3047 CXCursor parent, 3048 CXClientData client_data) { 3049 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 3050 3051 // If our current best cursor is the construction of a temporary object, 3052 // don't replace that cursor with a type reference, because we want 3053 // clang_getCursor() to point at the constructor. 3054 if (clang_isExpression(BestCursor->kind) && 3055 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3056 cursor.kind == CXCursor_TypeRef) 3057 return CXChildVisit_Recurse; 3058 3059 *BestCursor = cursor; 3060 return CXChildVisit_Recurse; 3061} 3062 3063CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3064 if (!TU) 3065 return clang_getNullCursor(); 3066 3067 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3068 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3069 3070 // Translate the given source location to make it point at the beginning of 3071 // the token under the cursor. 3072 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3073 3074 // Guard against an invalid SourceLocation, or we may assert in one 3075 // of the following calls. 3076 if (SLoc.isInvalid()) 3077 return clang_getNullCursor(); 3078 3079 bool Logging = getenv("LIBCLANG_LOGGING"); 3080 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 3081 CXXUnit->getASTContext().getLangOptions()); 3082 3083 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 3084 if (SLoc.isValid()) { 3085 // FIXME: Would be great to have a "hint" cursor, then walk from that 3086 // hint cursor upward until we find a cursor whose source range encloses 3087 // the region of interest, rather than starting from the translation unit. 3088 CXCursor Parent = clang_getTranslationUnitCursor(TU); 3089 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result, 3090 Decl::MaxPCHLevel, SourceLocation(SLoc)); 3091 CursorVis.VisitChildren(Parent); 3092 } 3093 3094 if (Logging) { 3095 CXFile SearchFile; 3096 unsigned SearchLine, SearchColumn; 3097 CXFile ResultFile; 3098 unsigned ResultLine, ResultColumn; 3099 CXString SearchFileName, ResultFileName, KindSpelling; 3100 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3101 3102 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 3103 0); 3104 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine, 3105 &ResultColumn, 0); 3106 SearchFileName = clang_getFileName(SearchFile); 3107 ResultFileName = clang_getFileName(ResultFile); 3108 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3109 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n", 3110 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3111 clang_getCString(KindSpelling), 3112 clang_getCString(ResultFileName), ResultLine, ResultColumn); 3113 clang_disposeString(SearchFileName); 3114 clang_disposeString(ResultFileName); 3115 clang_disposeString(KindSpelling); 3116 } 3117 3118 return Result; 3119} 3120 3121CXCursor clang_getNullCursor(void) { 3122 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3123} 3124 3125unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3126 return X == Y; 3127} 3128 3129unsigned clang_isInvalid(enum CXCursorKind K) { 3130 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3131} 3132 3133unsigned clang_isDeclaration(enum CXCursorKind K) { 3134 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 3135} 3136 3137unsigned clang_isReference(enum CXCursorKind K) { 3138 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3139} 3140 3141unsigned clang_isExpression(enum CXCursorKind K) { 3142 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3143} 3144 3145unsigned clang_isStatement(enum CXCursorKind K) { 3146 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3147} 3148 3149unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3150 return K == CXCursor_TranslationUnit; 3151} 3152 3153unsigned clang_isPreprocessing(enum CXCursorKind K) { 3154 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3155} 3156 3157unsigned clang_isUnexposed(enum CXCursorKind K) { 3158 switch (K) { 3159 case CXCursor_UnexposedDecl: 3160 case CXCursor_UnexposedExpr: 3161 case CXCursor_UnexposedStmt: 3162 case CXCursor_UnexposedAttr: 3163 return true; 3164 default: 3165 return false; 3166 } 3167} 3168 3169CXCursorKind clang_getCursorKind(CXCursor C) { 3170 return C.kind; 3171} 3172 3173CXSourceLocation clang_getCursorLocation(CXCursor C) { 3174 if (clang_isReference(C.kind)) { 3175 switch (C.kind) { 3176 case CXCursor_ObjCSuperClassRef: { 3177 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3178 = getCursorObjCSuperClassRef(C); 3179 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3180 } 3181 3182 case CXCursor_ObjCProtocolRef: { 3183 std::pair<ObjCProtocolDecl *, SourceLocation> P 3184 = getCursorObjCProtocolRef(C); 3185 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3186 } 3187 3188 case CXCursor_ObjCClassRef: { 3189 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3190 = getCursorObjCClassRef(C); 3191 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3192 } 3193 3194 case CXCursor_TypeRef: { 3195 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3196 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3197 } 3198 3199 case CXCursor_TemplateRef: { 3200 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3201 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3202 } 3203 3204 case CXCursor_NamespaceRef: { 3205 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3206 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3207 } 3208 3209 case CXCursor_MemberRef: { 3210 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3212 } 3213 3214 case CXCursor_CXXBaseSpecifier: { 3215 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3216 if (!BaseSpec) 3217 return clang_getNullLocation(); 3218 3219 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3220 return cxloc::translateSourceLocation(getCursorContext(C), 3221 TSInfo->getTypeLoc().getBeginLoc()); 3222 3223 return cxloc::translateSourceLocation(getCursorContext(C), 3224 BaseSpec->getSourceRange().getBegin()); 3225 } 3226 3227 case CXCursor_LabelRef: { 3228 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3229 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3230 } 3231 3232 case CXCursor_OverloadedDeclRef: 3233 return cxloc::translateSourceLocation(getCursorContext(C), 3234 getCursorOverloadedDeclRef(C).second); 3235 3236 default: 3237 // FIXME: Need a way to enumerate all non-reference cases. 3238 llvm_unreachable("Missed a reference kind"); 3239 } 3240 } 3241 3242 if (clang_isExpression(C.kind)) 3243 return cxloc::translateSourceLocation(getCursorContext(C), 3244 getLocationFromExpr(getCursorExpr(C))); 3245 3246 if (clang_isStatement(C.kind)) 3247 return cxloc::translateSourceLocation(getCursorContext(C), 3248 getCursorStmt(C)->getLocStart()); 3249 3250 if (C.kind == CXCursor_PreprocessingDirective) { 3251 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3252 return cxloc::translateSourceLocation(getCursorContext(C), L); 3253 } 3254 3255 if (C.kind == CXCursor_MacroInstantiation) { 3256 SourceLocation L 3257 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 3258 return cxloc::translateSourceLocation(getCursorContext(C), L); 3259 } 3260 3261 if (C.kind == CXCursor_MacroDefinition) { 3262 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 3263 return cxloc::translateSourceLocation(getCursorContext(C), L); 3264 } 3265 3266 if (C.kind == CXCursor_InclusionDirective) { 3267 SourceLocation L 3268 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 3269 return cxloc::translateSourceLocation(getCursorContext(C), L); 3270 } 3271 3272 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 3273 return clang_getNullLocation(); 3274 3275 Decl *D = getCursorDecl(C); 3276 SourceLocation Loc = D->getLocation(); 3277 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3278 Loc = Class->getClassLoc(); 3279 // FIXME: Multiple variables declared in a single declaration 3280 // currently lack the information needed to correctly determine their 3281 // ranges when accounting for the type-specifier. We use context 3282 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3283 // and if so, whether it is the first decl. 3284 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3285 if (!cxcursor::isFirstInDeclGroup(C)) 3286 Loc = VD->getLocation(); 3287 } 3288 3289 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 3290} 3291 3292} // end extern "C" 3293 3294static SourceRange getRawCursorExtent(CXCursor C) { 3295 if (clang_isReference(C.kind)) { 3296 switch (C.kind) { 3297 case CXCursor_ObjCSuperClassRef: 3298 return getCursorObjCSuperClassRef(C).second; 3299 3300 case CXCursor_ObjCProtocolRef: 3301 return getCursorObjCProtocolRef(C).second; 3302 3303 case CXCursor_ObjCClassRef: 3304 return getCursorObjCClassRef(C).second; 3305 3306 case CXCursor_TypeRef: 3307 return getCursorTypeRef(C).second; 3308 3309 case CXCursor_TemplateRef: 3310 return getCursorTemplateRef(C).second; 3311 3312 case CXCursor_NamespaceRef: 3313 return getCursorNamespaceRef(C).second; 3314 3315 case CXCursor_MemberRef: 3316 return getCursorMemberRef(C).second; 3317 3318 case CXCursor_CXXBaseSpecifier: 3319 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3320 3321 case CXCursor_LabelRef: 3322 return getCursorLabelRef(C).second; 3323 3324 case CXCursor_OverloadedDeclRef: 3325 return getCursorOverloadedDeclRef(C).second; 3326 3327 default: 3328 // FIXME: Need a way to enumerate all non-reference cases. 3329 llvm_unreachable("Missed a reference kind"); 3330 } 3331 } 3332 3333 if (clang_isExpression(C.kind)) 3334 return getCursorExpr(C)->getSourceRange(); 3335 3336 if (clang_isStatement(C.kind)) 3337 return getCursorStmt(C)->getSourceRange(); 3338 3339 if (C.kind == CXCursor_PreprocessingDirective) 3340 return cxcursor::getCursorPreprocessingDirective(C); 3341 3342 if (C.kind == CXCursor_MacroInstantiation) 3343 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3344 3345 if (C.kind == CXCursor_MacroDefinition) 3346 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3347 3348 if (C.kind == CXCursor_InclusionDirective) 3349 return cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 3350 3351 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3352 Decl *D = cxcursor::getCursorDecl(C); 3353 SourceRange R = D->getSourceRange(); 3354 // FIXME: Multiple variables declared in a single declaration 3355 // currently lack the information needed to correctly determine their 3356 // ranges when accounting for the type-specifier. We use context 3357 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3358 // and if so, whether it is the first decl. 3359 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3360 if (!cxcursor::isFirstInDeclGroup(C)) 3361 R.setBegin(VD->getLocation()); 3362 } 3363 return R; 3364 } 3365 return SourceRange();} 3366 3367extern "C" { 3368 3369CXSourceRange clang_getCursorExtent(CXCursor C) { 3370 SourceRange R = getRawCursorExtent(C); 3371 if (R.isInvalid()) 3372 return clang_getNullRange(); 3373 3374 return cxloc::translateSourceRange(getCursorContext(C), R); 3375} 3376 3377CXCursor clang_getCursorReferenced(CXCursor C) { 3378 if (clang_isInvalid(C.kind)) 3379 return clang_getNullCursor(); 3380 3381 CXTranslationUnit tu = getCursorTU(C); 3382 if (clang_isDeclaration(C.kind)) { 3383 Decl *D = getCursorDecl(C); 3384 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3385 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 3386 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3387 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu); 3388 if (ObjCForwardProtocolDecl *Protocols 3389 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3390 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu); 3391 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 3392 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 3393 return MakeCXCursor(Property, tu); 3394 3395 return C; 3396 } 3397 3398 if (clang_isExpression(C.kind)) { 3399 Expr *E = getCursorExpr(C); 3400 Decl *D = getDeclFromExpr(E); 3401 if (D) 3402 return MakeCXCursor(D, tu); 3403 3404 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3405 return MakeCursorOverloadedDeclRef(Ovl, tu); 3406 3407 return clang_getNullCursor(); 3408 } 3409 3410 if (clang_isStatement(C.kind)) { 3411 Stmt *S = getCursorStmt(C); 3412 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3413 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu); 3414 3415 return clang_getNullCursor(); 3416 } 3417 3418 if (C.kind == CXCursor_MacroInstantiation) { 3419 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3420 return MakeMacroDefinitionCursor(Def, tu); 3421 } 3422 3423 if (!clang_isReference(C.kind)) 3424 return clang_getNullCursor(); 3425 3426 switch (C.kind) { 3427 case CXCursor_ObjCSuperClassRef: 3428 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 3429 3430 case CXCursor_ObjCProtocolRef: { 3431 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu); 3432 3433 case CXCursor_ObjCClassRef: 3434 return MakeCXCursor(getCursorObjCClassRef(C).first, tu ); 3435 3436 case CXCursor_TypeRef: 3437 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 3438 3439 case CXCursor_TemplateRef: 3440 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 3441 3442 case CXCursor_NamespaceRef: 3443 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 3444 3445 case CXCursor_MemberRef: 3446 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 3447 3448 case CXCursor_CXXBaseSpecifier: { 3449 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3450 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3451 tu )); 3452 } 3453 3454 case CXCursor_LabelRef: 3455 // FIXME: We end up faking the "parent" declaration here because we 3456 // don't want to make CXCursor larger. 3457 return MakeCXCursor(getCursorLabelRef(C).first, 3458 static_cast<ASTUnit*>(tu->TUData)->getASTContext() 3459 .getTranslationUnitDecl(), 3460 tu); 3461 3462 case CXCursor_OverloadedDeclRef: 3463 return C; 3464 3465 default: 3466 // We would prefer to enumerate all non-reference cursor kinds here. 3467 llvm_unreachable("Unhandled reference cursor kind"); 3468 break; 3469 } 3470 } 3471 3472 return clang_getNullCursor(); 3473} 3474 3475CXCursor clang_getCursorDefinition(CXCursor C) { 3476 if (clang_isInvalid(C.kind)) 3477 return clang_getNullCursor(); 3478 3479 CXTranslationUnit TU = getCursorTU(C); 3480 3481 bool WasReference = false; 3482 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3483 C = clang_getCursorReferenced(C); 3484 WasReference = true; 3485 } 3486 3487 if (C.kind == CXCursor_MacroInstantiation) 3488 return clang_getCursorReferenced(C); 3489 3490 if (!clang_isDeclaration(C.kind)) 3491 return clang_getNullCursor(); 3492 3493 Decl *D = getCursorDecl(C); 3494 if (!D) 3495 return clang_getNullCursor(); 3496 3497 switch (D->getKind()) { 3498 // Declaration kinds that don't really separate the notions of 3499 // declaration and definition. 3500 case Decl::Namespace: 3501 case Decl::Typedef: 3502 case Decl::TemplateTypeParm: 3503 case Decl::EnumConstant: 3504 case Decl::Field: 3505 case Decl::ObjCIvar: 3506 case Decl::ObjCAtDefsField: 3507 case Decl::ImplicitParam: 3508 case Decl::ParmVar: 3509 case Decl::NonTypeTemplateParm: 3510 case Decl::TemplateTemplateParm: 3511 case Decl::ObjCCategoryImpl: 3512 case Decl::ObjCImplementation: 3513 case Decl::AccessSpec: 3514 case Decl::LinkageSpec: 3515 case Decl::ObjCPropertyImpl: 3516 case Decl::FileScopeAsm: 3517 case Decl::StaticAssert: 3518 case Decl::Block: 3519 return C; 3520 3521 // Declaration kinds that don't make any sense here, but are 3522 // nonetheless harmless. 3523 case Decl::TranslationUnit: 3524 break; 3525 3526 // Declaration kinds for which the definition is not resolvable. 3527 case Decl::UnresolvedUsingTypename: 3528 case Decl::UnresolvedUsingValue: 3529 break; 3530 3531 case Decl::UsingDirective: 3532 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3533 TU); 3534 3535 case Decl::NamespaceAlias: 3536 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 3537 3538 case Decl::Enum: 3539 case Decl::Record: 3540 case Decl::CXXRecord: 3541 case Decl::ClassTemplateSpecialization: 3542 case Decl::ClassTemplatePartialSpecialization: 3543 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3544 return MakeCXCursor(Def, TU); 3545 return clang_getNullCursor(); 3546 3547 case Decl::Function: 3548 case Decl::CXXMethod: 3549 case Decl::CXXConstructor: 3550 case Decl::CXXDestructor: 3551 case Decl::CXXConversion: { 3552 const FunctionDecl *Def = 0; 3553 if (cast<FunctionDecl>(D)->getBody(Def)) 3554 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU); 3555 return clang_getNullCursor(); 3556 } 3557 3558 case Decl::Var: { 3559 // Ask the variable if it has a definition. 3560 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3561 return MakeCXCursor(Def, TU); 3562 return clang_getNullCursor(); 3563 } 3564 3565 case Decl::FunctionTemplate: { 3566 const FunctionDecl *Def = 0; 3567 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3568 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 3569 return clang_getNullCursor(); 3570 } 3571 3572 case Decl::ClassTemplate: { 3573 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3574 ->getDefinition()) 3575 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3576 TU); 3577 return clang_getNullCursor(); 3578 } 3579 3580 case Decl::Using: 3581 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3582 D->getLocation(), TU); 3583 3584 case Decl::UsingShadow: 3585 return clang_getCursorDefinition( 3586 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3587 TU)); 3588 3589 case Decl::ObjCMethod: { 3590 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3591 if (Method->isThisDeclarationADefinition()) 3592 return C; 3593 3594 // Dig out the method definition in the associated 3595 // @implementation, if we have it. 3596 // FIXME: The ASTs should make finding the definition easier. 3597 if (ObjCInterfaceDecl *Class 3598 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3599 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3600 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3601 Method->isInstanceMethod())) 3602 if (Def->isThisDeclarationADefinition()) 3603 return MakeCXCursor(Def, TU); 3604 3605 return clang_getNullCursor(); 3606 } 3607 3608 case Decl::ObjCCategory: 3609 if (ObjCCategoryImplDecl *Impl 3610 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3611 return MakeCXCursor(Impl, TU); 3612 return clang_getNullCursor(); 3613 3614 case Decl::ObjCProtocol: 3615 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3616 return C; 3617 return clang_getNullCursor(); 3618 3619 case Decl::ObjCInterface: 3620 // There are two notions of a "definition" for an Objective-C 3621 // class: the interface and its implementation. When we resolved a 3622 // reference to an Objective-C class, produce the @interface as 3623 // the definition; when we were provided with the interface, 3624 // produce the @implementation as the definition. 3625 if (WasReference) { 3626 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3627 return C; 3628 } else if (ObjCImplementationDecl *Impl 3629 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3630 return MakeCXCursor(Impl, TU); 3631 return clang_getNullCursor(); 3632 3633 case Decl::ObjCProperty: 3634 // FIXME: We don't really know where to find the 3635 // ObjCPropertyImplDecls that implement this property. 3636 return clang_getNullCursor(); 3637 3638 case Decl::ObjCCompatibleAlias: 3639 if (ObjCInterfaceDecl *Class 3640 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3641 if (!Class->isForwardDecl()) 3642 return MakeCXCursor(Class, TU); 3643 3644 return clang_getNullCursor(); 3645 3646 case Decl::ObjCForwardProtocol: 3647 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 3648 D->getLocation(), TU); 3649 3650 case Decl::ObjCClass: 3651 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 3652 TU); 3653 3654 case Decl::Friend: 3655 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3656 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 3657 return clang_getNullCursor(); 3658 3659 case Decl::FriendTemplate: 3660 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3661 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 3662 return clang_getNullCursor(); 3663 } 3664 3665 return clang_getNullCursor(); 3666} 3667 3668unsigned clang_isCursorDefinition(CXCursor C) { 3669 if (!clang_isDeclaration(C.kind)) 3670 return 0; 3671 3672 return clang_getCursorDefinition(C) == C; 3673} 3674 3675unsigned clang_getNumOverloadedDecls(CXCursor C) { 3676 if (C.kind != CXCursor_OverloadedDeclRef) 3677 return 0; 3678 3679 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3680 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3681 return E->getNumDecls(); 3682 3683 if (OverloadedTemplateStorage *S 3684 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3685 return S->size(); 3686 3687 Decl *D = Storage.get<Decl*>(); 3688 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3689 return Using->shadow_size(); 3690 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3691 return Classes->size(); 3692 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 3693 return Protocols->protocol_size(); 3694 3695 return 0; 3696} 3697 3698CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 3699 if (cursor.kind != CXCursor_OverloadedDeclRef) 3700 return clang_getNullCursor(); 3701 3702 if (index >= clang_getNumOverloadedDecls(cursor)) 3703 return clang_getNullCursor(); 3704 3705 CXTranslationUnit TU = getCursorTU(cursor); 3706 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 3707 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3708 return MakeCXCursor(E->decls_begin()[index], TU); 3709 3710 if (OverloadedTemplateStorage *S 3711 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3712 return MakeCXCursor(S->begin()[index], TU); 3713 3714 Decl *D = Storage.get<Decl*>(); 3715 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 3716 // FIXME: This is, unfortunately, linear time. 3717 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 3718 std::advance(Pos, index); 3719 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 3720 } 3721 3722 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3723 return MakeCXCursor(Classes->begin()[index].getInterface(), TU); 3724 3725 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 3726 return MakeCXCursor(Protocols->protocol_begin()[index], TU); 3727 3728 return clang_getNullCursor(); 3729} 3730 3731void clang_getDefinitionSpellingAndExtent(CXCursor C, 3732 const char **startBuf, 3733 const char **endBuf, 3734 unsigned *startLine, 3735 unsigned *startColumn, 3736 unsigned *endLine, 3737 unsigned *endColumn) { 3738 assert(getCursorDecl(C) && "CXCursor has null decl"); 3739 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3740 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3741 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3742 3743 SourceManager &SM = FD->getASTContext().getSourceManager(); 3744 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3745 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3746 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3747 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3748 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3749 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3750} 3751 3752void clang_enableStackTraces(void) { 3753 llvm::sys::PrintStackTraceOnErrorSignal(); 3754} 3755 3756void clang_executeOnThread(void (*fn)(void*), void *user_data, 3757 unsigned stack_size) { 3758 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 3759} 3760 3761} // end: extern "C" 3762 3763//===----------------------------------------------------------------------===// 3764// Token-based Operations. 3765//===----------------------------------------------------------------------===// 3766 3767/* CXToken layout: 3768 * int_data[0]: a CXTokenKind 3769 * int_data[1]: starting token location 3770 * int_data[2]: token length 3771 * int_data[3]: reserved 3772 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3773 * otherwise unused. 3774 */ 3775extern "C" { 3776 3777CXTokenKind clang_getTokenKind(CXToken CXTok) { 3778 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3779} 3780 3781CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3782 switch (clang_getTokenKind(CXTok)) { 3783 case CXToken_Identifier: 3784 case CXToken_Keyword: 3785 // We know we have an IdentifierInfo*, so use that. 3786 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3787 ->getNameStart()); 3788 3789 case CXToken_Literal: { 3790 // We have stashed the starting pointer in the ptr_data field. Use it. 3791 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3792 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3793 } 3794 3795 case CXToken_Punctuation: 3796 case CXToken_Comment: 3797 break; 3798 } 3799 3800 // We have to find the starting buffer pointer the hard way, by 3801 // deconstructing the source location. 3802 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3803 if (!CXXUnit) 3804 return createCXString(""); 3805 3806 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3807 std::pair<FileID, unsigned> LocInfo 3808 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3809 bool Invalid = false; 3810 llvm::StringRef Buffer 3811 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3812 if (Invalid) 3813 return createCXString(""); 3814 3815 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3816} 3817 3818CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3819 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3820 if (!CXXUnit) 3821 return clang_getNullLocation(); 3822 3823 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3824 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3825} 3826 3827CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3829 if (!CXXUnit) 3830 return clang_getNullRange(); 3831 3832 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3833 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3834} 3835 3836void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3837 CXToken **Tokens, unsigned *NumTokens) { 3838 if (Tokens) 3839 *Tokens = 0; 3840 if (NumTokens) 3841 *NumTokens = 0; 3842 3843 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3844 if (!CXXUnit || !Tokens || !NumTokens) 3845 return; 3846 3847 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3848 3849 SourceRange R = cxloc::translateCXSourceRange(Range); 3850 if (R.isInvalid()) 3851 return; 3852 3853 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3854 std::pair<FileID, unsigned> BeginLocInfo 3855 = SourceMgr.getDecomposedLoc(R.getBegin()); 3856 std::pair<FileID, unsigned> EndLocInfo 3857 = SourceMgr.getDecomposedLoc(R.getEnd()); 3858 3859 // Cannot tokenize across files. 3860 if (BeginLocInfo.first != EndLocInfo.first) 3861 return; 3862 3863 // Create a lexer 3864 bool Invalid = false; 3865 llvm::StringRef Buffer 3866 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3867 if (Invalid) 3868 return; 3869 3870 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3871 CXXUnit->getASTContext().getLangOptions(), 3872 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3873 Lex.SetCommentRetentionState(true); 3874 3875 // Lex tokens until we hit the end of the range. 3876 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3877 llvm::SmallVector<CXToken, 32> CXTokens; 3878 Token Tok; 3879 bool previousWasAt = false; 3880 do { 3881 // Lex the next token 3882 Lex.LexFromRawLexer(Tok); 3883 if (Tok.is(tok::eof)) 3884 break; 3885 3886 // Initialize the CXToken. 3887 CXToken CXTok; 3888 3889 // - Common fields 3890 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3891 CXTok.int_data[2] = Tok.getLength(); 3892 CXTok.int_data[3] = 0; 3893 3894 // - Kind-specific fields 3895 if (Tok.isLiteral()) { 3896 CXTok.int_data[0] = CXToken_Literal; 3897 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3898 } else if (Tok.is(tok::identifier)) { 3899 // Lookup the identifier to determine whether we have a keyword. 3900 std::pair<FileID, unsigned> LocInfo 3901 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3902 bool Invalid = false; 3903 llvm::StringRef Buf 3904 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3905 if (Invalid) 3906 return; 3907 3908 const char *StartPos = Buf.data() + LocInfo.second; 3909 IdentifierInfo *II 3910 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3911 3912 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 3913 CXTok.int_data[0] = CXToken_Keyword; 3914 } 3915 else { 3916 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3917 CXToken_Identifier 3918 : CXToken_Keyword; 3919 } 3920 CXTok.ptr_data = II; 3921 } else if (Tok.is(tok::comment)) { 3922 CXTok.int_data[0] = CXToken_Comment; 3923 CXTok.ptr_data = 0; 3924 } else { 3925 CXTok.int_data[0] = CXToken_Punctuation; 3926 CXTok.ptr_data = 0; 3927 } 3928 CXTokens.push_back(CXTok); 3929 previousWasAt = Tok.is(tok::at); 3930 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3931 3932 if (CXTokens.empty()) 3933 return; 3934 3935 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3936 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3937 *NumTokens = CXTokens.size(); 3938} 3939 3940void clang_disposeTokens(CXTranslationUnit TU, 3941 CXToken *Tokens, unsigned NumTokens) { 3942 free(Tokens); 3943} 3944 3945} // end: extern "C" 3946 3947//===----------------------------------------------------------------------===// 3948// Token annotation APIs. 3949//===----------------------------------------------------------------------===// 3950 3951typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3952static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3953 CXCursor parent, 3954 CXClientData client_data); 3955namespace { 3956class AnnotateTokensWorker { 3957 AnnotateTokensData &Annotated; 3958 CXToken *Tokens; 3959 CXCursor *Cursors; 3960 unsigned NumTokens; 3961 unsigned TokIdx; 3962 unsigned PreprocessingTokIdx; 3963 CursorVisitor AnnotateVis; 3964 SourceManager &SrcMgr; 3965 3966 bool MoreTokens() const { return TokIdx < NumTokens; } 3967 unsigned NextToken() const { return TokIdx; } 3968 void AdvanceToken() { ++TokIdx; } 3969 SourceLocation GetTokenLoc(unsigned tokI) { 3970 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3971 } 3972 3973public: 3974 AnnotateTokensWorker(AnnotateTokensData &annotated, 3975 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3976 CXTranslationUnit tu, SourceRange RegionOfInterest) 3977 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3978 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 3979 AnnotateVis(tu, 3980 AnnotateTokensVisitor, this, 3981 Decl::MaxPCHLevel, RegionOfInterest), 3982 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {} 3983 3984 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3985 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3986 void AnnotateTokens(CXCursor parent); 3987 void AnnotateTokens() { 3988 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU())); 3989 } 3990}; 3991} 3992 3993void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3994 // Walk the AST within the region of interest, annotating tokens 3995 // along the way. 3996 VisitChildren(parent); 3997 3998 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3999 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4000 if (Pos != Annotated.end() && 4001 (clang_isInvalid(Cursors[I].kind) || 4002 Pos->second.kind != CXCursor_PreprocessingDirective)) 4003 Cursors[I] = Pos->second; 4004 } 4005 4006 // Finish up annotating any tokens left. 4007 if (!MoreTokens()) 4008 return; 4009 4010 const CXCursor &C = clang_getNullCursor(); 4011 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 4012 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4013 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 4014 } 4015} 4016 4017enum CXChildVisitResult 4018AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 4019 CXSourceLocation Loc = clang_getCursorLocation(cursor); 4020 SourceRange cursorRange = getRawCursorExtent(cursor); 4021 if (cursorRange.isInvalid()) 4022 return CXChildVisit_Recurse; 4023 4024 if (clang_isPreprocessing(cursor.kind)) { 4025 // For macro instantiations, just note where the beginning of the macro 4026 // instantiation occurs. 4027 if (cursor.kind == CXCursor_MacroInstantiation) { 4028 Annotated[Loc.int_data] = cursor; 4029 return CXChildVisit_Recurse; 4030 } 4031 4032 // Items in the preprocessing record are kept separate from items in 4033 // declarations, so we keep a separate token index. 4034 unsigned SavedTokIdx = TokIdx; 4035 TokIdx = PreprocessingTokIdx; 4036 4037 // Skip tokens up until we catch up to the beginning of the preprocessing 4038 // entry. 4039 while (MoreTokens()) { 4040 const unsigned I = NextToken(); 4041 SourceLocation TokLoc = GetTokenLoc(I); 4042 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4043 case RangeBefore: 4044 AdvanceToken(); 4045 continue; 4046 case RangeAfter: 4047 case RangeOverlap: 4048 break; 4049 } 4050 break; 4051 } 4052 4053 // Look at all of the tokens within this range. 4054 while (MoreTokens()) { 4055 const unsigned I = NextToken(); 4056 SourceLocation TokLoc = GetTokenLoc(I); 4057 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4058 case RangeBefore: 4059 assert(0 && "Infeasible"); 4060 case RangeAfter: 4061 break; 4062 case RangeOverlap: 4063 Cursors[I] = cursor; 4064 AdvanceToken(); 4065 continue; 4066 } 4067 break; 4068 } 4069 4070 // Save the preprocessing token index; restore the non-preprocessing 4071 // token index. 4072 PreprocessingTokIdx = TokIdx; 4073 TokIdx = SavedTokIdx; 4074 return CXChildVisit_Recurse; 4075 } 4076 4077 if (cursorRange.isInvalid()) 4078 return CXChildVisit_Continue; 4079 4080 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 4081 4082 // Adjust the annotated range based specific declarations. 4083 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 4084 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 4085 Decl *D = cxcursor::getCursorDecl(cursor); 4086 // Don't visit synthesized ObjC methods, since they have no syntatic 4087 // representation in the source. 4088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 4089 if (MD->isSynthesized()) 4090 return CXChildVisit_Continue; 4091 } 4092 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4093 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 4094 TypeLoc TL = TI->getTypeLoc(); 4095 SourceLocation TLoc = TL.getSourceRange().getBegin(); 4096 if (TLoc.isValid() && L.isValid() && 4097 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 4098 cursorRange.setBegin(TLoc); 4099 } 4100 } 4101 } 4102 4103 // If the location of the cursor occurs within a macro instantiation, record 4104 // the spelling location of the cursor in our annotation map. We can then 4105 // paper over the token labelings during a post-processing step to try and 4106 // get cursor mappings for tokens that are the *arguments* of a macro 4107 // instantiation. 4108 if (L.isMacroID()) { 4109 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 4110 // Only invalidate the old annotation if it isn't part of a preprocessing 4111 // directive. Here we assume that the default construction of CXCursor 4112 // results in CXCursor.kind being an initialized value (i.e., 0). If 4113 // this isn't the case, we can fix by doing lookup + insertion. 4114 4115 CXCursor &oldC = Annotated[rawEncoding]; 4116 if (!clang_isPreprocessing(oldC.kind)) 4117 oldC = cursor; 4118 } 4119 4120 const enum CXCursorKind K = clang_getCursorKind(parent); 4121 const CXCursor updateC = 4122 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 4123 ? clang_getNullCursor() : parent; 4124 4125 while (MoreTokens()) { 4126 const unsigned I = NextToken(); 4127 SourceLocation TokLoc = GetTokenLoc(I); 4128 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4129 case RangeBefore: 4130 Cursors[I] = updateC; 4131 AdvanceToken(); 4132 continue; 4133 case RangeAfter: 4134 case RangeOverlap: 4135 break; 4136 } 4137 break; 4138 } 4139 4140 // Visit children to get their cursor information. 4141 const unsigned BeforeChildren = NextToken(); 4142 VisitChildren(cursor); 4143 const unsigned AfterChildren = NextToken(); 4144 4145 // Adjust 'Last' to the last token within the extent of the cursor. 4146 while (MoreTokens()) { 4147 const unsigned I = NextToken(); 4148 SourceLocation TokLoc = GetTokenLoc(I); 4149 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4150 case RangeBefore: 4151 assert(0 && "Infeasible"); 4152 case RangeAfter: 4153 break; 4154 case RangeOverlap: 4155 Cursors[I] = updateC; 4156 AdvanceToken(); 4157 continue; 4158 } 4159 break; 4160 } 4161 const unsigned Last = NextToken(); 4162 4163 // Scan the tokens that are at the beginning of the cursor, but are not 4164 // capture by the child cursors. 4165 4166 // For AST elements within macros, rely on a post-annotate pass to 4167 // to correctly annotate the tokens with cursors. Otherwise we can 4168 // get confusing results of having tokens that map to cursors that really 4169 // are expanded by an instantiation. 4170 if (L.isMacroID()) 4171 cursor = clang_getNullCursor(); 4172 4173 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 4174 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 4175 break; 4176 4177 Cursors[I] = cursor; 4178 } 4179 // Scan the tokens that are at the end of the cursor, but are not captured 4180 // but the child cursors. 4181 for (unsigned I = AfterChildren; I != Last; ++I) 4182 Cursors[I] = cursor; 4183 4184 TokIdx = Last; 4185 return CXChildVisit_Continue; 4186} 4187 4188static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4189 CXCursor parent, 4190 CXClientData client_data) { 4191 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 4192} 4193 4194// This gets run a separate thread to avoid stack blowout. 4195static void runAnnotateTokensWorker(void *UserData) { 4196 ((AnnotateTokensWorker*)UserData)->AnnotateTokens(); 4197} 4198 4199extern "C" { 4200 4201void clang_annotateTokens(CXTranslationUnit TU, 4202 CXToken *Tokens, unsigned NumTokens, 4203 CXCursor *Cursors) { 4204 4205 if (NumTokens == 0 || !Tokens || !Cursors) 4206 return; 4207 4208 // Any token we don't specifically annotate will have a NULL cursor. 4209 CXCursor C = clang_getNullCursor(); 4210 for (unsigned I = 0; I != NumTokens; ++I) 4211 Cursors[I] = C; 4212 4213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4214 if (!CXXUnit) 4215 return; 4216 4217 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4218 4219 // Determine the region of interest, which contains all of the tokens. 4220 SourceRange RegionOfInterest; 4221 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 4222 clang_getTokenLocation(TU, Tokens[0]))); 4223 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 4224 clang_getTokenLocation(TU, 4225 Tokens[NumTokens - 1]))); 4226 4227 // A mapping from the source locations found when re-lexing or traversing the 4228 // region of interest to the corresponding cursors. 4229 AnnotateTokensData Annotated; 4230 4231 // Relex the tokens within the source range to look for preprocessing 4232 // directives. 4233 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4234 std::pair<FileID, unsigned> BeginLocInfo 4235 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 4236 std::pair<FileID, unsigned> EndLocInfo 4237 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 4238 4239 llvm::StringRef Buffer; 4240 bool Invalid = false; 4241 if (BeginLocInfo.first == EndLocInfo.first && 4242 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 4243 !Invalid) { 4244 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4245 CXXUnit->getASTContext().getLangOptions(), 4246 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 4247 Buffer.end()); 4248 Lex.SetCommentRetentionState(true); 4249 4250 // Lex tokens in raw mode until we hit the end of the range, to avoid 4251 // entering #includes or expanding macros. 4252 while (true) { 4253 Token Tok; 4254 Lex.LexFromRawLexer(Tok); 4255 4256 reprocess: 4257 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 4258 // We have found a preprocessing directive. Gobble it up so that we 4259 // don't see it while preprocessing these tokens later, but keep track 4260 // of all of the token locations inside this preprocessing directive so 4261 // that we can annotate them appropriately. 4262 // 4263 // FIXME: Some simple tests here could identify macro definitions and 4264 // #undefs, to provide specific cursor kinds for those. 4265 std::vector<SourceLocation> Locations; 4266 do { 4267 Locations.push_back(Tok.getLocation()); 4268 Lex.LexFromRawLexer(Tok); 4269 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 4270 4271 using namespace cxcursor; 4272 CXCursor Cursor 4273 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 4274 Locations.back()), 4275 TU); 4276 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 4277 Annotated[Locations[I].getRawEncoding()] = Cursor; 4278 } 4279 4280 if (Tok.isAtStartOfLine()) 4281 goto reprocess; 4282 4283 continue; 4284 } 4285 4286 if (Tok.is(tok::eof)) 4287 break; 4288 } 4289 } 4290 4291 // Annotate all of the source locations in the region of interest that map to 4292 // a specific cursor. 4293 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 4294 TU, RegionOfInterest); 4295 4296 // Run the worker within a CrashRecoveryContext. 4297 // FIXME: We use a ridiculous stack size here because the data-recursion 4298 // algorithm uses a large stack frame than the non-data recursive version, 4299 // and AnnotationTokensWorker currently transforms the data-recursion 4300 // algorithm back into a traditional recursion by explicitly calling 4301 // VisitChildren(). We will need to remove this explicit recursive call. 4302 llvm::CrashRecoveryContext CRC; 4303 if (!RunSafely(CRC, runAnnotateTokensWorker, &W, 4304 GetSafetyThreadStackSize() * 2)) { 4305 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 4306 } 4307} 4308} // end: extern "C" 4309 4310//===----------------------------------------------------------------------===// 4311// Operations for querying linkage of a cursor. 4312//===----------------------------------------------------------------------===// 4313 4314extern "C" { 4315CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 4316 if (!clang_isDeclaration(cursor.kind)) 4317 return CXLinkage_Invalid; 4318 4319 Decl *D = cxcursor::getCursorDecl(cursor); 4320 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 4321 switch (ND->getLinkage()) { 4322 case NoLinkage: return CXLinkage_NoLinkage; 4323 case InternalLinkage: return CXLinkage_Internal; 4324 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 4325 case ExternalLinkage: return CXLinkage_External; 4326 }; 4327 4328 return CXLinkage_Invalid; 4329} 4330} // end: extern "C" 4331 4332//===----------------------------------------------------------------------===// 4333// Operations for querying language of a cursor. 4334//===----------------------------------------------------------------------===// 4335 4336static CXLanguageKind getDeclLanguage(const Decl *D) { 4337 switch (D->getKind()) { 4338 default: 4339 break; 4340 case Decl::ImplicitParam: 4341 case Decl::ObjCAtDefsField: 4342 case Decl::ObjCCategory: 4343 case Decl::ObjCCategoryImpl: 4344 case Decl::ObjCClass: 4345 case Decl::ObjCCompatibleAlias: 4346 case Decl::ObjCForwardProtocol: 4347 case Decl::ObjCImplementation: 4348 case Decl::ObjCInterface: 4349 case Decl::ObjCIvar: 4350 case Decl::ObjCMethod: 4351 case Decl::ObjCProperty: 4352 case Decl::ObjCPropertyImpl: 4353 case Decl::ObjCProtocol: 4354 return CXLanguage_ObjC; 4355 case Decl::CXXConstructor: 4356 case Decl::CXXConversion: 4357 case Decl::CXXDestructor: 4358 case Decl::CXXMethod: 4359 case Decl::CXXRecord: 4360 case Decl::ClassTemplate: 4361 case Decl::ClassTemplatePartialSpecialization: 4362 case Decl::ClassTemplateSpecialization: 4363 case Decl::Friend: 4364 case Decl::FriendTemplate: 4365 case Decl::FunctionTemplate: 4366 case Decl::LinkageSpec: 4367 case Decl::Namespace: 4368 case Decl::NamespaceAlias: 4369 case Decl::NonTypeTemplateParm: 4370 case Decl::StaticAssert: 4371 case Decl::TemplateTemplateParm: 4372 case Decl::TemplateTypeParm: 4373 case Decl::UnresolvedUsingTypename: 4374 case Decl::UnresolvedUsingValue: 4375 case Decl::Using: 4376 case Decl::UsingDirective: 4377 case Decl::UsingShadow: 4378 return CXLanguage_CPlusPlus; 4379 } 4380 4381 return CXLanguage_C; 4382} 4383 4384extern "C" { 4385 4386enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 4387 if (clang_isDeclaration(cursor.kind)) 4388 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 4389 if (D->hasAttr<UnavailableAttr>() || 4390 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 4391 return CXAvailability_Available; 4392 4393 if (D->hasAttr<DeprecatedAttr>()) 4394 return CXAvailability_Deprecated; 4395 } 4396 4397 return CXAvailability_Available; 4398} 4399 4400CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4401 if (clang_isDeclaration(cursor.kind)) 4402 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4403 4404 return CXLanguage_Invalid; 4405} 4406 4407CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4408 if (clang_isDeclaration(cursor.kind)) { 4409 if (Decl *D = getCursorDecl(cursor)) { 4410 DeclContext *DC = D->getDeclContext(); 4411 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor)); 4412 } 4413 } 4414 4415 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4416 if (Decl *D = getCursorDecl(cursor)) 4417 return MakeCXCursor(D, getCursorTU(cursor)); 4418 } 4419 4420 return clang_getNullCursor(); 4421} 4422 4423CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 4424 if (clang_isDeclaration(cursor.kind)) { 4425 if (Decl *D = getCursorDecl(cursor)) { 4426 DeclContext *DC = D->getLexicalDeclContext(); 4427 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor)); 4428 } 4429 } 4430 4431 // FIXME: Note that we can't easily compute the lexical context of a 4432 // statement or expression, so we return nothing. 4433 return clang_getNullCursor(); 4434} 4435 4436static void CollectOverriddenMethods(DeclContext *Ctx, 4437 ObjCMethodDecl *Method, 4438 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 4439 if (!Ctx) 4440 return; 4441 4442 // If we have a class or category implementation, jump straight to the 4443 // interface. 4444 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 4445 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 4446 4447 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 4448 if (!Container) 4449 return; 4450 4451 // Check whether we have a matching method at this level. 4452 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 4453 Method->isInstanceMethod())) 4454 if (Method != Overridden) { 4455 // We found an override at this level; there is no need to look 4456 // into other protocols or categories. 4457 Methods.push_back(Overridden); 4458 return; 4459 } 4460 4461 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4462 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 4463 PEnd = Protocol->protocol_end(); 4464 P != PEnd; ++P) 4465 CollectOverriddenMethods(*P, Method, Methods); 4466 } 4467 4468 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 4469 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 4470 PEnd = Category->protocol_end(); 4471 P != PEnd; ++P) 4472 CollectOverriddenMethods(*P, Method, Methods); 4473 } 4474 4475 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4476 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 4477 PEnd = Interface->protocol_end(); 4478 P != PEnd; ++P) 4479 CollectOverriddenMethods(*P, Method, Methods); 4480 4481 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 4482 Category; Category = Category->getNextClassCategory()) 4483 CollectOverriddenMethods(Category, Method, Methods); 4484 4485 // We only look into the superclass if we haven't found anything yet. 4486 if (Methods.empty()) 4487 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 4488 return CollectOverriddenMethods(Super, Method, Methods); 4489 } 4490} 4491 4492void clang_getOverriddenCursors(CXCursor cursor, 4493 CXCursor **overridden, 4494 unsigned *num_overridden) { 4495 if (overridden) 4496 *overridden = 0; 4497 if (num_overridden) 4498 *num_overridden = 0; 4499 if (!overridden || !num_overridden) 4500 return; 4501 4502 if (!clang_isDeclaration(cursor.kind)) 4503 return; 4504 4505 Decl *D = getCursorDecl(cursor); 4506 if (!D) 4507 return; 4508 4509 // Handle C++ member functions. 4510 CXTranslationUnit TU = getCursorTU(cursor); 4511 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 4512 *num_overridden = CXXMethod->size_overridden_methods(); 4513 if (!*num_overridden) 4514 return; 4515 4516 *overridden = new CXCursor [*num_overridden]; 4517 unsigned I = 0; 4518 for (CXXMethodDecl::method_iterator 4519 M = CXXMethod->begin_overridden_methods(), 4520 MEnd = CXXMethod->end_overridden_methods(); 4521 M != MEnd; (void)++M, ++I) 4522 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU); 4523 return; 4524 } 4525 4526 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 4527 if (!Method) 4528 return; 4529 4530 // Handle Objective-C methods. 4531 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 4532 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 4533 4534 if (Methods.empty()) 4535 return; 4536 4537 *num_overridden = Methods.size(); 4538 *overridden = new CXCursor [Methods.size()]; 4539 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 4540 (*overridden)[I] = MakeCXCursor(Methods[I], TU); 4541} 4542 4543void clang_disposeOverriddenCursors(CXCursor *overridden) { 4544 delete [] overridden; 4545} 4546 4547CXFile clang_getIncludedFile(CXCursor cursor) { 4548 if (cursor.kind != CXCursor_InclusionDirective) 4549 return 0; 4550 4551 InclusionDirective *ID = getCursorInclusionDirective(cursor); 4552 return (void *)ID->getFile(); 4553} 4554 4555} // end: extern "C" 4556 4557 4558//===----------------------------------------------------------------------===// 4559// C++ AST instrospection. 4560//===----------------------------------------------------------------------===// 4561 4562extern "C" { 4563unsigned clang_CXXMethod_isStatic(CXCursor C) { 4564 if (!clang_isDeclaration(C.kind)) 4565 return 0; 4566 4567 CXXMethodDecl *Method = 0; 4568 Decl *D = cxcursor::getCursorDecl(C); 4569 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 4570 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 4571 else 4572 Method = dyn_cast_or_null<CXXMethodDecl>(D); 4573 return (Method && Method->isStatic()) ? 1 : 0; 4574} 4575 4576} // end: extern "C" 4577 4578//===----------------------------------------------------------------------===// 4579// Attribute introspection. 4580//===----------------------------------------------------------------------===// 4581 4582extern "C" { 4583CXType clang_getIBOutletCollectionType(CXCursor C) { 4584 if (C.kind != CXCursor_IBOutletCollectionAttr) 4585 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 4586 4587 IBOutletCollectionAttr *A = 4588 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 4589 4590 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 4591} 4592} // end: extern "C" 4593 4594//===----------------------------------------------------------------------===// 4595// Misc. utility functions. 4596//===----------------------------------------------------------------------===// 4597 4598/// Default to using an 8 MB stack size on "safety" threads. 4599static unsigned SafetyStackThreadSize = 8 << 20; 4600 4601namespace clang { 4602 4603bool RunSafely(llvm::CrashRecoveryContext &CRC, 4604 void (*Fn)(void*), void *UserData, 4605 unsigned Size) { 4606 if (!Size) 4607 Size = GetSafetyThreadStackSize(); 4608 if (Size) 4609 return CRC.RunSafelyOnThread(Fn, UserData, Size); 4610 return CRC.RunSafely(Fn, UserData); 4611} 4612 4613unsigned GetSafetyThreadStackSize() { 4614 return SafetyStackThreadSize; 4615} 4616 4617void SetSafetyThreadStackSize(unsigned Value) { 4618 SafetyStackThreadSize = Value; 4619} 4620 4621} 4622 4623extern "C" { 4624 4625CXString clang_getClangVersion() { 4626 return createCXString(getClangFullVersion()); 4627} 4628 4629} // end: extern "C" 4630