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