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