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