CIndex.cpp revision 826faa22bae112e01293a58534a40711043cce65
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 = Loc; 2481 if (SpellLoc.isMacroID()) { 2482 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc); 2483 if (SimpleSpellingLoc.isFileID() && 2484 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first)) 2485 SpellLoc = SimpleSpellingLoc; 2486 else 2487 SpellLoc = SM.getInstantiationLoc(SpellLoc); 2488 } 2489 2490 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); 2491 FileID FID = LocInfo.first; 2492 unsigned FileOffset = LocInfo.second; 2493 2494 if (file) 2495 *file = (void *)SM.getFileEntryForID(FID); 2496 if (line) 2497 *line = SM.getLineNumber(FID, FileOffset); 2498 if (column) 2499 *column = SM.getColumnNumber(FID, FileOffset); 2500 if (offset) 2501 *offset = FileOffset; 2502} 2503 2504CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2505 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2506 range.begin_int_data }; 2507 return Result; 2508} 2509 2510CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2511 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2512 range.end_int_data }; 2513 return Result; 2514} 2515 2516} // end: extern "C" 2517 2518//===----------------------------------------------------------------------===// 2519// CXFile Operations. 2520//===----------------------------------------------------------------------===// 2521 2522extern "C" { 2523CXString clang_getFileName(CXFile SFile) { 2524 if (!SFile) 2525 return createCXString(NULL); 2526 2527 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2528 return createCXString(FEnt->getName()); 2529} 2530 2531time_t clang_getFileTime(CXFile SFile) { 2532 if (!SFile) 2533 return 0; 2534 2535 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2536 return FEnt->getModificationTime(); 2537} 2538 2539CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2540 if (!tu) 2541 return 0; 2542 2543 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2544 2545 FileManager &FMgr = CXXUnit->getFileManager(); 2546 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name), 2547 CXXUnit->getFileSystemOpts()); 2548 return const_cast<FileEntry *>(File); 2549} 2550 2551} // end: extern "C" 2552 2553//===----------------------------------------------------------------------===// 2554// CXCursor Operations. 2555//===----------------------------------------------------------------------===// 2556 2557static Decl *getDeclFromExpr(Stmt *E) { 2558 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2559 return getDeclFromExpr(CE->getSubExpr()); 2560 2561 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2562 return RefExpr->getDecl(); 2563 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2564 return RefExpr->getDecl(); 2565 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2566 return ME->getMemberDecl(); 2567 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2568 return RE->getDecl(); 2569 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2570 return PRE->getProperty(); 2571 2572 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2573 return getDeclFromExpr(CE->getCallee()); 2574 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E)) 2575 if (!CE->isElidable()) 2576 return CE->getConstructor(); 2577 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2578 return OME->getMethodDecl(); 2579 2580 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2581 return PE->getProtocol(); 2582 2583 return 0; 2584} 2585 2586static SourceLocation getLocationFromExpr(Expr *E) { 2587 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2588 return /*FIXME:*/Msg->getLeftLoc(); 2589 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2590 return DRE->getLocation(); 2591 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2592 return RefExpr->getLocation(); 2593 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2594 return Member->getMemberLoc(); 2595 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2596 return Ivar->getLocation(); 2597 return E->getLocStart(); 2598} 2599 2600extern "C" { 2601 2602unsigned clang_visitChildren(CXCursor parent, 2603 CXCursorVisitor visitor, 2604 CXClientData client_data) { 2605 ASTUnit *CXXUnit = getCursorASTUnit(parent); 2606 2607 CursorVisitor CursorVis(CXXUnit, visitor, client_data, 2608 CXXUnit->getMaxPCHLevel()); 2609 return CursorVis.VisitChildren(parent); 2610} 2611 2612#ifndef __has_feature 2613#define __has_feature(x) 0 2614#endif 2615#if __has_feature(blocks) 2616typedef enum CXChildVisitResult 2617 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 2618 2619static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2620 CXClientData client_data) { 2621 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2622 return block(cursor, parent); 2623} 2624#else 2625// If we are compiled with a compiler that doesn't have native blocks support, 2626// define and call the block manually, so the 2627typedef struct _CXChildVisitResult 2628{ 2629 void *isa; 2630 int flags; 2631 int reserved; 2632 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 2633 CXCursor); 2634} *CXCursorVisitorBlock; 2635 2636static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2637 CXClientData client_data) { 2638 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2639 return block->invoke(block, cursor, parent); 2640} 2641#endif 2642 2643 2644unsigned clang_visitChildrenWithBlock(CXCursor parent, 2645 CXCursorVisitorBlock block) { 2646 return clang_visitChildren(parent, visitWithBlock, block); 2647} 2648 2649static CXString getDeclSpelling(Decl *D) { 2650 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2651 if (!ND) 2652 return createCXString(""); 2653 2654 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2655 return createCXString(OMD->getSelector().getAsString()); 2656 2657 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2658 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2659 // and returns different names. NamedDecl returns the class name and 2660 // ObjCCategoryImplDecl returns the category name. 2661 return createCXString(CIMP->getIdentifier()->getNameStart()); 2662 2663 if (isa<UsingDirectiveDecl>(D)) 2664 return createCXString(""); 2665 2666 llvm::SmallString<1024> S; 2667 llvm::raw_svector_ostream os(S); 2668 ND->printName(os); 2669 2670 return createCXString(os.str()); 2671} 2672 2673CXString clang_getCursorSpelling(CXCursor C) { 2674 if (clang_isTranslationUnit(C.kind)) 2675 return clang_getTranslationUnitSpelling(C.data[2]); 2676 2677 if (clang_isReference(C.kind)) { 2678 switch (C.kind) { 2679 case CXCursor_ObjCSuperClassRef: { 2680 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2681 return createCXString(Super->getIdentifier()->getNameStart()); 2682 } 2683 case CXCursor_ObjCClassRef: { 2684 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2685 return createCXString(Class->getIdentifier()->getNameStart()); 2686 } 2687 case CXCursor_ObjCProtocolRef: { 2688 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2689 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2690 return createCXString(OID->getIdentifier()->getNameStart()); 2691 } 2692 case CXCursor_CXXBaseSpecifier: { 2693 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2694 return createCXString(B->getType().getAsString()); 2695 } 2696 case CXCursor_TypeRef: { 2697 TypeDecl *Type = getCursorTypeRef(C).first; 2698 assert(Type && "Missing type decl"); 2699 2700 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2701 getAsString()); 2702 } 2703 case CXCursor_TemplateRef: { 2704 TemplateDecl *Template = getCursorTemplateRef(C).first; 2705 assert(Template && "Missing template decl"); 2706 2707 return createCXString(Template->getNameAsString()); 2708 } 2709 2710 case CXCursor_NamespaceRef: { 2711 NamedDecl *NS = getCursorNamespaceRef(C).first; 2712 assert(NS && "Missing namespace decl"); 2713 2714 return createCXString(NS->getNameAsString()); 2715 } 2716 2717 case CXCursor_MemberRef: { 2718 FieldDecl *Field = getCursorMemberRef(C).first; 2719 assert(Field && "Missing member decl"); 2720 2721 return createCXString(Field->getNameAsString()); 2722 } 2723 2724 case CXCursor_LabelRef: { 2725 LabelStmt *Label = getCursorLabelRef(C).first; 2726 assert(Label && "Missing label"); 2727 2728 return createCXString(Label->getID()->getName()); 2729 } 2730 2731 case CXCursor_OverloadedDeclRef: { 2732 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 2733 if (Decl *D = Storage.dyn_cast<Decl *>()) { 2734 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 2735 return createCXString(ND->getNameAsString()); 2736 return createCXString(""); 2737 } 2738 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 2739 return createCXString(E->getName().getAsString()); 2740 OverloadedTemplateStorage *Ovl 2741 = Storage.get<OverloadedTemplateStorage*>(); 2742 if (Ovl->size() == 0) 2743 return createCXString(""); 2744 return createCXString((*Ovl->begin())->getNameAsString()); 2745 } 2746 2747 default: 2748 return createCXString("<not implemented>"); 2749 } 2750 } 2751 2752 if (clang_isExpression(C.kind)) { 2753 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2754 if (D) 2755 return getDeclSpelling(D); 2756 return createCXString(""); 2757 } 2758 2759 if (clang_isStatement(C.kind)) { 2760 Stmt *S = getCursorStmt(C); 2761 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 2762 return createCXString(Label->getID()->getName()); 2763 2764 return createCXString(""); 2765 } 2766 2767 if (C.kind == CXCursor_MacroInstantiation) 2768 return createCXString(getCursorMacroInstantiation(C)->getName() 2769 ->getNameStart()); 2770 2771 if (C.kind == CXCursor_MacroDefinition) 2772 return createCXString(getCursorMacroDefinition(C)->getName() 2773 ->getNameStart()); 2774 2775 if (C.kind == CXCursor_InclusionDirective) 2776 return createCXString(getCursorInclusionDirective(C)->getFileName()); 2777 2778 if (clang_isDeclaration(C.kind)) 2779 return getDeclSpelling(getCursorDecl(C)); 2780 2781 return createCXString(""); 2782} 2783 2784CXString clang_getCursorDisplayName(CXCursor C) { 2785 if (!clang_isDeclaration(C.kind)) 2786 return clang_getCursorSpelling(C); 2787 2788 Decl *D = getCursorDecl(C); 2789 if (!D) 2790 return createCXString(""); 2791 2792 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 2793 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 2794 D = FunTmpl->getTemplatedDecl(); 2795 2796 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 2797 llvm::SmallString<64> Str; 2798 llvm::raw_svector_ostream OS(Str); 2799 OS << Function->getNameAsString(); 2800 if (Function->getPrimaryTemplate()) 2801 OS << "<>"; 2802 OS << "("; 2803 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 2804 if (I) 2805 OS << ", "; 2806 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 2807 } 2808 2809 if (Function->isVariadic()) { 2810 if (Function->getNumParams()) 2811 OS << ", "; 2812 OS << "..."; 2813 } 2814 OS << ")"; 2815 return createCXString(OS.str()); 2816 } 2817 2818 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 2819 llvm::SmallString<64> Str; 2820 llvm::raw_svector_ostream OS(Str); 2821 OS << ClassTemplate->getNameAsString(); 2822 OS << "<"; 2823 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 2824 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2825 if (I) 2826 OS << ", "; 2827 2828 NamedDecl *Param = Params->getParam(I); 2829 if (Param->getIdentifier()) { 2830 OS << Param->getIdentifier()->getName(); 2831 continue; 2832 } 2833 2834 // There is no parameter name, which makes this tricky. Try to come up 2835 // with something useful that isn't too long. 2836 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2837 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 2838 else if (NonTypeTemplateParmDecl *NTTP 2839 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2840 OS << NTTP->getType().getAsString(Policy); 2841 else 2842 OS << "template<...> class"; 2843 } 2844 2845 OS << ">"; 2846 return createCXString(OS.str()); 2847 } 2848 2849 if (ClassTemplateSpecializationDecl *ClassSpec 2850 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 2851 // If the type was explicitly written, use that. 2852 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 2853 return createCXString(TSInfo->getType().getAsString(Policy)); 2854 2855 llvm::SmallString<64> Str; 2856 llvm::raw_svector_ostream OS(Str); 2857 OS << ClassSpec->getNameAsString(); 2858 OS << TemplateSpecializationType::PrintTemplateArgumentList( 2859 ClassSpec->getTemplateArgs().data(), 2860 ClassSpec->getTemplateArgs().size(), 2861 Policy); 2862 return createCXString(OS.str()); 2863 } 2864 2865 return clang_getCursorSpelling(C); 2866} 2867 2868CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2869 switch (Kind) { 2870 case CXCursor_FunctionDecl: 2871 return createCXString("FunctionDecl"); 2872 case CXCursor_TypedefDecl: 2873 return createCXString("TypedefDecl"); 2874 case CXCursor_EnumDecl: 2875 return createCXString("EnumDecl"); 2876 case CXCursor_EnumConstantDecl: 2877 return createCXString("EnumConstantDecl"); 2878 case CXCursor_StructDecl: 2879 return createCXString("StructDecl"); 2880 case CXCursor_UnionDecl: 2881 return createCXString("UnionDecl"); 2882 case CXCursor_ClassDecl: 2883 return createCXString("ClassDecl"); 2884 case CXCursor_FieldDecl: 2885 return createCXString("FieldDecl"); 2886 case CXCursor_VarDecl: 2887 return createCXString("VarDecl"); 2888 case CXCursor_ParmDecl: 2889 return createCXString("ParmDecl"); 2890 case CXCursor_ObjCInterfaceDecl: 2891 return createCXString("ObjCInterfaceDecl"); 2892 case CXCursor_ObjCCategoryDecl: 2893 return createCXString("ObjCCategoryDecl"); 2894 case CXCursor_ObjCProtocolDecl: 2895 return createCXString("ObjCProtocolDecl"); 2896 case CXCursor_ObjCPropertyDecl: 2897 return createCXString("ObjCPropertyDecl"); 2898 case CXCursor_ObjCIvarDecl: 2899 return createCXString("ObjCIvarDecl"); 2900 case CXCursor_ObjCInstanceMethodDecl: 2901 return createCXString("ObjCInstanceMethodDecl"); 2902 case CXCursor_ObjCClassMethodDecl: 2903 return createCXString("ObjCClassMethodDecl"); 2904 case CXCursor_ObjCImplementationDecl: 2905 return createCXString("ObjCImplementationDecl"); 2906 case CXCursor_ObjCCategoryImplDecl: 2907 return createCXString("ObjCCategoryImplDecl"); 2908 case CXCursor_CXXMethod: 2909 return createCXString("CXXMethod"); 2910 case CXCursor_UnexposedDecl: 2911 return createCXString("UnexposedDecl"); 2912 case CXCursor_ObjCSuperClassRef: 2913 return createCXString("ObjCSuperClassRef"); 2914 case CXCursor_ObjCProtocolRef: 2915 return createCXString("ObjCProtocolRef"); 2916 case CXCursor_ObjCClassRef: 2917 return createCXString("ObjCClassRef"); 2918 case CXCursor_TypeRef: 2919 return createCXString("TypeRef"); 2920 case CXCursor_TemplateRef: 2921 return createCXString("TemplateRef"); 2922 case CXCursor_NamespaceRef: 2923 return createCXString("NamespaceRef"); 2924 case CXCursor_MemberRef: 2925 return createCXString("MemberRef"); 2926 case CXCursor_LabelRef: 2927 return createCXString("LabelRef"); 2928 case CXCursor_OverloadedDeclRef: 2929 return createCXString("OverloadedDeclRef"); 2930 case CXCursor_UnexposedExpr: 2931 return createCXString("UnexposedExpr"); 2932 case CXCursor_BlockExpr: 2933 return createCXString("BlockExpr"); 2934 case CXCursor_DeclRefExpr: 2935 return createCXString("DeclRefExpr"); 2936 case CXCursor_MemberRefExpr: 2937 return createCXString("MemberRefExpr"); 2938 case CXCursor_CallExpr: 2939 return createCXString("CallExpr"); 2940 case CXCursor_ObjCMessageExpr: 2941 return createCXString("ObjCMessageExpr"); 2942 case CXCursor_UnexposedStmt: 2943 return createCXString("UnexposedStmt"); 2944 case CXCursor_LabelStmt: 2945 return createCXString("LabelStmt"); 2946 case CXCursor_InvalidFile: 2947 return createCXString("InvalidFile"); 2948 case CXCursor_InvalidCode: 2949 return createCXString("InvalidCode"); 2950 case CXCursor_NoDeclFound: 2951 return createCXString("NoDeclFound"); 2952 case CXCursor_NotImplemented: 2953 return createCXString("NotImplemented"); 2954 case CXCursor_TranslationUnit: 2955 return createCXString("TranslationUnit"); 2956 case CXCursor_UnexposedAttr: 2957 return createCXString("UnexposedAttr"); 2958 case CXCursor_IBActionAttr: 2959 return createCXString("attribute(ibaction)"); 2960 case CXCursor_IBOutletAttr: 2961 return createCXString("attribute(iboutlet)"); 2962 case CXCursor_IBOutletCollectionAttr: 2963 return createCXString("attribute(iboutletcollection)"); 2964 case CXCursor_PreprocessingDirective: 2965 return createCXString("preprocessing directive"); 2966 case CXCursor_MacroDefinition: 2967 return createCXString("macro definition"); 2968 case CXCursor_MacroInstantiation: 2969 return createCXString("macro instantiation"); 2970 case CXCursor_InclusionDirective: 2971 return createCXString("inclusion directive"); 2972 case CXCursor_Namespace: 2973 return createCXString("Namespace"); 2974 case CXCursor_LinkageSpec: 2975 return createCXString("LinkageSpec"); 2976 case CXCursor_CXXBaseSpecifier: 2977 return createCXString("C++ base class specifier"); 2978 case CXCursor_Constructor: 2979 return createCXString("CXXConstructor"); 2980 case CXCursor_Destructor: 2981 return createCXString("CXXDestructor"); 2982 case CXCursor_ConversionFunction: 2983 return createCXString("CXXConversion"); 2984 case CXCursor_TemplateTypeParameter: 2985 return createCXString("TemplateTypeParameter"); 2986 case CXCursor_NonTypeTemplateParameter: 2987 return createCXString("NonTypeTemplateParameter"); 2988 case CXCursor_TemplateTemplateParameter: 2989 return createCXString("TemplateTemplateParameter"); 2990 case CXCursor_FunctionTemplate: 2991 return createCXString("FunctionTemplate"); 2992 case CXCursor_ClassTemplate: 2993 return createCXString("ClassTemplate"); 2994 case CXCursor_ClassTemplatePartialSpecialization: 2995 return createCXString("ClassTemplatePartialSpecialization"); 2996 case CXCursor_NamespaceAlias: 2997 return createCXString("NamespaceAlias"); 2998 case CXCursor_UsingDirective: 2999 return createCXString("UsingDirective"); 3000 case CXCursor_UsingDeclaration: 3001 return createCXString("UsingDeclaration"); 3002 } 3003 3004 llvm_unreachable("Unhandled CXCursorKind"); 3005 return createCXString(NULL); 3006} 3007 3008enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3009 CXCursor parent, 3010 CXClientData client_data) { 3011 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 3012 3013 // If our current best cursor is the construction of a temporary object, 3014 // don't replace that cursor with a type reference, because we want 3015 // clang_getCursor() to point at the constructor. 3016 if (clang_isExpression(BestCursor->kind) && 3017 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3018 cursor.kind == CXCursor_TypeRef) 3019 return CXChildVisit_Recurse; 3020 3021 *BestCursor = cursor; 3022 return CXChildVisit_Recurse; 3023} 3024 3025CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3026 if (!TU) 3027 return clang_getNullCursor(); 3028 3029 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3030 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3031 3032 // Translate the given source location to make it point at the beginning of 3033 // the token under the cursor. 3034 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3035 3036 // Guard against an invalid SourceLocation, or we may assert in one 3037 // of the following calls. 3038 if (SLoc.isInvalid()) 3039 return clang_getNullCursor(); 3040 3041 bool Logging = getenv("LIBCLANG_LOGGING"); 3042 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 3043 CXXUnit->getASTContext().getLangOptions()); 3044 3045 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 3046 if (SLoc.isValid()) { 3047 // FIXME: Would be great to have a "hint" cursor, then walk from that 3048 // hint cursor upward until we find a cursor whose source range encloses 3049 // the region of interest, rather than starting from the translation unit. 3050 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); 3051 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, 3052 Decl::MaxPCHLevel, SourceLocation(SLoc)); 3053 CursorVis.VisitChildren(Parent); 3054 } 3055 3056 if (Logging) { 3057 CXFile SearchFile; 3058 unsigned SearchLine, SearchColumn; 3059 CXFile ResultFile; 3060 unsigned ResultLine, ResultColumn; 3061 CXString SearchFileName, ResultFileName, KindSpelling; 3062 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3063 3064 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 3065 0); 3066 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine, 3067 &ResultColumn, 0); 3068 SearchFileName = clang_getFileName(SearchFile); 3069 ResultFileName = clang_getFileName(ResultFile); 3070 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3071 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n", 3072 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3073 clang_getCString(KindSpelling), 3074 clang_getCString(ResultFileName), ResultLine, ResultColumn); 3075 clang_disposeString(SearchFileName); 3076 clang_disposeString(ResultFileName); 3077 clang_disposeString(KindSpelling); 3078 } 3079 3080 return Result; 3081} 3082 3083CXCursor clang_getNullCursor(void) { 3084 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3085} 3086 3087unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3088 return X == Y; 3089} 3090 3091unsigned clang_isInvalid(enum CXCursorKind K) { 3092 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3093} 3094 3095unsigned clang_isDeclaration(enum CXCursorKind K) { 3096 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 3097} 3098 3099unsigned clang_isReference(enum CXCursorKind K) { 3100 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3101} 3102 3103unsigned clang_isExpression(enum CXCursorKind K) { 3104 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3105} 3106 3107unsigned clang_isStatement(enum CXCursorKind K) { 3108 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3109} 3110 3111unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3112 return K == CXCursor_TranslationUnit; 3113} 3114 3115unsigned clang_isPreprocessing(enum CXCursorKind K) { 3116 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3117} 3118 3119unsigned clang_isUnexposed(enum CXCursorKind K) { 3120 switch (K) { 3121 case CXCursor_UnexposedDecl: 3122 case CXCursor_UnexposedExpr: 3123 case CXCursor_UnexposedStmt: 3124 case CXCursor_UnexposedAttr: 3125 return true; 3126 default: 3127 return false; 3128 } 3129} 3130 3131CXCursorKind clang_getCursorKind(CXCursor C) { 3132 return C.kind; 3133} 3134 3135CXSourceLocation clang_getCursorLocation(CXCursor C) { 3136 if (clang_isReference(C.kind)) { 3137 switch (C.kind) { 3138 case CXCursor_ObjCSuperClassRef: { 3139 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3140 = getCursorObjCSuperClassRef(C); 3141 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3142 } 3143 3144 case CXCursor_ObjCProtocolRef: { 3145 std::pair<ObjCProtocolDecl *, SourceLocation> P 3146 = getCursorObjCProtocolRef(C); 3147 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3148 } 3149 3150 case CXCursor_ObjCClassRef: { 3151 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3152 = getCursorObjCClassRef(C); 3153 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3154 } 3155 3156 case CXCursor_TypeRef: { 3157 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3158 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3159 } 3160 3161 case CXCursor_TemplateRef: { 3162 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3163 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3164 } 3165 3166 case CXCursor_NamespaceRef: { 3167 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3168 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3169 } 3170 3171 case CXCursor_MemberRef: { 3172 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3173 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3174 } 3175 3176 case CXCursor_CXXBaseSpecifier: { 3177 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3178 if (!BaseSpec) 3179 return clang_getNullLocation(); 3180 3181 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3182 return cxloc::translateSourceLocation(getCursorContext(C), 3183 TSInfo->getTypeLoc().getBeginLoc()); 3184 3185 return cxloc::translateSourceLocation(getCursorContext(C), 3186 BaseSpec->getSourceRange().getBegin()); 3187 } 3188 3189 case CXCursor_LabelRef: { 3190 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3191 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3192 } 3193 3194 case CXCursor_OverloadedDeclRef: 3195 return cxloc::translateSourceLocation(getCursorContext(C), 3196 getCursorOverloadedDeclRef(C).second); 3197 3198 default: 3199 // FIXME: Need a way to enumerate all non-reference cases. 3200 llvm_unreachable("Missed a reference kind"); 3201 } 3202 } 3203 3204 if (clang_isExpression(C.kind)) 3205 return cxloc::translateSourceLocation(getCursorContext(C), 3206 getLocationFromExpr(getCursorExpr(C))); 3207 3208 if (clang_isStatement(C.kind)) 3209 return cxloc::translateSourceLocation(getCursorContext(C), 3210 getCursorStmt(C)->getLocStart()); 3211 3212 if (C.kind == CXCursor_PreprocessingDirective) { 3213 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3214 return cxloc::translateSourceLocation(getCursorContext(C), L); 3215 } 3216 3217 if (C.kind == CXCursor_MacroInstantiation) { 3218 SourceLocation L 3219 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 3220 return cxloc::translateSourceLocation(getCursorContext(C), L); 3221 } 3222 3223 if (C.kind == CXCursor_MacroDefinition) { 3224 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 3225 return cxloc::translateSourceLocation(getCursorContext(C), L); 3226 } 3227 3228 if (C.kind == CXCursor_InclusionDirective) { 3229 SourceLocation L 3230 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 3231 return cxloc::translateSourceLocation(getCursorContext(C), L); 3232 } 3233 3234 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 3235 return clang_getNullLocation(); 3236 3237 Decl *D = getCursorDecl(C); 3238 SourceLocation Loc = D->getLocation(); 3239 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3240 Loc = Class->getClassLoc(); 3241 // FIXME: Multiple variables declared in a single declaration 3242 // currently lack the information needed to correctly determine their 3243 // ranges when accounting for the type-specifier. We use context 3244 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3245 // and if so, whether it is the first decl. 3246 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3247 if (!cxcursor::isFirstInDeclGroup(C)) 3248 Loc = VD->getLocation(); 3249 } 3250 3251 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 3252} 3253 3254} // end extern "C" 3255 3256static SourceRange getRawCursorExtent(CXCursor C) { 3257 if (clang_isReference(C.kind)) { 3258 switch (C.kind) { 3259 case CXCursor_ObjCSuperClassRef: 3260 return getCursorObjCSuperClassRef(C).second; 3261 3262 case CXCursor_ObjCProtocolRef: 3263 return getCursorObjCProtocolRef(C).second; 3264 3265 case CXCursor_ObjCClassRef: 3266 return getCursorObjCClassRef(C).second; 3267 3268 case CXCursor_TypeRef: 3269 return getCursorTypeRef(C).second; 3270 3271 case CXCursor_TemplateRef: 3272 return getCursorTemplateRef(C).second; 3273 3274 case CXCursor_NamespaceRef: 3275 return getCursorNamespaceRef(C).second; 3276 3277 case CXCursor_MemberRef: 3278 return getCursorMemberRef(C).second; 3279 3280 case CXCursor_CXXBaseSpecifier: 3281 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3282 3283 case CXCursor_LabelRef: 3284 return getCursorLabelRef(C).second; 3285 3286 case CXCursor_OverloadedDeclRef: 3287 return getCursorOverloadedDeclRef(C).second; 3288 3289 default: 3290 // FIXME: Need a way to enumerate all non-reference cases. 3291 llvm_unreachable("Missed a reference kind"); 3292 } 3293 } 3294 3295 if (clang_isExpression(C.kind)) 3296 return getCursorExpr(C)->getSourceRange(); 3297 3298 if (clang_isStatement(C.kind)) 3299 return getCursorStmt(C)->getSourceRange(); 3300 3301 if (C.kind == CXCursor_PreprocessingDirective) 3302 return cxcursor::getCursorPreprocessingDirective(C); 3303 3304 if (C.kind == CXCursor_MacroInstantiation) 3305 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3306 3307 if (C.kind == CXCursor_MacroDefinition) 3308 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3309 3310 if (C.kind == CXCursor_InclusionDirective) 3311 return cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 3312 3313 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3314 Decl *D = cxcursor::getCursorDecl(C); 3315 SourceRange R = D->getSourceRange(); 3316 // FIXME: Multiple variables declared in a single declaration 3317 // currently lack the information needed to correctly determine their 3318 // ranges when accounting for the type-specifier. We use context 3319 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3320 // and if so, whether it is the first decl. 3321 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3322 if (!cxcursor::isFirstInDeclGroup(C)) 3323 R.setBegin(VD->getLocation()); 3324 } 3325 return R; 3326 } 3327 return SourceRange();} 3328 3329extern "C" { 3330 3331CXSourceRange clang_getCursorExtent(CXCursor C) { 3332 SourceRange R = getRawCursorExtent(C); 3333 if (R.isInvalid()) 3334 return clang_getNullRange(); 3335 3336 return cxloc::translateSourceRange(getCursorContext(C), R); 3337} 3338 3339CXCursor clang_getCursorReferenced(CXCursor C) { 3340 if (clang_isInvalid(C.kind)) 3341 return clang_getNullCursor(); 3342 3343 ASTUnit *CXXUnit = getCursorASTUnit(C); 3344 if (clang_isDeclaration(C.kind)) { 3345 Decl *D = getCursorDecl(C); 3346 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3347 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit); 3348 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3349 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit); 3350 if (ObjCForwardProtocolDecl *Protocols 3351 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3352 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit); 3353 3354 return C; 3355 } 3356 3357 if (clang_isExpression(C.kind)) { 3358 Expr *E = getCursorExpr(C); 3359 Decl *D = getDeclFromExpr(E); 3360 if (D) 3361 return MakeCXCursor(D, CXXUnit); 3362 3363 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3364 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit); 3365 3366 return clang_getNullCursor(); 3367 } 3368 3369 if (clang_isStatement(C.kind)) { 3370 Stmt *S = getCursorStmt(C); 3371 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3372 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), 3373 getCursorASTUnit(C)); 3374 3375 return clang_getNullCursor(); 3376 } 3377 3378 if (C.kind == CXCursor_MacroInstantiation) { 3379 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3380 return MakeMacroDefinitionCursor(Def, CXXUnit); 3381 } 3382 3383 if (!clang_isReference(C.kind)) 3384 return clang_getNullCursor(); 3385 3386 switch (C.kind) { 3387 case CXCursor_ObjCSuperClassRef: 3388 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); 3389 3390 case CXCursor_ObjCProtocolRef: { 3391 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); 3392 3393 case CXCursor_ObjCClassRef: 3394 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); 3395 3396 case CXCursor_TypeRef: 3397 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); 3398 3399 case CXCursor_TemplateRef: 3400 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit); 3401 3402 case CXCursor_NamespaceRef: 3403 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit); 3404 3405 case CXCursor_MemberRef: 3406 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit); 3407 3408 case CXCursor_CXXBaseSpecifier: { 3409 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3410 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3411 CXXUnit)); 3412 } 3413 3414 case CXCursor_LabelRef: 3415 // FIXME: We end up faking the "parent" declaration here because we 3416 // don't want to make CXCursor larger. 3417 return MakeCXCursor(getCursorLabelRef(C).first, 3418 CXXUnit->getASTContext().getTranslationUnitDecl(), 3419 CXXUnit); 3420 3421 case CXCursor_OverloadedDeclRef: 3422 return C; 3423 3424 default: 3425 // We would prefer to enumerate all non-reference cursor kinds here. 3426 llvm_unreachable("Unhandled reference cursor kind"); 3427 break; 3428 } 3429 } 3430 3431 return clang_getNullCursor(); 3432} 3433 3434CXCursor clang_getCursorDefinition(CXCursor C) { 3435 if (clang_isInvalid(C.kind)) 3436 return clang_getNullCursor(); 3437 3438 ASTUnit *CXXUnit = getCursorASTUnit(C); 3439 3440 bool WasReference = false; 3441 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3442 C = clang_getCursorReferenced(C); 3443 WasReference = true; 3444 } 3445 3446 if (C.kind == CXCursor_MacroInstantiation) 3447 return clang_getCursorReferenced(C); 3448 3449 if (!clang_isDeclaration(C.kind)) 3450 return clang_getNullCursor(); 3451 3452 Decl *D = getCursorDecl(C); 3453 if (!D) 3454 return clang_getNullCursor(); 3455 3456 switch (D->getKind()) { 3457 // Declaration kinds that don't really separate the notions of 3458 // declaration and definition. 3459 case Decl::Namespace: 3460 case Decl::Typedef: 3461 case Decl::TemplateTypeParm: 3462 case Decl::EnumConstant: 3463 case Decl::Field: 3464 case Decl::ObjCIvar: 3465 case Decl::ObjCAtDefsField: 3466 case Decl::ImplicitParam: 3467 case Decl::ParmVar: 3468 case Decl::NonTypeTemplateParm: 3469 case Decl::TemplateTemplateParm: 3470 case Decl::ObjCCategoryImpl: 3471 case Decl::ObjCImplementation: 3472 case Decl::AccessSpec: 3473 case Decl::LinkageSpec: 3474 case Decl::ObjCPropertyImpl: 3475 case Decl::FileScopeAsm: 3476 case Decl::StaticAssert: 3477 case Decl::Block: 3478 return C; 3479 3480 // Declaration kinds that don't make any sense here, but are 3481 // nonetheless harmless. 3482 case Decl::TranslationUnit: 3483 break; 3484 3485 // Declaration kinds for which the definition is not resolvable. 3486 case Decl::UnresolvedUsingTypename: 3487 case Decl::UnresolvedUsingValue: 3488 break; 3489 3490 case Decl::UsingDirective: 3491 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3492 CXXUnit); 3493 3494 case Decl::NamespaceAlias: 3495 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit); 3496 3497 case Decl::Enum: 3498 case Decl::Record: 3499 case Decl::CXXRecord: 3500 case Decl::ClassTemplateSpecialization: 3501 case Decl::ClassTemplatePartialSpecialization: 3502 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3503 return MakeCXCursor(Def, CXXUnit); 3504 return clang_getNullCursor(); 3505 3506 case Decl::Function: 3507 case Decl::CXXMethod: 3508 case Decl::CXXConstructor: 3509 case Decl::CXXDestructor: 3510 case Decl::CXXConversion: { 3511 const FunctionDecl *Def = 0; 3512 if (cast<FunctionDecl>(D)->getBody(Def)) 3513 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit); 3514 return clang_getNullCursor(); 3515 } 3516 3517 case Decl::Var: { 3518 // Ask the variable if it has a definition. 3519 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3520 return MakeCXCursor(Def, CXXUnit); 3521 return clang_getNullCursor(); 3522 } 3523 3524 case Decl::FunctionTemplate: { 3525 const FunctionDecl *Def = 0; 3526 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3527 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); 3528 return clang_getNullCursor(); 3529 } 3530 3531 case Decl::ClassTemplate: { 3532 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3533 ->getDefinition()) 3534 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3535 CXXUnit); 3536 return clang_getNullCursor(); 3537 } 3538 3539 case Decl::Using: 3540 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3541 D->getLocation(), CXXUnit); 3542 3543 case Decl::UsingShadow: 3544 return clang_getCursorDefinition( 3545 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3546 CXXUnit)); 3547 3548 case Decl::ObjCMethod: { 3549 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3550 if (Method->isThisDeclarationADefinition()) 3551 return C; 3552 3553 // Dig out the method definition in the associated 3554 // @implementation, if we have it. 3555 // FIXME: The ASTs should make finding the definition easier. 3556 if (ObjCInterfaceDecl *Class 3557 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3558 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3559 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3560 Method->isInstanceMethod())) 3561 if (Def->isThisDeclarationADefinition()) 3562 return MakeCXCursor(Def, CXXUnit); 3563 3564 return clang_getNullCursor(); 3565 } 3566 3567 case Decl::ObjCCategory: 3568 if (ObjCCategoryImplDecl *Impl 3569 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3570 return MakeCXCursor(Impl, CXXUnit); 3571 return clang_getNullCursor(); 3572 3573 case Decl::ObjCProtocol: 3574 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3575 return C; 3576 return clang_getNullCursor(); 3577 3578 case Decl::ObjCInterface: 3579 // There are two notions of a "definition" for an Objective-C 3580 // class: the interface and its implementation. When we resolved a 3581 // reference to an Objective-C class, produce the @interface as 3582 // the definition; when we were provided with the interface, 3583 // produce the @implementation as the definition. 3584 if (WasReference) { 3585 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3586 return C; 3587 } else if (ObjCImplementationDecl *Impl 3588 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3589 return MakeCXCursor(Impl, CXXUnit); 3590 return clang_getNullCursor(); 3591 3592 case Decl::ObjCProperty: 3593 // FIXME: We don't really know where to find the 3594 // ObjCPropertyImplDecls that implement this property. 3595 return clang_getNullCursor(); 3596 3597 case Decl::ObjCCompatibleAlias: 3598 if (ObjCInterfaceDecl *Class 3599 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3600 if (!Class->isForwardDecl()) 3601 return MakeCXCursor(Class, CXXUnit); 3602 3603 return clang_getNullCursor(); 3604 3605 case Decl::ObjCForwardProtocol: 3606 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 3607 D->getLocation(), CXXUnit); 3608 3609 case Decl::ObjCClass: 3610 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 3611 CXXUnit); 3612 3613 case Decl::Friend: 3614 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3615 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3616 return clang_getNullCursor(); 3617 3618 case Decl::FriendTemplate: 3619 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3620 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3621 return clang_getNullCursor(); 3622 } 3623 3624 return clang_getNullCursor(); 3625} 3626 3627unsigned clang_isCursorDefinition(CXCursor C) { 3628 if (!clang_isDeclaration(C.kind)) 3629 return 0; 3630 3631 return clang_getCursorDefinition(C) == C; 3632} 3633 3634unsigned clang_getNumOverloadedDecls(CXCursor C) { 3635 if (C.kind != CXCursor_OverloadedDeclRef) 3636 return 0; 3637 3638 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3639 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3640 return E->getNumDecls(); 3641 3642 if (OverloadedTemplateStorage *S 3643 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3644 return S->size(); 3645 3646 Decl *D = Storage.get<Decl*>(); 3647 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3648 return Using->shadow_size(); 3649 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3650 return Classes->size(); 3651 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 3652 return Protocols->protocol_size(); 3653 3654 return 0; 3655} 3656 3657CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 3658 if (cursor.kind != CXCursor_OverloadedDeclRef) 3659 return clang_getNullCursor(); 3660 3661 if (index >= clang_getNumOverloadedDecls(cursor)) 3662 return clang_getNullCursor(); 3663 3664 ASTUnit *Unit = getCursorASTUnit(cursor); 3665 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 3666 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3667 return MakeCXCursor(E->decls_begin()[index], Unit); 3668 3669 if (OverloadedTemplateStorage *S 3670 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3671 return MakeCXCursor(S->begin()[index], Unit); 3672 3673 Decl *D = Storage.get<Decl*>(); 3674 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 3675 // FIXME: This is, unfortunately, linear time. 3676 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 3677 std::advance(Pos, index); 3678 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit); 3679 } 3680 3681 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3682 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit); 3683 3684 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 3685 return MakeCXCursor(Protocols->protocol_begin()[index], Unit); 3686 3687 return clang_getNullCursor(); 3688} 3689 3690void clang_getDefinitionSpellingAndExtent(CXCursor C, 3691 const char **startBuf, 3692 const char **endBuf, 3693 unsigned *startLine, 3694 unsigned *startColumn, 3695 unsigned *endLine, 3696 unsigned *endColumn) { 3697 assert(getCursorDecl(C) && "CXCursor has null decl"); 3698 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3699 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3700 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3701 3702 SourceManager &SM = FD->getASTContext().getSourceManager(); 3703 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3704 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3705 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3706 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3707 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3708 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3709} 3710 3711void clang_enableStackTraces(void) { 3712 llvm::sys::PrintStackTraceOnErrorSignal(); 3713} 3714 3715void clang_executeOnThread(void (*fn)(void*), void *user_data, 3716 unsigned stack_size) { 3717 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 3718} 3719 3720} // end: extern "C" 3721 3722//===----------------------------------------------------------------------===// 3723// Token-based Operations. 3724//===----------------------------------------------------------------------===// 3725 3726/* CXToken layout: 3727 * int_data[0]: a CXTokenKind 3728 * int_data[1]: starting token location 3729 * int_data[2]: token length 3730 * int_data[3]: reserved 3731 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3732 * otherwise unused. 3733 */ 3734extern "C" { 3735 3736CXTokenKind clang_getTokenKind(CXToken CXTok) { 3737 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3738} 3739 3740CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3741 switch (clang_getTokenKind(CXTok)) { 3742 case CXToken_Identifier: 3743 case CXToken_Keyword: 3744 // We know we have an IdentifierInfo*, so use that. 3745 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3746 ->getNameStart()); 3747 3748 case CXToken_Literal: { 3749 // We have stashed the starting pointer in the ptr_data field. Use it. 3750 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3751 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3752 } 3753 3754 case CXToken_Punctuation: 3755 case CXToken_Comment: 3756 break; 3757 } 3758 3759 // We have to find the starting buffer pointer the hard way, by 3760 // deconstructing the source location. 3761 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3762 if (!CXXUnit) 3763 return createCXString(""); 3764 3765 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3766 std::pair<FileID, unsigned> LocInfo 3767 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3768 bool Invalid = false; 3769 llvm::StringRef Buffer 3770 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3771 if (Invalid) 3772 return createCXString(""); 3773 3774 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3775} 3776 3777CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3778 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3779 if (!CXXUnit) 3780 return clang_getNullLocation(); 3781 3782 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3783 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3784} 3785 3786CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3788 if (!CXXUnit) 3789 return clang_getNullRange(); 3790 3791 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3792 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3793} 3794 3795void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3796 CXToken **Tokens, unsigned *NumTokens) { 3797 if (Tokens) 3798 *Tokens = 0; 3799 if (NumTokens) 3800 *NumTokens = 0; 3801 3802 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3803 if (!CXXUnit || !Tokens || !NumTokens) 3804 return; 3805 3806 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3807 3808 SourceRange R = cxloc::translateCXSourceRange(Range); 3809 if (R.isInvalid()) 3810 return; 3811 3812 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3813 std::pair<FileID, unsigned> BeginLocInfo 3814 = SourceMgr.getDecomposedLoc(R.getBegin()); 3815 std::pair<FileID, unsigned> EndLocInfo 3816 = SourceMgr.getDecomposedLoc(R.getEnd()); 3817 3818 // Cannot tokenize across files. 3819 if (BeginLocInfo.first != EndLocInfo.first) 3820 return; 3821 3822 // Create a lexer 3823 bool Invalid = false; 3824 llvm::StringRef Buffer 3825 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3826 if (Invalid) 3827 return; 3828 3829 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3830 CXXUnit->getASTContext().getLangOptions(), 3831 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3832 Lex.SetCommentRetentionState(true); 3833 3834 // Lex tokens until we hit the end of the range. 3835 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3836 llvm::SmallVector<CXToken, 32> CXTokens; 3837 Token Tok; 3838 bool previousWasAt = false; 3839 do { 3840 // Lex the next token 3841 Lex.LexFromRawLexer(Tok); 3842 if (Tok.is(tok::eof)) 3843 break; 3844 3845 // Initialize the CXToken. 3846 CXToken CXTok; 3847 3848 // - Common fields 3849 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3850 CXTok.int_data[2] = Tok.getLength(); 3851 CXTok.int_data[3] = 0; 3852 3853 // - Kind-specific fields 3854 if (Tok.isLiteral()) { 3855 CXTok.int_data[0] = CXToken_Literal; 3856 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3857 } else if (Tok.is(tok::identifier)) { 3858 // Lookup the identifier to determine whether we have a keyword. 3859 std::pair<FileID, unsigned> LocInfo 3860 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3861 bool Invalid = false; 3862 llvm::StringRef Buf 3863 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3864 if (Invalid) 3865 return; 3866 3867 const char *StartPos = Buf.data() + LocInfo.second; 3868 IdentifierInfo *II 3869 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3870 3871 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 3872 CXTok.int_data[0] = CXToken_Keyword; 3873 } 3874 else { 3875 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3876 CXToken_Identifier 3877 : CXToken_Keyword; 3878 } 3879 CXTok.ptr_data = II; 3880 } else if (Tok.is(tok::comment)) { 3881 CXTok.int_data[0] = CXToken_Comment; 3882 CXTok.ptr_data = 0; 3883 } else { 3884 CXTok.int_data[0] = CXToken_Punctuation; 3885 CXTok.ptr_data = 0; 3886 } 3887 CXTokens.push_back(CXTok); 3888 previousWasAt = Tok.is(tok::at); 3889 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3890 3891 if (CXTokens.empty()) 3892 return; 3893 3894 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3895 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3896 *NumTokens = CXTokens.size(); 3897} 3898 3899void clang_disposeTokens(CXTranslationUnit TU, 3900 CXToken *Tokens, unsigned NumTokens) { 3901 free(Tokens); 3902} 3903 3904} // end: extern "C" 3905 3906//===----------------------------------------------------------------------===// 3907// Token annotation APIs. 3908//===----------------------------------------------------------------------===// 3909 3910typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3911static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3912 CXCursor parent, 3913 CXClientData client_data); 3914namespace { 3915class AnnotateTokensWorker { 3916 AnnotateTokensData &Annotated; 3917 CXToken *Tokens; 3918 CXCursor *Cursors; 3919 unsigned NumTokens; 3920 unsigned TokIdx; 3921 unsigned PreprocessingTokIdx; 3922 CursorVisitor AnnotateVis; 3923 SourceManager &SrcMgr; 3924 3925 bool MoreTokens() const { return TokIdx < NumTokens; } 3926 unsigned NextToken() const { return TokIdx; } 3927 void AdvanceToken() { ++TokIdx; } 3928 SourceLocation GetTokenLoc(unsigned tokI) { 3929 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3930 } 3931 3932public: 3933 AnnotateTokensWorker(AnnotateTokensData &annotated, 3934 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3935 ASTUnit *CXXUnit, SourceRange RegionOfInterest) 3936 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3937 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 3938 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this, 3939 Decl::MaxPCHLevel, RegionOfInterest), 3940 SrcMgr(CXXUnit->getSourceManager()) {} 3941 3942 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3943 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3944 void AnnotateTokens(CXCursor parent); 3945}; 3946} 3947 3948void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3949 // Walk the AST within the region of interest, annotating tokens 3950 // along the way. 3951 VisitChildren(parent); 3952 3953 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3954 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3955 if (Pos != Annotated.end() && 3956 (clang_isInvalid(Cursors[I].kind) || 3957 Pos->second.kind != CXCursor_PreprocessingDirective)) 3958 Cursors[I] = Pos->second; 3959 } 3960 3961 // Finish up annotating any tokens left. 3962 if (!MoreTokens()) 3963 return; 3964 3965 const CXCursor &C = clang_getNullCursor(); 3966 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 3967 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3968 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 3969 } 3970} 3971 3972enum CXChildVisitResult 3973AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 3974 CXSourceLocation Loc = clang_getCursorLocation(cursor); 3975 SourceRange cursorRange = getRawCursorExtent(cursor); 3976 if (cursorRange.isInvalid()) 3977 return CXChildVisit_Recurse; 3978 3979 if (clang_isPreprocessing(cursor.kind)) { 3980 // For macro instantiations, just note where the beginning of the macro 3981 // instantiation occurs. 3982 if (cursor.kind == CXCursor_MacroInstantiation) { 3983 Annotated[Loc.int_data] = cursor; 3984 return CXChildVisit_Recurse; 3985 } 3986 3987 // Items in the preprocessing record are kept separate from items in 3988 // declarations, so we keep a separate token index. 3989 unsigned SavedTokIdx = TokIdx; 3990 TokIdx = PreprocessingTokIdx; 3991 3992 // Skip tokens up until we catch up to the beginning of the preprocessing 3993 // entry. 3994 while (MoreTokens()) { 3995 const unsigned I = NextToken(); 3996 SourceLocation TokLoc = GetTokenLoc(I); 3997 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3998 case RangeBefore: 3999 AdvanceToken(); 4000 continue; 4001 case RangeAfter: 4002 case RangeOverlap: 4003 break; 4004 } 4005 break; 4006 } 4007 4008 // Look at all of the tokens within this range. 4009 while (MoreTokens()) { 4010 const unsigned I = NextToken(); 4011 SourceLocation TokLoc = GetTokenLoc(I); 4012 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4013 case RangeBefore: 4014 assert(0 && "Infeasible"); 4015 case RangeAfter: 4016 break; 4017 case RangeOverlap: 4018 Cursors[I] = cursor; 4019 AdvanceToken(); 4020 continue; 4021 } 4022 break; 4023 } 4024 4025 // Save the preprocessing token index; restore the non-preprocessing 4026 // token index. 4027 PreprocessingTokIdx = TokIdx; 4028 TokIdx = SavedTokIdx; 4029 return CXChildVisit_Recurse; 4030 } 4031 4032 if (cursorRange.isInvalid()) 4033 return CXChildVisit_Continue; 4034 4035 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 4036 4037 // Adjust the annotated range based specific declarations. 4038 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 4039 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 4040 Decl *D = cxcursor::getCursorDecl(cursor); 4041 // Don't visit synthesized ObjC methods, since they have no syntatic 4042 // representation in the source. 4043 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 4044 if (MD->isSynthesized()) 4045 return CXChildVisit_Continue; 4046 } 4047 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4048 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 4049 TypeLoc TL = TI->getTypeLoc(); 4050 SourceLocation TLoc = TL.getSourceRange().getBegin(); 4051 if (TLoc.isValid() && L.isValid() && 4052 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 4053 cursorRange.setBegin(TLoc); 4054 } 4055 } 4056 } 4057 4058 // If the location of the cursor occurs within a macro instantiation, record 4059 // the spelling location of the cursor in our annotation map. We can then 4060 // paper over the token labelings during a post-processing step to try and 4061 // get cursor mappings for tokens that are the *arguments* of a macro 4062 // instantiation. 4063 if (L.isMacroID()) { 4064 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 4065 // Only invalidate the old annotation if it isn't part of a preprocessing 4066 // directive. Here we assume that the default construction of CXCursor 4067 // results in CXCursor.kind being an initialized value (i.e., 0). If 4068 // this isn't the case, we can fix by doing lookup + insertion. 4069 4070 CXCursor &oldC = Annotated[rawEncoding]; 4071 if (!clang_isPreprocessing(oldC.kind)) 4072 oldC = cursor; 4073 } 4074 4075 const enum CXCursorKind K = clang_getCursorKind(parent); 4076 const CXCursor updateC = 4077 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 4078 ? clang_getNullCursor() : parent; 4079 4080 while (MoreTokens()) { 4081 const unsigned I = NextToken(); 4082 SourceLocation TokLoc = GetTokenLoc(I); 4083 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4084 case RangeBefore: 4085 Cursors[I] = updateC; 4086 AdvanceToken(); 4087 continue; 4088 case RangeAfter: 4089 case RangeOverlap: 4090 break; 4091 } 4092 break; 4093 } 4094 4095 // Visit children to get their cursor information. 4096 const unsigned BeforeChildren = NextToken(); 4097 VisitChildren(cursor); 4098 const unsigned AfterChildren = NextToken(); 4099 4100 // Adjust 'Last' to the last token within the extent of the cursor. 4101 while (MoreTokens()) { 4102 const unsigned I = NextToken(); 4103 SourceLocation TokLoc = GetTokenLoc(I); 4104 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4105 case RangeBefore: 4106 assert(0 && "Infeasible"); 4107 case RangeAfter: 4108 break; 4109 case RangeOverlap: 4110 Cursors[I] = updateC; 4111 AdvanceToken(); 4112 continue; 4113 } 4114 break; 4115 } 4116 const unsigned Last = NextToken(); 4117 4118 // Scan the tokens that are at the beginning of the cursor, but are not 4119 // capture by the child cursors. 4120 4121 // For AST elements within macros, rely on a post-annotate pass to 4122 // to correctly annotate the tokens with cursors. Otherwise we can 4123 // get confusing results of having tokens that map to cursors that really 4124 // are expanded by an instantiation. 4125 if (L.isMacroID()) 4126 cursor = clang_getNullCursor(); 4127 4128 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 4129 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 4130 break; 4131 4132 Cursors[I] = cursor; 4133 } 4134 // Scan the tokens that are at the end of the cursor, but are not captured 4135 // but the child cursors. 4136 for (unsigned I = AfterChildren; I != Last; ++I) 4137 Cursors[I] = cursor; 4138 4139 TokIdx = Last; 4140 return CXChildVisit_Continue; 4141} 4142 4143static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4144 CXCursor parent, 4145 CXClientData client_data) { 4146 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 4147} 4148 4149extern "C" { 4150 4151void clang_annotateTokens(CXTranslationUnit TU, 4152 CXToken *Tokens, unsigned NumTokens, 4153 CXCursor *Cursors) { 4154 4155 if (NumTokens == 0 || !Tokens || !Cursors) 4156 return; 4157 4158 // Any token we don't specifically annotate will have a NULL cursor. 4159 CXCursor C = clang_getNullCursor(); 4160 for (unsigned I = 0; I != NumTokens; ++I) 4161 Cursors[I] = C; 4162 4163 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 4164 if (!CXXUnit) 4165 return; 4166 4167 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4168 4169 // Determine the region of interest, which contains all of the tokens. 4170 SourceRange RegionOfInterest; 4171 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 4172 clang_getTokenLocation(TU, Tokens[0]))); 4173 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 4174 clang_getTokenLocation(TU, 4175 Tokens[NumTokens - 1]))); 4176 4177 // A mapping from the source locations found when re-lexing or traversing the 4178 // region of interest to the corresponding cursors. 4179 AnnotateTokensData Annotated; 4180 4181 // Relex the tokens within the source range to look for preprocessing 4182 // directives. 4183 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4184 std::pair<FileID, unsigned> BeginLocInfo 4185 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 4186 std::pair<FileID, unsigned> EndLocInfo 4187 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 4188 4189 llvm::StringRef Buffer; 4190 bool Invalid = false; 4191 if (BeginLocInfo.first == EndLocInfo.first && 4192 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 4193 !Invalid) { 4194 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4195 CXXUnit->getASTContext().getLangOptions(), 4196 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 4197 Buffer.end()); 4198 Lex.SetCommentRetentionState(true); 4199 4200 // Lex tokens in raw mode until we hit the end of the range, to avoid 4201 // entering #includes or expanding macros. 4202 while (true) { 4203 Token Tok; 4204 Lex.LexFromRawLexer(Tok); 4205 4206 reprocess: 4207 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 4208 // We have found a preprocessing directive. Gobble it up so that we 4209 // don't see it while preprocessing these tokens later, but keep track 4210 // of all of the token locations inside this preprocessing directive so 4211 // that we can annotate them appropriately. 4212 // 4213 // FIXME: Some simple tests here could identify macro definitions and 4214 // #undefs, to provide specific cursor kinds for those. 4215 std::vector<SourceLocation> Locations; 4216 do { 4217 Locations.push_back(Tok.getLocation()); 4218 Lex.LexFromRawLexer(Tok); 4219 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 4220 4221 using namespace cxcursor; 4222 CXCursor Cursor 4223 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 4224 Locations.back()), 4225 CXXUnit); 4226 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 4227 Annotated[Locations[I].getRawEncoding()] = Cursor; 4228 } 4229 4230 if (Tok.isAtStartOfLine()) 4231 goto reprocess; 4232 4233 continue; 4234 } 4235 4236 if (Tok.is(tok::eof)) 4237 break; 4238 } 4239 } 4240 4241 // Annotate all of the source locations in the region of interest that map to 4242 // a specific cursor. 4243 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 4244 CXXUnit, RegionOfInterest); 4245 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit)); 4246} 4247} // end: extern "C" 4248 4249//===----------------------------------------------------------------------===// 4250// Operations for querying linkage of a cursor. 4251//===----------------------------------------------------------------------===// 4252 4253extern "C" { 4254CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 4255 if (!clang_isDeclaration(cursor.kind)) 4256 return CXLinkage_Invalid; 4257 4258 Decl *D = cxcursor::getCursorDecl(cursor); 4259 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 4260 switch (ND->getLinkage()) { 4261 case NoLinkage: return CXLinkage_NoLinkage; 4262 case InternalLinkage: return CXLinkage_Internal; 4263 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 4264 case ExternalLinkage: return CXLinkage_External; 4265 }; 4266 4267 return CXLinkage_Invalid; 4268} 4269} // end: extern "C" 4270 4271//===----------------------------------------------------------------------===// 4272// Operations for querying language of a cursor. 4273//===----------------------------------------------------------------------===// 4274 4275static CXLanguageKind getDeclLanguage(const Decl *D) { 4276 switch (D->getKind()) { 4277 default: 4278 break; 4279 case Decl::ImplicitParam: 4280 case Decl::ObjCAtDefsField: 4281 case Decl::ObjCCategory: 4282 case Decl::ObjCCategoryImpl: 4283 case Decl::ObjCClass: 4284 case Decl::ObjCCompatibleAlias: 4285 case Decl::ObjCForwardProtocol: 4286 case Decl::ObjCImplementation: 4287 case Decl::ObjCInterface: 4288 case Decl::ObjCIvar: 4289 case Decl::ObjCMethod: 4290 case Decl::ObjCProperty: 4291 case Decl::ObjCPropertyImpl: 4292 case Decl::ObjCProtocol: 4293 return CXLanguage_ObjC; 4294 case Decl::CXXConstructor: 4295 case Decl::CXXConversion: 4296 case Decl::CXXDestructor: 4297 case Decl::CXXMethod: 4298 case Decl::CXXRecord: 4299 case Decl::ClassTemplate: 4300 case Decl::ClassTemplatePartialSpecialization: 4301 case Decl::ClassTemplateSpecialization: 4302 case Decl::Friend: 4303 case Decl::FriendTemplate: 4304 case Decl::FunctionTemplate: 4305 case Decl::LinkageSpec: 4306 case Decl::Namespace: 4307 case Decl::NamespaceAlias: 4308 case Decl::NonTypeTemplateParm: 4309 case Decl::StaticAssert: 4310 case Decl::TemplateTemplateParm: 4311 case Decl::TemplateTypeParm: 4312 case Decl::UnresolvedUsingTypename: 4313 case Decl::UnresolvedUsingValue: 4314 case Decl::Using: 4315 case Decl::UsingDirective: 4316 case Decl::UsingShadow: 4317 return CXLanguage_CPlusPlus; 4318 } 4319 4320 return CXLanguage_C; 4321} 4322 4323extern "C" { 4324 4325enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 4326 if (clang_isDeclaration(cursor.kind)) 4327 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 4328 if (D->hasAttr<UnavailableAttr>() || 4329 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 4330 return CXAvailability_Available; 4331 4332 if (D->hasAttr<DeprecatedAttr>()) 4333 return CXAvailability_Deprecated; 4334 } 4335 4336 return CXAvailability_Available; 4337} 4338 4339CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4340 if (clang_isDeclaration(cursor.kind)) 4341 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4342 4343 return CXLanguage_Invalid; 4344} 4345 4346CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4347 if (clang_isDeclaration(cursor.kind)) { 4348 if (Decl *D = getCursorDecl(cursor)) { 4349 DeclContext *DC = D->getDeclContext(); 4350 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4351 } 4352 } 4353 4354 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4355 if (Decl *D = getCursorDecl(cursor)) 4356 return MakeCXCursor(D, getCursorASTUnit(cursor)); 4357 } 4358 4359 return clang_getNullCursor(); 4360} 4361 4362CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 4363 if (clang_isDeclaration(cursor.kind)) { 4364 if (Decl *D = getCursorDecl(cursor)) { 4365 DeclContext *DC = D->getLexicalDeclContext(); 4366 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4367 } 4368 } 4369 4370 // FIXME: Note that we can't easily compute the lexical context of a 4371 // statement or expression, so we return nothing. 4372 return clang_getNullCursor(); 4373} 4374 4375static void CollectOverriddenMethods(DeclContext *Ctx, 4376 ObjCMethodDecl *Method, 4377 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 4378 if (!Ctx) 4379 return; 4380 4381 // If we have a class or category implementation, jump straight to the 4382 // interface. 4383 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 4384 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 4385 4386 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 4387 if (!Container) 4388 return; 4389 4390 // Check whether we have a matching method at this level. 4391 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 4392 Method->isInstanceMethod())) 4393 if (Method != Overridden) { 4394 // We found an override at this level; there is no need to look 4395 // into other protocols or categories. 4396 Methods.push_back(Overridden); 4397 return; 4398 } 4399 4400 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4401 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 4402 PEnd = Protocol->protocol_end(); 4403 P != PEnd; ++P) 4404 CollectOverriddenMethods(*P, Method, Methods); 4405 } 4406 4407 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 4408 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 4409 PEnd = Category->protocol_end(); 4410 P != PEnd; ++P) 4411 CollectOverriddenMethods(*P, Method, Methods); 4412 } 4413 4414 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4415 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 4416 PEnd = Interface->protocol_end(); 4417 P != PEnd; ++P) 4418 CollectOverriddenMethods(*P, Method, Methods); 4419 4420 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 4421 Category; Category = Category->getNextClassCategory()) 4422 CollectOverriddenMethods(Category, Method, Methods); 4423 4424 // We only look into the superclass if we haven't found anything yet. 4425 if (Methods.empty()) 4426 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 4427 return CollectOverriddenMethods(Super, Method, Methods); 4428 } 4429} 4430 4431void clang_getOverriddenCursors(CXCursor cursor, 4432 CXCursor **overridden, 4433 unsigned *num_overridden) { 4434 if (overridden) 4435 *overridden = 0; 4436 if (num_overridden) 4437 *num_overridden = 0; 4438 if (!overridden || !num_overridden) 4439 return; 4440 4441 if (!clang_isDeclaration(cursor.kind)) 4442 return; 4443 4444 Decl *D = getCursorDecl(cursor); 4445 if (!D) 4446 return; 4447 4448 // Handle C++ member functions. 4449 ASTUnit *CXXUnit = getCursorASTUnit(cursor); 4450 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 4451 *num_overridden = CXXMethod->size_overridden_methods(); 4452 if (!*num_overridden) 4453 return; 4454 4455 *overridden = new CXCursor [*num_overridden]; 4456 unsigned I = 0; 4457 for (CXXMethodDecl::method_iterator 4458 M = CXXMethod->begin_overridden_methods(), 4459 MEnd = CXXMethod->end_overridden_methods(); 4460 M != MEnd; (void)++M, ++I) 4461 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit); 4462 return; 4463 } 4464 4465 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 4466 if (!Method) 4467 return; 4468 4469 // Handle Objective-C methods. 4470 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 4471 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 4472 4473 if (Methods.empty()) 4474 return; 4475 4476 *num_overridden = Methods.size(); 4477 *overridden = new CXCursor [Methods.size()]; 4478 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 4479 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit); 4480} 4481 4482void clang_disposeOverriddenCursors(CXCursor *overridden) { 4483 delete [] overridden; 4484} 4485 4486CXFile clang_getIncludedFile(CXCursor cursor) { 4487 if (cursor.kind != CXCursor_InclusionDirective) 4488 return 0; 4489 4490 InclusionDirective *ID = getCursorInclusionDirective(cursor); 4491 return (void *)ID->getFile(); 4492} 4493 4494} // end: extern "C" 4495 4496 4497//===----------------------------------------------------------------------===// 4498// C++ AST instrospection. 4499//===----------------------------------------------------------------------===// 4500 4501extern "C" { 4502unsigned clang_CXXMethod_isStatic(CXCursor C) { 4503 if (!clang_isDeclaration(C.kind)) 4504 return 0; 4505 4506 CXXMethodDecl *Method = 0; 4507 Decl *D = cxcursor::getCursorDecl(C); 4508 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 4509 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 4510 else 4511 Method = dyn_cast_or_null<CXXMethodDecl>(D); 4512 return (Method && Method->isStatic()) ? 1 : 0; 4513} 4514 4515} // end: extern "C" 4516 4517//===----------------------------------------------------------------------===// 4518// Attribute introspection. 4519//===----------------------------------------------------------------------===// 4520 4521extern "C" { 4522CXType clang_getIBOutletCollectionType(CXCursor C) { 4523 if (C.kind != CXCursor_IBOutletCollectionAttr) 4524 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C)); 4525 4526 IBOutletCollectionAttr *A = 4527 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 4528 4529 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C)); 4530} 4531} // end: extern "C" 4532 4533//===----------------------------------------------------------------------===// 4534// CXString Operations. 4535//===----------------------------------------------------------------------===// 4536 4537extern "C" { 4538const char *clang_getCString(CXString string) { 4539 return string.Spelling; 4540} 4541 4542void clang_disposeString(CXString string) { 4543 if (string.MustFreeString && string.Spelling) 4544 free((void*)string.Spelling); 4545} 4546 4547} // end: extern "C" 4548 4549namespace clang { namespace cxstring { 4550CXString createCXString(const char *String, bool DupString){ 4551 CXString Str; 4552 if (DupString) { 4553 Str.Spelling = strdup(String); 4554 Str.MustFreeString = 1; 4555 } else { 4556 Str.Spelling = String; 4557 Str.MustFreeString = 0; 4558 } 4559 return Str; 4560} 4561 4562CXString createCXString(llvm::StringRef String, bool DupString) { 4563 CXString Result; 4564 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { 4565 char *Spelling = (char *)malloc(String.size() + 1); 4566 memmove(Spelling, String.data(), String.size()); 4567 Spelling[String.size()] = 0; 4568 Result.Spelling = Spelling; 4569 Result.MustFreeString = 1; 4570 } else { 4571 Result.Spelling = String.data(); 4572 Result.MustFreeString = 0; 4573 } 4574 return Result; 4575} 4576}} 4577 4578//===----------------------------------------------------------------------===// 4579// Misc. utility functions. 4580//===----------------------------------------------------------------------===// 4581 4582/// Default to using an 8 MB stack size on "safety" threads. 4583static unsigned SafetyStackThreadSize = 8 << 20; 4584 4585namespace clang { 4586 4587bool RunSafely(llvm::CrashRecoveryContext &CRC, 4588 void (*Fn)(void*), void *UserData) { 4589 if (unsigned Size = GetSafetyThreadStackSize()) 4590 return CRC.RunSafelyOnThread(Fn, UserData, Size); 4591 return CRC.RunSafely(Fn, UserData); 4592} 4593 4594unsigned GetSafetyThreadStackSize() { 4595 return SafetyStackThreadSize; 4596} 4597 4598void SetSafetyThreadStackSize(unsigned Value) { 4599 SafetyStackThreadSize = Value; 4600} 4601 4602} 4603 4604extern "C" { 4605 4606CXString clang_getClangVersion() { 4607 return createCXString(getClangFullVersion()); 4608} 4609 4610} // end: extern "C" 4611