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