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