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