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