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