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