CIndex.cpp revision b13621d08e20ac7aa550e05896de8a57ee99c1e8
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 "CIndexDiagnostic.h" 17#include "CXComment.h" 18#include "CXCursor.h" 19#include "CXSourceLocation.h" 20#include "CXString.h" 21#include "CXTranslationUnit.h" 22#include "CXType.h" 23#include "CursorVisitor.h" 24#include "clang/AST/StmtVisitor.h" 25#include "clang/Basic/Diagnostic.h" 26#include "clang/Basic/Version.h" 27#include "clang/Frontend/ASTUnit.h" 28#include "clang/Frontend/CompilerInstance.h" 29#include "clang/Frontend/FrontendDiagnostic.h" 30#include "clang/Lex/HeaderSearch.h" 31#include "clang/Lex/Lexer.h" 32#include "clang/Lex/PreprocessingRecord.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/ADT/Optional.h" 35#include "llvm/ADT/STLExtras.h" 36#include "llvm/ADT/StringSwitch.h" 37#include "llvm/Support/Compiler.h" 38#include "llvm/Support/CrashRecoveryContext.h" 39#include "llvm/Support/MemoryBuffer.h" 40#include "llvm/Support/Mutex.h" 41#include "llvm/Support/PrettyStackTrace.h" 42#include "llvm/Support/Program.h" 43#include "llvm/Support/SaveAndRestore.h" 44#include "llvm/Support/Signals.h" 45#include "llvm/Support/Threading.h" 46#include "llvm/Support/Timer.h" 47#include "llvm/Support/raw_ostream.h" 48 49using namespace clang; 50using namespace clang::cxcursor; 51using namespace clang::cxstring; 52using namespace clang::cxtu; 53using namespace clang::cxindex; 54 55CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) { 56 if (!TU) 57 return 0; 58 CXTranslationUnit D = new CXTranslationUnitImpl(); 59 D->CIdx = CIdx; 60 D->TUData = TU; 61 D->StringPool = createCXStringPool(); 62 D->Diagnostics = 0; 63 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 64 return D; 65} 66 67cxtu::CXTUOwner::~CXTUOwner() { 68 if (TU) 69 clang_disposeTranslationUnit(TU); 70} 71 72/// \brief Compare two source ranges to determine their relative position in 73/// the translation unit. 74static RangeComparisonResult RangeCompare(SourceManager &SM, 75 SourceRange R1, 76 SourceRange R2) { 77 assert(R1.isValid() && "First range is invalid?"); 78 assert(R2.isValid() && "Second range is invalid?"); 79 if (R1.getEnd() != R2.getBegin() && 80 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 81 return RangeBefore; 82 if (R2.getEnd() != R1.getBegin() && 83 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 84 return RangeAfter; 85 return RangeOverlap; 86} 87 88/// \brief Determine if a source location falls within, before, or after a 89/// a given source range. 90static RangeComparisonResult LocationCompare(SourceManager &SM, 91 SourceLocation L, SourceRange R) { 92 assert(R.isValid() && "First range is invalid?"); 93 assert(L.isValid() && "Second range is invalid?"); 94 if (L == R.getBegin() || L == R.getEnd()) 95 return RangeOverlap; 96 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 97 return RangeBefore; 98 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 99 return RangeAfter; 100 return RangeOverlap; 101} 102 103/// \brief Translate a Clang source range into a CIndex source range. 104/// 105/// Clang internally represents ranges where the end location points to the 106/// start of the token at the end. However, for external clients it is more 107/// useful to have a CXSourceRange be a proper half-open interval. This routine 108/// does the appropriate translation. 109CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 110 const LangOptions &LangOpts, 111 const CharSourceRange &R) { 112 // We want the last character in this location, so we will adjust the 113 // location accordingly. 114 SourceLocation EndLoc = R.getEnd(); 115 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) 116 EndLoc = SM.getExpansionRange(EndLoc).second; 117 if (R.isTokenRange() && !EndLoc.isInvalid()) { 118 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), 119 SM, LangOpts); 120 EndLoc = EndLoc.getLocWithOffset(Length); 121 } 122 123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, 124 R.getBegin().getRawEncoding(), 125 EndLoc.getRawEncoding() }; 126 return Result; 127} 128 129//===----------------------------------------------------------------------===// 130// Cursor visitor. 131//===----------------------------------------------------------------------===// 132 133static SourceRange getRawCursorExtent(CXCursor C); 134static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 135 136 137RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 138 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 139} 140 141/// \brief Visit the given cursor and, if requested by the visitor, 142/// its children. 143/// 144/// \param Cursor the cursor to visit. 145/// 146/// \param CheckedRegionOfInterest if true, then the caller already checked 147/// that this cursor is within the region of interest. 148/// 149/// \returns true if the visitation should be aborted, false if it 150/// should continue. 151bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 152 if (clang_isInvalid(Cursor.kind)) 153 return false; 154 155 if (clang_isDeclaration(Cursor.kind)) { 156 Decl *D = getCursorDecl(Cursor); 157 if (!D) { 158 assert(0 && "Invalid declaration cursor"); 159 return true; // abort. 160 } 161 162 // Ignore implicit declarations, unless it's an objc method because 163 // currently we should report implicit methods for properties when indexing. 164 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 165 return false; 166 } 167 168 // If we have a range of interest, and this cursor doesn't intersect with it, 169 // we're done. 170 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 171 SourceRange Range = getRawCursorExtent(Cursor); 172 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 173 return false; 174 } 175 176 switch (Visitor(Cursor, Parent, ClientData)) { 177 case CXChildVisit_Break: 178 return true; 179 180 case CXChildVisit_Continue: 181 return false; 182 183 case CXChildVisit_Recurse: { 184 bool ret = VisitChildren(Cursor); 185 if (PostChildrenVisitor) 186 if (PostChildrenVisitor(Cursor, ClientData)) 187 return true; 188 return ret; 189 } 190 } 191 192 llvm_unreachable("Invalid CXChildVisitResult!"); 193} 194 195static bool visitPreprocessedEntitiesInRange(SourceRange R, 196 PreprocessingRecord &PPRec, 197 CursorVisitor &Visitor) { 198 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 199 FileID FID; 200 201 if (!Visitor.shouldVisitIncludedEntities()) { 202 // If the begin/end of the range lie in the same FileID, do the optimization 203 // where we skip preprocessed entities that do not come from the same FileID. 204 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 205 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 206 FID = FileID(); 207 } 208 209 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 210 Entities = PPRec.getPreprocessedEntitiesInRange(R); 211 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second, 212 PPRec, FID); 213} 214 215void CursorVisitor::visitFileRegion() { 216 if (RegionOfInterest.isInvalid()) 217 return; 218 219 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 220 SourceManager &SM = Unit->getSourceManager(); 221 222 std::pair<FileID, unsigned> 223 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 224 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 225 226 if (End.first != Begin.first) { 227 // If the end does not reside in the same file, try to recover by 228 // picking the end of the file of begin location. 229 End.first = Begin.first; 230 End.second = SM.getFileIDSize(Begin.first); 231 } 232 233 assert(Begin.first == End.first); 234 if (Begin.second > End.second) 235 return; 236 237 FileID File = Begin.first; 238 unsigned Offset = Begin.second; 239 unsigned Length = End.second - Begin.second; 240 241 if (!VisitDeclsOnly && !VisitPreprocessorLast) 242 if (visitPreprocessedEntitiesInRegion()) 243 return; // visitation break. 244 245 visitDeclsFromFileRegion(File, Offset, Length); 246 247 if (!VisitDeclsOnly && VisitPreprocessorLast) 248 visitPreprocessedEntitiesInRegion(); 249} 250 251static bool isInLexicalContext(Decl *D, DeclContext *DC) { 252 if (!DC) 253 return false; 254 255 for (DeclContext *DeclDC = D->getLexicalDeclContext(); 256 DeclDC; DeclDC = DeclDC->getLexicalParent()) { 257 if (DeclDC == DC) 258 return true; 259 } 260 return false; 261} 262 263void CursorVisitor::visitDeclsFromFileRegion(FileID File, 264 unsigned Offset, unsigned Length) { 265 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 266 SourceManager &SM = Unit->getSourceManager(); 267 SourceRange Range = RegionOfInterest; 268 269 SmallVector<Decl *, 16> Decls; 270 Unit->findFileRegionDecls(File, Offset, Length, Decls); 271 272 // If we didn't find any file level decls for the file, try looking at the 273 // file that it was included from. 274 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 275 bool Invalid = false; 276 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 277 if (Invalid) 278 return; 279 280 SourceLocation Outer; 281 if (SLEntry.isFile()) 282 Outer = SLEntry.getFile().getIncludeLoc(); 283 else 284 Outer = SLEntry.getExpansion().getExpansionLocStart(); 285 if (Outer.isInvalid()) 286 return; 287 288 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 289 Length = 0; 290 Unit->findFileRegionDecls(File, Offset, Length, Decls); 291 } 292 293 assert(!Decls.empty()); 294 295 bool VisitedAtLeastOnce = false; 296 DeclContext *CurDC = 0; 297 SmallVector<Decl *, 16>::iterator DIt = Decls.begin(); 298 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 299 Decl *D = *DIt; 300 if (D->getSourceRange().isInvalid()) 301 continue; 302 303 if (isInLexicalContext(D, CurDC)) 304 continue; 305 306 CurDC = dyn_cast<DeclContext>(D); 307 308 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 309 if (!TD->isFreeStanding()) 310 continue; 311 312 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); 313 if (CompRes == RangeBefore) 314 continue; 315 if (CompRes == RangeAfter) 316 break; 317 318 assert(CompRes == RangeOverlap); 319 VisitedAtLeastOnce = true; 320 321 if (isa<ObjCContainerDecl>(D)) { 322 FileDI_current = &DIt; 323 FileDE_current = DE; 324 } else { 325 FileDI_current = 0; 326 } 327 328 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 329 break; 330 } 331 332 if (VisitedAtLeastOnce) 333 return; 334 335 // No Decls overlapped with the range. Move up the lexical context until there 336 // is a context that contains the range or we reach the translation unit 337 // level. 338 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() 339 : (*(DIt-1))->getLexicalDeclContext(); 340 341 while (DC && !DC->isTranslationUnit()) { 342 Decl *D = cast<Decl>(DC); 343 SourceRange CurDeclRange = D->getSourceRange(); 344 if (CurDeclRange.isInvalid()) 345 break; 346 347 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 348 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true); 349 break; 350 } 351 352 DC = D->getLexicalDeclContext(); 353 } 354} 355 356bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 357 if (!AU->getPreprocessor().getPreprocessingRecord()) 358 return false; 359 360 PreprocessingRecord &PPRec 361 = *AU->getPreprocessor().getPreprocessingRecord(); 362 SourceManager &SM = AU->getSourceManager(); 363 364 if (RegionOfInterest.isValid()) { 365 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 366 SourceLocation B = MappedRange.getBegin(); 367 SourceLocation E = MappedRange.getEnd(); 368 369 if (AU->isInPreambleFileID(B)) { 370 if (SM.isLoadedSourceLocation(E)) 371 return visitPreprocessedEntitiesInRange(SourceRange(B, E), 372 PPRec, *this); 373 374 // Beginning of range lies in the preamble but it also extends beyond 375 // it into the main file. Split the range into 2 parts, one covering 376 // the preamble and another covering the main file. This allows subsequent 377 // calls to visitPreprocessedEntitiesInRange to accept a source range that 378 // lies in the same FileID, allowing it to skip preprocessed entities that 379 // do not come from the same FileID. 380 bool breaked = 381 visitPreprocessedEntitiesInRange( 382 SourceRange(B, AU->getEndOfPreambleFileID()), 383 PPRec, *this); 384 if (breaked) return true; 385 return visitPreprocessedEntitiesInRange( 386 SourceRange(AU->getStartOfMainFileID(), E), 387 PPRec, *this); 388 } 389 390 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 391 } 392 393 bool OnlyLocalDecls 394 = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 395 396 if (OnlyLocalDecls) 397 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 398 PPRec); 399 400 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 401} 402 403template<typename InputIterator> 404bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 405 InputIterator Last, 406 PreprocessingRecord &PPRec, 407 FileID FID) { 408 for (; First != Last; ++First) { 409 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 410 continue; 411 412 PreprocessedEntity *PPE = *First; 413 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 414 if (Visit(MakeMacroExpansionCursor(ME, TU))) 415 return true; 416 417 continue; 418 } 419 420 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) { 421 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 422 return true; 423 424 continue; 425 } 426 427 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 428 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 429 return true; 430 431 continue; 432 } 433 } 434 435 return false; 436} 437 438/// \brief Visit the children of the given cursor. 439/// 440/// \returns true if the visitation should be aborted, false if it 441/// should continue. 442bool CursorVisitor::VisitChildren(CXCursor Cursor) { 443 if (clang_isReference(Cursor.kind) && 444 Cursor.kind != CXCursor_CXXBaseSpecifier) { 445 // By definition, references have no children. 446 return false; 447 } 448 449 // Set the Parent field to Cursor, then back to its old value once we're 450 // done. 451 SetParentRAII SetParent(Parent, StmtParent, Cursor); 452 453 if (clang_isDeclaration(Cursor.kind)) { 454 Decl *D = getCursorDecl(Cursor); 455 if (!D) 456 return false; 457 458 return VisitAttributes(D) || Visit(D); 459 } 460 461 if (clang_isStatement(Cursor.kind)) { 462 if (Stmt *S = getCursorStmt(Cursor)) 463 return Visit(S); 464 465 return false; 466 } 467 468 if (clang_isExpression(Cursor.kind)) { 469 if (Expr *E = getCursorExpr(Cursor)) 470 return Visit(E); 471 472 return false; 473 } 474 475 if (clang_isTranslationUnit(Cursor.kind)) { 476 CXTranslationUnit tu = getCursorTU(Cursor); 477 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData); 478 479 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; 480 for (unsigned I = 0; I != 2; ++I) { 481 if (VisitOrder[I]) { 482 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 483 RegionOfInterest.isInvalid()) { 484 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 485 TLEnd = CXXUnit->top_level_end(); 486 TL != TLEnd; ++TL) { 487 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true)) 488 return true; 489 } 490 } else if (VisitDeclContext( 491 CXXUnit->getASTContext().getTranslationUnitDecl())) 492 return true; 493 continue; 494 } 495 496 // Walk the preprocessing record. 497 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 498 visitPreprocessedEntitiesInRegion(); 499 } 500 501 return false; 502 } 503 504 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 505 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 506 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 507 return Visit(BaseTSInfo->getTypeLoc()); 508 } 509 } 510 } 511 512 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 513 IBOutletCollectionAttr *A = 514 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 515 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>()) 516 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(), 517 A->getInterfaceLoc(), TU)); 518 } 519 520 // Nothing to visit at the moment. 521 return false; 522} 523 524bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 525 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 526 if (Visit(TSInfo->getTypeLoc())) 527 return true; 528 529 if (Stmt *Body = B->getBody()) 530 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 531 532 return false; 533} 534 535llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 536 if (RegionOfInterest.isValid()) { 537 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 538 if (Range.isInvalid()) 539 return llvm::Optional<bool>(); 540 541 switch (CompareRegionOfInterest(Range)) { 542 case RangeBefore: 543 // This declaration comes before the region of interest; skip it. 544 return llvm::Optional<bool>(); 545 546 case RangeAfter: 547 // This declaration comes after the region of interest; we're done. 548 return false; 549 550 case RangeOverlap: 551 // This declaration overlaps the region of interest; visit it. 552 break; 553 } 554 } 555 return true; 556} 557 558bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 559 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 560 561 // FIXME: Eventually remove. This part of a hack to support proper 562 // iteration over all Decls contained lexically within an ObjC container. 563 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 564 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 565 566 for ( ; I != E; ++I) { 567 Decl *D = *I; 568 if (D->getLexicalDeclContext() != DC) 569 continue; 570 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 571 572 // Ignore synthesized ivars here, otherwise if we have something like: 573 // @synthesize prop = _prop; 574 // and '_prop' is not declared, we will encounter a '_prop' ivar before 575 // encountering the 'prop' synthesize declaration and we will think that 576 // we passed the region-of-interest. 577 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 578 if (ivarD->getSynthesize()) 579 continue; 580 } 581 582 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 583 // declarations is a mismatch with the compiler semantics. 584 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 585 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D); 586 if (!ID->isThisDeclarationADefinition()) 587 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 588 589 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 590 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D); 591 if (!PD->isThisDeclarationADefinition()) 592 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 593 } 594 595 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 596 if (!V.hasValue()) 597 continue; 598 if (!V.getValue()) 599 return false; 600 if (Visit(Cursor, true)) 601 return true; 602 } 603 return false; 604} 605 606bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 607 llvm_unreachable("Translation units are visited directly by Visit()"); 608} 609 610bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 611 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 612 return Visit(TSInfo->getTypeLoc()); 613 614 return false; 615} 616 617bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 618 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 619 return Visit(TSInfo->getTypeLoc()); 620 621 return false; 622} 623 624bool CursorVisitor::VisitTagDecl(TagDecl *D) { 625 return VisitDeclContext(D); 626} 627 628bool CursorVisitor::VisitClassTemplateSpecializationDecl( 629 ClassTemplateSpecializationDecl *D) { 630 bool ShouldVisitBody = false; 631 switch (D->getSpecializationKind()) { 632 case TSK_Undeclared: 633 case TSK_ImplicitInstantiation: 634 // Nothing to visit 635 return false; 636 637 case TSK_ExplicitInstantiationDeclaration: 638 case TSK_ExplicitInstantiationDefinition: 639 break; 640 641 case TSK_ExplicitSpecialization: 642 ShouldVisitBody = true; 643 break; 644 } 645 646 // Visit the template arguments used in the specialization. 647 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 648 TypeLoc TL = SpecType->getTypeLoc(); 649 if (TemplateSpecializationTypeLoc *TSTLoc 650 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) { 651 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I) 652 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I))) 653 return true; 654 } 655 } 656 657 if (ShouldVisitBody && VisitCXXRecordDecl(D)) 658 return true; 659 660 return false; 661} 662 663bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 664 ClassTemplatePartialSpecializationDecl *D) { 665 // FIXME: Visit the "outer" template parameter lists on the TagDecl 666 // before visiting these template parameters. 667 if (VisitTemplateParameters(D->getTemplateParameters())) 668 return true; 669 670 // Visit the partial specialization arguments. 671 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten(); 672 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I) 673 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 674 return true; 675 676 return VisitCXXRecordDecl(D); 677} 678 679bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 680 // Visit the default argument. 681 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 682 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 683 if (Visit(DefArg->getTypeLoc())) 684 return true; 685 686 return false; 687} 688 689bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 690 if (Expr *Init = D->getInitExpr()) 691 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 692 return false; 693} 694 695bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 696 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 697 if (Visit(TSInfo->getTypeLoc())) 698 return true; 699 700 // Visit the nested-name-specifier, if present. 701 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 702 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 703 return true; 704 705 return false; 706} 707 708/// \brief Compare two base or member initializers based on their source order. 709static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) { 710 CXXCtorInitializer const * const *X 711 = static_cast<CXXCtorInitializer const * const *>(Xp); 712 CXXCtorInitializer const * const *Y 713 = static_cast<CXXCtorInitializer const * const *>(Yp); 714 715 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder()) 716 return -1; 717 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder()) 718 return 1; 719 else 720 return 0; 721} 722 723bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 724 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 725 // Visit the function declaration's syntactic components in the order 726 // written. This requires a bit of work. 727 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 728 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL); 729 730 // If we have a function declared directly (without the use of a typedef), 731 // visit just the return type. Otherwise, just visit the function's type 732 // now. 733 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) || 734 (!FTL && Visit(TL))) 735 return true; 736 737 // Visit the nested-name-specifier, if present. 738 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 739 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 740 return true; 741 742 // Visit the declaration name. 743 if (VisitDeclarationNameInfo(ND->getNameInfo())) 744 return true; 745 746 // FIXME: Visit explicitly-specified template arguments! 747 748 // Visit the function parameters, if we have a function type. 749 if (FTL && VisitFunctionTypeLoc(*FTL, true)) 750 return true; 751 752 // FIXME: Attributes? 753 } 754 755 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 756 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 757 // Find the initializers that were written in the source. 758 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 759 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(), 760 IEnd = Constructor->init_end(); 761 I != IEnd; ++I) { 762 if (!(*I)->isWritten()) 763 continue; 764 765 WrittenInits.push_back(*I); 766 } 767 768 // Sort the initializers in source order 769 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 770 &CompareCXXCtorInitializers); 771 772 // Visit the initializers in source order 773 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 774 CXXCtorInitializer *Init = WrittenInits[I]; 775 if (Init->isAnyMemberInitializer()) { 776 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 777 Init->getMemberLocation(), TU))) 778 return true; 779 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 780 if (Visit(TInfo->getTypeLoc())) 781 return true; 782 } 783 784 // Visit the initializer value. 785 if (Expr *Initializer = Init->getInit()) 786 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 787 return true; 788 } 789 } 790 791 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 792 return true; 793 } 794 795 return false; 796} 797 798bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 799 if (VisitDeclaratorDecl(D)) 800 return true; 801 802 if (Expr *BitWidth = D->getBitWidth()) 803 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 804 805 return false; 806} 807 808bool CursorVisitor::VisitVarDecl(VarDecl *D) { 809 if (VisitDeclaratorDecl(D)) 810 return true; 811 812 if (Expr *Init = D->getInit()) 813 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 814 815 return false; 816} 817 818bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 819 if (VisitDeclaratorDecl(D)) 820 return true; 821 822 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 823 if (Expr *DefArg = D->getDefaultArgument()) 824 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 825 826 return false; 827} 828 829bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 830 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 831 // before visiting these template parameters. 832 if (VisitTemplateParameters(D->getTemplateParameters())) 833 return true; 834 835 return VisitFunctionDecl(D->getTemplatedDecl()); 836} 837 838bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 839 // FIXME: Visit the "outer" template parameter lists on the TagDecl 840 // before visiting these template parameters. 841 if (VisitTemplateParameters(D->getTemplateParameters())) 842 return true; 843 844 return VisitCXXRecordDecl(D->getTemplatedDecl()); 845} 846 847bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 848 if (VisitTemplateParameters(D->getTemplateParameters())) 849 return true; 850 851 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 852 VisitTemplateArgumentLoc(D->getDefaultArgument())) 853 return true; 854 855 return false; 856} 857 858bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 859 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) 860 if (Visit(TSInfo->getTypeLoc())) 861 return true; 862 863 for (ObjCMethodDecl::param_iterator P = ND->param_begin(), 864 PEnd = ND->param_end(); 865 P != PEnd; ++P) { 866 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 867 return true; 868 } 869 870 if (ND->isThisDeclarationADefinition() && 871 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 872 return true; 873 874 return false; 875} 876 877template <typename DeclIt> 878static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 879 SourceManager &SM, SourceLocation EndLoc, 880 SmallVectorImpl<Decl *> &Decls) { 881 DeclIt next = *DI_current; 882 while (++next != DE_current) { 883 Decl *D_next = *next; 884 if (!D_next) 885 break; 886 SourceLocation L = D_next->getLocStart(); 887 if (!L.isValid()) 888 break; 889 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 890 *DI_current = next; 891 Decls.push_back(D_next); 892 continue; 893 } 894 break; 895 } 896} 897 898namespace { 899 struct ContainerDeclsSort { 900 SourceManager &SM; 901 ContainerDeclsSort(SourceManager &sm) : SM(sm) {} 902 bool operator()(Decl *A, Decl *B) { 903 SourceLocation L_A = A->getLocStart(); 904 SourceLocation L_B = B->getLocStart(); 905 assert(L_A.isValid() && L_B.isValid()); 906 return SM.isBeforeInTranslationUnit(L_A, L_B); 907 } 908 }; 909} 910 911bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 912 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 913 // an @implementation can lexically contain Decls that are not properly 914 // nested in the AST. When we identify such cases, we need to retrofit 915 // this nesting here. 916 if (!DI_current && !FileDI_current) 917 return VisitDeclContext(D); 918 919 // Scan the Decls that immediately come after the container 920 // in the current DeclContext. If any fall within the 921 // container's lexical region, stash them into a vector 922 // for later processing. 923 SmallVector<Decl *, 24> DeclsInContainer; 924 SourceLocation EndLoc = D->getSourceRange().getEnd(); 925 SourceManager &SM = AU->getSourceManager(); 926 if (EndLoc.isValid()) { 927 if (DI_current) { 928 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 929 DeclsInContainer); 930 } else { 931 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 932 DeclsInContainer); 933 } 934 } 935 936 // The common case. 937 if (DeclsInContainer.empty()) 938 return VisitDeclContext(D); 939 940 // Get all the Decls in the DeclContext, and sort them with the 941 // additional ones we've collected. Then visit them. 942 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 943 I!=E; ++I) { 944 Decl *subDecl = *I; 945 if (!subDecl || subDecl->getLexicalDeclContext() != D || 946 subDecl->getLocStart().isInvalid()) 947 continue; 948 DeclsInContainer.push_back(subDecl); 949 } 950 951 // Now sort the Decls so that they appear in lexical order. 952 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), 953 ContainerDeclsSort(SM)); 954 955 // Now visit the decls. 956 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 957 E = DeclsInContainer.end(); I != E; ++I) { 958 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 959 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 960 if (!V.hasValue()) 961 continue; 962 if (!V.getValue()) 963 return false; 964 if (Visit(Cursor, true)) 965 return true; 966 } 967 return false; 968} 969 970bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 971 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 972 TU))) 973 return true; 974 975 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 976 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 977 E = ND->protocol_end(); I != E; ++I, ++PL) 978 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 979 return true; 980 981 return VisitObjCContainerDecl(ND); 982} 983 984bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 985 if (!PID->isThisDeclarationADefinition()) 986 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 987 988 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 989 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 990 E = PID->protocol_end(); I != E; ++I, ++PL) 991 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 992 return true; 993 994 return VisitObjCContainerDecl(PID); 995} 996 997bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 998 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 999 return true; 1000 1001 // FIXME: This implements a workaround with @property declarations also being 1002 // installed in the DeclContext for the @interface. Eventually this code 1003 // should be removed. 1004 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1005 if (!CDecl || !CDecl->IsClassExtension()) 1006 return false; 1007 1008 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1009 if (!ID) 1010 return false; 1011 1012 IdentifierInfo *PropertyId = PD->getIdentifier(); 1013 ObjCPropertyDecl *prevDecl = 1014 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId); 1015 1016 if (!prevDecl) 1017 return false; 1018 1019 // Visit synthesized methods since they will be skipped when visiting 1020 // the @interface. 1021 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1022 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1023 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1024 return true; 1025 1026 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1027 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1028 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1029 return true; 1030 1031 return false; 1032} 1033 1034bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1035 if (!D->isThisDeclarationADefinition()) { 1036 // Forward declaration is treated like a reference. 1037 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1038 } 1039 1040 // Issue callbacks for super class. 1041 if (D->getSuperClass() && 1042 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1043 D->getSuperClassLoc(), 1044 TU))) 1045 return true; 1046 1047 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1048 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1049 E = D->protocol_end(); I != E; ++I, ++PL) 1050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1051 return true; 1052 1053 return VisitObjCContainerDecl(D); 1054} 1055 1056bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1057 return VisitObjCContainerDecl(D); 1058} 1059 1060bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1061 // 'ID' could be null when dealing with invalid code. 1062 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1063 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1064 return true; 1065 1066 return VisitObjCImplDecl(D); 1067} 1068 1069bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1070#if 0 1071 // Issue callbacks for super class. 1072 // FIXME: No source location information! 1073 if (D->getSuperClass() && 1074 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1075 D->getSuperClassLoc(), 1076 TU))) 1077 return true; 1078#endif 1079 1080 return VisitObjCImplDecl(D); 1081} 1082 1083bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1084 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1085 if (PD->isIvarNameSpecified()) 1086 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1087 1088 return false; 1089} 1090 1091bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1092 return VisitDeclContext(D); 1093} 1094 1095bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1096 // Visit nested-name-specifier. 1097 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1098 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1099 return true; 1100 1101 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1102 D->getTargetNameLoc(), TU)); 1103} 1104 1105bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1106 // Visit nested-name-specifier. 1107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1108 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1109 return true; 1110 } 1111 1112 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1113 return true; 1114 1115 return VisitDeclarationNameInfo(D->getNameInfo()); 1116} 1117 1118bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1119 // Visit nested-name-specifier. 1120 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1121 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1122 return true; 1123 1124 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1125 D->getIdentLocation(), TU)); 1126} 1127 1128bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1129 // Visit nested-name-specifier. 1130 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1131 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1132 return true; 1133 } 1134 1135 return VisitDeclarationNameInfo(D->getNameInfo()); 1136} 1137 1138bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1139 UnresolvedUsingTypenameDecl *D) { 1140 // Visit nested-name-specifier. 1141 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1142 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1143 return true; 1144 1145 return false; 1146} 1147 1148bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1149 switch (Name.getName().getNameKind()) { 1150 case clang::DeclarationName::Identifier: 1151 case clang::DeclarationName::CXXLiteralOperatorName: 1152 case clang::DeclarationName::CXXOperatorName: 1153 case clang::DeclarationName::CXXUsingDirective: 1154 return false; 1155 1156 case clang::DeclarationName::CXXConstructorName: 1157 case clang::DeclarationName::CXXDestructorName: 1158 case clang::DeclarationName::CXXConversionFunctionName: 1159 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1160 return Visit(TSInfo->getTypeLoc()); 1161 return false; 1162 1163 case clang::DeclarationName::ObjCZeroArgSelector: 1164 case clang::DeclarationName::ObjCOneArgSelector: 1165 case clang::DeclarationName::ObjCMultiArgSelector: 1166 // FIXME: Per-identifier location info? 1167 return false; 1168 } 1169 1170 llvm_unreachable("Invalid DeclarationName::Kind!"); 1171} 1172 1173bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1174 SourceRange Range) { 1175 // FIXME: This whole routine is a hack to work around the lack of proper 1176 // source information in nested-name-specifiers (PR5791). Since we do have 1177 // a beginning source location, we can visit the first component of the 1178 // nested-name-specifier, if it's a single-token component. 1179 if (!NNS) 1180 return false; 1181 1182 // Get the first component in the nested-name-specifier. 1183 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1184 NNS = Prefix; 1185 1186 switch (NNS->getKind()) { 1187 case NestedNameSpecifier::Namespace: 1188 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1189 TU)); 1190 1191 case NestedNameSpecifier::NamespaceAlias: 1192 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1193 Range.getBegin(), TU)); 1194 1195 case NestedNameSpecifier::TypeSpec: { 1196 // If the type has a form where we know that the beginning of the source 1197 // range matches up with a reference cursor. Visit the appropriate reference 1198 // cursor. 1199 const Type *T = NNS->getAsType(); 1200 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1201 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1202 if (const TagType *Tag = dyn_cast<TagType>(T)) 1203 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1204 if (const TemplateSpecializationType *TST 1205 = dyn_cast<TemplateSpecializationType>(T)) 1206 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1207 break; 1208 } 1209 1210 case NestedNameSpecifier::TypeSpecWithTemplate: 1211 case NestedNameSpecifier::Global: 1212 case NestedNameSpecifier::Identifier: 1213 break; 1214 } 1215 1216 return false; 1217} 1218 1219bool 1220CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1221 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1222 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1223 Qualifiers.push_back(Qualifier); 1224 1225 while (!Qualifiers.empty()) { 1226 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1227 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1228 switch (NNS->getKind()) { 1229 case NestedNameSpecifier::Namespace: 1230 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1231 Q.getLocalBeginLoc(), 1232 TU))) 1233 return true; 1234 1235 break; 1236 1237 case NestedNameSpecifier::NamespaceAlias: 1238 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1239 Q.getLocalBeginLoc(), 1240 TU))) 1241 return true; 1242 1243 break; 1244 1245 case NestedNameSpecifier::TypeSpec: 1246 case NestedNameSpecifier::TypeSpecWithTemplate: 1247 if (Visit(Q.getTypeLoc())) 1248 return true; 1249 1250 break; 1251 1252 case NestedNameSpecifier::Global: 1253 case NestedNameSpecifier::Identifier: 1254 break; 1255 } 1256 } 1257 1258 return false; 1259} 1260 1261bool CursorVisitor::VisitTemplateParameters( 1262 const TemplateParameterList *Params) { 1263 if (!Params) 1264 return false; 1265 1266 for (TemplateParameterList::const_iterator P = Params->begin(), 1267 PEnd = Params->end(); 1268 P != PEnd; ++P) { 1269 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1270 return true; 1271 } 1272 1273 return false; 1274} 1275 1276bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1277 switch (Name.getKind()) { 1278 case TemplateName::Template: 1279 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1280 1281 case TemplateName::OverloadedTemplate: 1282 // Visit the overloaded template set. 1283 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1284 return true; 1285 1286 return false; 1287 1288 case TemplateName::DependentTemplate: 1289 // FIXME: Visit nested-name-specifier. 1290 return false; 1291 1292 case TemplateName::QualifiedTemplate: 1293 // FIXME: Visit nested-name-specifier. 1294 return Visit(MakeCursorTemplateRef( 1295 Name.getAsQualifiedTemplateName()->getDecl(), 1296 Loc, TU)); 1297 1298 case TemplateName::SubstTemplateTemplateParm: 1299 return Visit(MakeCursorTemplateRef( 1300 Name.getAsSubstTemplateTemplateParm()->getParameter(), 1301 Loc, TU)); 1302 1303 case TemplateName::SubstTemplateTemplateParmPack: 1304 return Visit(MakeCursorTemplateRef( 1305 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), 1306 Loc, TU)); 1307 } 1308 1309 llvm_unreachable("Invalid TemplateName::Kind!"); 1310} 1311 1312bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1313 switch (TAL.getArgument().getKind()) { 1314 case TemplateArgument::Null: 1315 case TemplateArgument::Integral: 1316 case TemplateArgument::Pack: 1317 return false; 1318 1319 case TemplateArgument::Type: 1320 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1321 return Visit(TSInfo->getTypeLoc()); 1322 return false; 1323 1324 case TemplateArgument::Declaration: 1325 if (Expr *E = TAL.getSourceDeclExpression()) 1326 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1327 return false; 1328 1329 case TemplateArgument::NullPtr: 1330 if (Expr *E = TAL.getSourceNullPtrExpression()) 1331 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1332 return false; 1333 1334 case TemplateArgument::Expression: 1335 if (Expr *E = TAL.getSourceExpression()) 1336 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1337 return false; 1338 1339 case TemplateArgument::Template: 1340 case TemplateArgument::TemplateExpansion: 1341 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1342 return true; 1343 1344 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1345 TAL.getTemplateNameLoc()); 1346 } 1347 1348 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1349} 1350 1351bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1352 return VisitDeclContext(D); 1353} 1354 1355bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1356 return Visit(TL.getUnqualifiedLoc()); 1357} 1358 1359bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1360 ASTContext &Context = AU->getASTContext(); 1361 1362 // Some builtin types (such as Objective-C's "id", "sel", and 1363 // "Class") have associated declarations. Create cursors for those. 1364 QualType VisitType; 1365 switch (TL.getTypePtr()->getKind()) { 1366 1367 case BuiltinType::Void: 1368 case BuiltinType::NullPtr: 1369 case BuiltinType::Dependent: 1370 case BuiltinType::OCLImage1d: 1371 case BuiltinType::OCLImage1dArray: 1372 case BuiltinType::OCLImage1dBuffer: 1373 case BuiltinType::OCLImage2d: 1374 case BuiltinType::OCLImage2dArray: 1375 case BuiltinType::OCLImage3d: 1376#define BUILTIN_TYPE(Id, SingletonId) 1377#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1378#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1379#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 1380#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 1381#include "clang/AST/BuiltinTypes.def" 1382 break; 1383 1384 case BuiltinType::ObjCId: 1385 VisitType = Context.getObjCIdType(); 1386 break; 1387 1388 case BuiltinType::ObjCClass: 1389 VisitType = Context.getObjCClassType(); 1390 break; 1391 1392 case BuiltinType::ObjCSel: 1393 VisitType = Context.getObjCSelType(); 1394 break; 1395 } 1396 1397 if (!VisitType.isNull()) { 1398 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1399 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1400 TU)); 1401 } 1402 1403 return false; 1404} 1405 1406bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1407 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); 1408} 1409 1410bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1411 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1412} 1413 1414bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1415 if (TL.isDefinition()) 1416 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); 1417 1418 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1419} 1420 1421bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1422 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1423} 1424 1425bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1426 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1427 return true; 1428 1429 return false; 1430} 1431 1432bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1433 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1434 return true; 1435 1436 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1437 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1438 TU))) 1439 return true; 1440 } 1441 1442 return false; 1443} 1444 1445bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1446 return Visit(TL.getPointeeLoc()); 1447} 1448 1449bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1450 return Visit(TL.getInnerLoc()); 1451} 1452 1453bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1454 return Visit(TL.getPointeeLoc()); 1455} 1456 1457bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1458 return Visit(TL.getPointeeLoc()); 1459} 1460 1461bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1462 return Visit(TL.getPointeeLoc()); 1463} 1464 1465bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1466 return Visit(TL.getPointeeLoc()); 1467} 1468 1469bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1470 return Visit(TL.getPointeeLoc()); 1471} 1472 1473bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 1474 return Visit(TL.getModifiedLoc()); 1475} 1476 1477bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1478 bool SkipResultType) { 1479 if (!SkipResultType && Visit(TL.getResultLoc())) 1480 return true; 1481 1482 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1483 if (Decl *D = TL.getArg(I)) 1484 if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) 1485 return true; 1486 1487 return false; 1488} 1489 1490bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1491 if (Visit(TL.getElementLoc())) 1492 return true; 1493 1494 if (Expr *Size = TL.getSizeExpr()) 1495 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); 1496 1497 return false; 1498} 1499 1500bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1501 TemplateSpecializationTypeLoc TL) { 1502 // Visit the template name. 1503 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1504 TL.getTemplateNameLoc())) 1505 return true; 1506 1507 // Visit the template arguments. 1508 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1509 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1510 return true; 1511 1512 return false; 1513} 1514 1515bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1516 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1517} 1518 1519bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1520 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1521 return Visit(TSInfo->getTypeLoc()); 1522 1523 return false; 1524} 1525 1526bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 1527 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1528 return Visit(TSInfo->getTypeLoc()); 1529 1530 return false; 1531} 1532 1533bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1534 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1535 return true; 1536 1537 return false; 1538} 1539 1540bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1541 DependentTemplateSpecializationTypeLoc TL) { 1542 // Visit the nested-name-specifier, if there is one. 1543 if (TL.getQualifierLoc() && 1544 VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1545 return true; 1546 1547 // Visit the template arguments. 1548 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1549 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1550 return true; 1551 1552 return false; 1553} 1554 1555bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1556 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1557 return true; 1558 1559 return Visit(TL.getNamedTypeLoc()); 1560} 1561 1562bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1563 return Visit(TL.getPatternLoc()); 1564} 1565 1566bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 1567 if (Expr *E = TL.getUnderlyingExpr()) 1568 return Visit(MakeCXCursor(E, StmtParent, TU)); 1569 1570 return false; 1571} 1572 1573bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 1574 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1575} 1576 1577bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 1578 return Visit(TL.getValueLoc()); 1579} 1580 1581#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ 1582bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ 1583 return Visit##PARENT##Loc(TL); \ 1584} 1585 1586DEFAULT_TYPELOC_IMPL(Complex, Type) 1587DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) 1588DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) 1589DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) 1590DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) 1591DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) 1592DEFAULT_TYPELOC_IMPL(Vector, Type) 1593DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) 1594DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) 1595DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) 1596DEFAULT_TYPELOC_IMPL(Record, TagType) 1597DEFAULT_TYPELOC_IMPL(Enum, TagType) 1598DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) 1599DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) 1600DEFAULT_TYPELOC_IMPL(Auto, Type) 1601 1602bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1603 // Visit the nested-name-specifier, if present. 1604 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1605 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1606 return true; 1607 1608 if (D->isCompleteDefinition()) { 1609 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1610 E = D->bases_end(); I != E; ++I) { 1611 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1612 return true; 1613 } 1614 } 1615 1616 return VisitTagDecl(D); 1617} 1618 1619bool CursorVisitor::VisitAttributes(Decl *D) { 1620 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1621 i != e; ++i) 1622 if (Visit(MakeCXCursor(*i, D, TU))) 1623 return true; 1624 1625 return false; 1626} 1627 1628//===----------------------------------------------------------------------===// 1629// Data-recursive visitor methods. 1630//===----------------------------------------------------------------------===// 1631 1632namespace { 1633#define DEF_JOB(NAME, DATA, KIND)\ 1634class NAME : public VisitorJob {\ 1635public:\ 1636 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1637 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1638 DATA *get() const { return static_cast<DATA*>(data[0]); }\ 1639}; 1640 1641DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1642DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1643DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1644DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1645DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo, 1646 ExplicitTemplateArgsVisitKind) 1647DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1648DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) 1649DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) 1650#undef DEF_JOB 1651 1652class DeclVisit : public VisitorJob { 1653public: 1654 DeclVisit(Decl *d, CXCursor parent, bool isFirst) : 1655 VisitorJob(parent, VisitorJob::DeclVisitKind, 1656 d, isFirst ? (void*) 1 : (void*) 0) {} 1657 static bool classof(const VisitorJob *VJ) { 1658 return VJ->getKind() == DeclVisitKind; 1659 } 1660 Decl *get() const { return static_cast<Decl*>(data[0]); } 1661 bool isFirst() const { return data[1] ? true : false; } 1662}; 1663class TypeLocVisit : public VisitorJob { 1664public: 1665 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1666 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1667 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1668 1669 static bool classof(const VisitorJob *VJ) { 1670 return VJ->getKind() == TypeLocVisitKind; 1671 } 1672 1673 TypeLoc get() const { 1674 QualType T = QualType::getFromOpaquePtr(data[0]); 1675 return TypeLoc(T, data[1]); 1676 } 1677}; 1678 1679class LabelRefVisit : public VisitorJob { 1680public: 1681 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1682 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1683 labelLoc.getPtrEncoding()) {} 1684 1685 static bool classof(const VisitorJob *VJ) { 1686 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1687 } 1688 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); } 1689 SourceLocation getLoc() const { 1690 return SourceLocation::getFromPtrEncoding(data[1]); } 1691}; 1692 1693class NestedNameSpecifierLocVisit : public VisitorJob { 1694public: 1695 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1696 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1697 Qualifier.getNestedNameSpecifier(), 1698 Qualifier.getOpaqueData()) { } 1699 1700 static bool classof(const VisitorJob *VJ) { 1701 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1702 } 1703 1704 NestedNameSpecifierLoc get() const { 1705 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]), 1706 data[1]); 1707 } 1708}; 1709 1710class DeclarationNameInfoVisit : public VisitorJob { 1711public: 1712 DeclarationNameInfoVisit(Stmt *S, CXCursor parent) 1713 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1714 static bool classof(const VisitorJob *VJ) { 1715 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1716 } 1717 DeclarationNameInfo get() const { 1718 Stmt *S = static_cast<Stmt*>(data[0]); 1719 switch (S->getStmtClass()) { 1720 default: 1721 llvm_unreachable("Unhandled Stmt"); 1722 case clang::Stmt::MSDependentExistsStmtClass: 1723 return cast<MSDependentExistsStmt>(S)->getNameInfo(); 1724 case Stmt::CXXDependentScopeMemberExprClass: 1725 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1726 case Stmt::DependentScopeDeclRefExprClass: 1727 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1728 } 1729 } 1730}; 1731class MemberRefVisit : public VisitorJob { 1732public: 1733 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent) 1734 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1735 L.getPtrEncoding()) {} 1736 static bool classof(const VisitorJob *VJ) { 1737 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1738 } 1739 FieldDecl *get() const { 1740 return static_cast<FieldDecl*>(data[0]); 1741 } 1742 SourceLocation getLoc() const { 1743 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); 1744 } 1745}; 1746class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> { 1747 VisitorWorkList &WL; 1748 CXCursor Parent; 1749public: 1750 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1751 : WL(wl), Parent(parent) {} 1752 1753 void VisitAddrLabelExpr(AddrLabelExpr *E); 1754 void VisitBlockExpr(BlockExpr *B); 1755 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1756 void VisitCompoundStmt(CompoundStmt *S); 1757 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ } 1758 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S); 1759 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 1760 void VisitCXXNewExpr(CXXNewExpr *E); 1761 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 1762 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 1763 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 1764 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 1765 void VisitCXXTypeidExpr(CXXTypeidExpr *E); 1766 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 1767 void VisitCXXUuidofExpr(CXXUuidofExpr *E); 1768 void VisitCXXCatchStmt(CXXCatchStmt *S); 1769 void VisitDeclRefExpr(DeclRefExpr *D); 1770 void VisitDeclStmt(DeclStmt *S); 1771 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 1772 void VisitDesignatedInitExpr(DesignatedInitExpr *E); 1773 void VisitExplicitCastExpr(ExplicitCastExpr *E); 1774 void VisitForStmt(ForStmt *FS); 1775 void VisitGotoStmt(GotoStmt *GS); 1776 void VisitIfStmt(IfStmt *If); 1777 void VisitInitListExpr(InitListExpr *IE); 1778 void VisitMemberExpr(MemberExpr *M); 1779 void VisitOffsetOfExpr(OffsetOfExpr *E); 1780 void VisitObjCEncodeExpr(ObjCEncodeExpr *E); 1781 void VisitObjCMessageExpr(ObjCMessageExpr *M); 1782 void VisitOverloadExpr(OverloadExpr *E); 1783 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); 1784 void VisitStmt(Stmt *S); 1785 void VisitSwitchStmt(SwitchStmt *S); 1786 void VisitWhileStmt(WhileStmt *W); 1787 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); 1788 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E); 1789 void VisitTypeTraitExpr(TypeTraitExpr *E); 1790 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); 1791 void VisitExpressionTraitExpr(ExpressionTraitExpr *E); 1792 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U); 1793 void VisitVAArgExpr(VAArgExpr *E); 1794 void VisitSizeOfPackExpr(SizeOfPackExpr *E); 1795 void VisitPseudoObjectExpr(PseudoObjectExpr *E); 1796 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 1797 void VisitLambdaExpr(LambdaExpr *E); 1798 1799private: 1800 void AddDeclarationNameInfo(Stmt *S); 1801 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 1802 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A); 1803 void AddMemberRef(FieldDecl *D, SourceLocation L); 1804 void AddStmt(Stmt *S); 1805 void AddDecl(Decl *D, bool isFirst = true); 1806 void AddTypeLoc(TypeSourceInfo *TI); 1807 void EnqueueChildren(Stmt *S); 1808}; 1809} // end anonyous namespace 1810 1811void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) { 1812 // 'S' should always be non-null, since it comes from the 1813 // statement we are visiting. 1814 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 1815} 1816 1817void 1818EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1819 if (Qualifier) 1820 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 1821} 1822 1823void EnqueueVisitor::AddStmt(Stmt *S) { 1824 if (S) 1825 WL.push_back(StmtVisit(S, Parent)); 1826} 1827void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) { 1828 if (D) 1829 WL.push_back(DeclVisit(D, Parent, isFirst)); 1830} 1831void EnqueueVisitor:: 1832 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) { 1833 if (A) 1834 WL.push_back(ExplicitTemplateArgsVisit( 1835 const_cast<ASTTemplateArgumentListInfo*>(A), Parent)); 1836} 1837void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) { 1838 if (D) 1839 WL.push_back(MemberRefVisit(D, L, Parent)); 1840} 1841void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 1842 if (TI) 1843 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 1844 } 1845void EnqueueVisitor::EnqueueChildren(Stmt *S) { 1846 unsigned size = WL.size(); 1847 for (Stmt::child_range Child = S->children(); Child; ++Child) { 1848 AddStmt(*Child); 1849 } 1850 if (size == WL.size()) 1851 return; 1852 // Now reverse the entries we just added. This will match the DFS 1853 // ordering performed by the worklist. 1854 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1855 std::reverse(I, E); 1856} 1857void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1858 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 1859} 1860void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) { 1861 AddDecl(B->getBlockDecl()); 1862} 1863void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1864 EnqueueChildren(E); 1865 AddTypeLoc(E->getTypeSourceInfo()); 1866} 1867void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) { 1868 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(), 1869 E = S->body_rend(); I != E; ++I) { 1870 AddStmt(*I); 1871 } 1872} 1873void EnqueueVisitor:: 1874VisitMSDependentExistsStmt(MSDependentExistsStmt *S) { 1875 AddStmt(S->getSubStmt()); 1876 AddDeclarationNameInfo(S); 1877 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 1878 AddNestedNameSpecifierLoc(QualifierLoc); 1879} 1880 1881void EnqueueVisitor:: 1882VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { 1883 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1884 AddDeclarationNameInfo(E); 1885 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1886 AddNestedNameSpecifierLoc(QualifierLoc); 1887 if (!E->isImplicitAccess()) 1888 AddStmt(E->getBase()); 1889} 1890void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1891 // Enqueue the initializer , if any. 1892 AddStmt(E->getInitializer()); 1893 // Enqueue the array size, if any. 1894 AddStmt(E->getArraySize()); 1895 // Enqueue the allocated type. 1896 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 1897 // Enqueue the placement arguments. 1898 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 1899 AddStmt(E->getPlacementArg(I-1)); 1900} 1901void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { 1902 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 1903 AddStmt(CE->getArg(I-1)); 1904 AddStmt(CE->getCallee()); 1905 AddStmt(CE->getArg(0)); 1906} 1907void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1908 // Visit the name of the type being destroyed. 1909 AddTypeLoc(E->getDestroyedTypeInfo()); 1910 // Visit the scope type that looks disturbingly like the nested-name-specifier 1911 // but isn't. 1912 AddTypeLoc(E->getScopeTypeInfo()); 1913 // Visit the nested-name-specifier. 1914 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1915 AddNestedNameSpecifierLoc(QualifierLoc); 1916 // Visit base expression. 1917 AddStmt(E->getBase()); 1918} 1919void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1920 AddTypeLoc(E->getTypeSourceInfo()); 1921} 1922void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1923 EnqueueChildren(E); 1924 AddTypeLoc(E->getTypeSourceInfo()); 1925} 1926void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1927 EnqueueChildren(E); 1928 if (E->isTypeOperand()) 1929 AddTypeLoc(E->getTypeOperandSourceInfo()); 1930} 1931 1932void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr 1933 *E) { 1934 EnqueueChildren(E); 1935 AddTypeLoc(E->getTypeSourceInfo()); 1936} 1937void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1938 EnqueueChildren(E); 1939 if (E->isTypeOperand()) 1940 AddTypeLoc(E->getTypeOperandSourceInfo()); 1941} 1942 1943void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) { 1944 EnqueueChildren(S); 1945 AddDecl(S->getExceptionDecl()); 1946} 1947 1948void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) { 1949 if (DR->hasExplicitTemplateArgs()) { 1950 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs()); 1951 } 1952 WL.push_back(DeclRefExprParts(DR, Parent)); 1953} 1954void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 1955 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1956 AddDeclarationNameInfo(E); 1957 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 1958} 1959void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) { 1960 unsigned size = WL.size(); 1961 bool isFirst = true; 1962 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1963 D != DEnd; ++D) { 1964 AddDecl(*D, isFirst); 1965 isFirst = false; 1966 } 1967 if (size == WL.size()) 1968 return; 1969 // Now reverse the entries we just added. This will match the DFS 1970 // ordering performed by the worklist. 1971 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1972 std::reverse(I, E); 1973} 1974void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1975 AddStmt(E->getInit()); 1976 typedef DesignatedInitExpr::Designator Designator; 1977 for (DesignatedInitExpr::reverse_designators_iterator 1978 D = E->designators_rbegin(), DEnd = E->designators_rend(); 1979 D != DEnd; ++D) { 1980 if (D->isFieldDesignator()) { 1981 if (FieldDecl *Field = D->getField()) 1982 AddMemberRef(Field, D->getFieldLoc()); 1983 continue; 1984 } 1985 if (D->isArrayDesignator()) { 1986 AddStmt(E->getArrayIndex(*D)); 1987 continue; 1988 } 1989 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 1990 AddStmt(E->getArrayRangeEnd(*D)); 1991 AddStmt(E->getArrayRangeStart(*D)); 1992 } 1993} 1994void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 1995 EnqueueChildren(E); 1996 AddTypeLoc(E->getTypeInfoAsWritten()); 1997} 1998void EnqueueVisitor::VisitForStmt(ForStmt *FS) { 1999 AddStmt(FS->getBody()); 2000 AddStmt(FS->getInc()); 2001 AddStmt(FS->getCond()); 2002 AddDecl(FS->getConditionVariable()); 2003 AddStmt(FS->getInit()); 2004} 2005void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) { 2006 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2007} 2008void EnqueueVisitor::VisitIfStmt(IfStmt *If) { 2009 AddStmt(If->getElse()); 2010 AddStmt(If->getThen()); 2011 AddStmt(If->getCond()); 2012 AddDecl(If->getConditionVariable()); 2013} 2014void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) { 2015 // We care about the syntactic form of the initializer list, only. 2016 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2017 IE = Syntactic; 2018 EnqueueChildren(IE); 2019} 2020void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) { 2021 WL.push_back(MemberExprParts(M, Parent)); 2022 2023 // If the base of the member access expression is an implicit 'this', don't 2024 // visit it. 2025 // FIXME: If we ever want to show these implicit accesses, this will be 2026 // unfortunate. However, clang_getCursor() relies on this behavior. 2027 if (!M->isImplicitAccess()) 2028 AddStmt(M->getBase()); 2029} 2030void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 2031 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2032} 2033void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) { 2034 EnqueueChildren(M); 2035 AddTypeLoc(M->getClassReceiverTypeInfo()); 2036} 2037void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 2038 // Visit the components of the offsetof expression. 2039 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2040 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 2041 const OffsetOfNode &Node = E->getComponent(I-1); 2042 switch (Node.getKind()) { 2043 case OffsetOfNode::Array: 2044 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2045 break; 2046 case OffsetOfNode::Field: 2047 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2048 break; 2049 case OffsetOfNode::Identifier: 2050 case OffsetOfNode::Base: 2051 continue; 2052 } 2053 } 2054 // Visit the type into which we're computing the offset. 2055 AddTypeLoc(E->getTypeSourceInfo()); 2056} 2057void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) { 2058 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 2059 WL.push_back(OverloadExprParts(E, Parent)); 2060} 2061void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2062 UnaryExprOrTypeTraitExpr *E) { 2063 EnqueueChildren(E); 2064 if (E->isArgumentType()) 2065 AddTypeLoc(E->getArgumentTypeInfo()); 2066} 2067void EnqueueVisitor::VisitStmt(Stmt *S) { 2068 EnqueueChildren(S); 2069} 2070void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) { 2071 AddStmt(S->getBody()); 2072 AddStmt(S->getCond()); 2073 AddDecl(S->getConditionVariable()); 2074} 2075 2076void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) { 2077 AddStmt(W->getBody()); 2078 AddStmt(W->getCond()); 2079 AddDecl(W->getConditionVariable()); 2080} 2081 2082void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 2083 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2084} 2085 2086void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) { 2087 AddTypeLoc(E->getRhsTypeSourceInfo()); 2088 AddTypeLoc(E->getLhsTypeSourceInfo()); 2089} 2090 2091void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) { 2092 for (unsigned I = E->getNumArgs(); I > 0; --I) 2093 AddTypeLoc(E->getArg(I-1)); 2094} 2095 2096void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { 2097 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2098} 2099 2100void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { 2101 EnqueueChildren(E); 2102} 2103 2104void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) { 2105 VisitOverloadExpr(U); 2106 if (!U->isImplicitAccess()) 2107 AddStmt(U->getBase()); 2108} 2109void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) { 2110 AddStmt(E->getSubExpr()); 2111 AddTypeLoc(E->getWrittenTypeInfo()); 2112} 2113void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 2114 WL.push_back(SizeOfPackExprParts(E, Parent)); 2115} 2116void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) { 2117 // If the opaque value has a source expression, just transparently 2118 // visit that. This is useful for (e.g.) pseudo-object expressions. 2119 if (Expr *SourceExpr = E->getSourceExpr()) 2120 return Visit(SourceExpr); 2121} 2122void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) { 2123 AddStmt(E->getBody()); 2124 WL.push_back(LambdaExprParts(E, Parent)); 2125} 2126void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 2127 // Treat the expression like its syntactic form. 2128 Visit(E->getSyntacticForm()); 2129} 2130 2131void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) { 2132 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); 2133} 2134 2135bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 2136 if (RegionOfInterest.isValid()) { 2137 SourceRange Range = getRawCursorExtent(C); 2138 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 2139 return false; 2140 } 2141 return true; 2142} 2143 2144bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 2145 while (!WL.empty()) { 2146 // Dequeue the worklist item. 2147 VisitorJob LI = WL.back(); 2148 WL.pop_back(); 2149 2150 // Set the Parent field, then back to its old value once we're done. 2151 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 2152 2153 switch (LI.getKind()) { 2154 case VisitorJob::DeclVisitKind: { 2155 Decl *D = cast<DeclVisit>(&LI)->get(); 2156 if (!D) 2157 continue; 2158 2159 // For now, perform default visitation for Decls. 2160 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 2161 cast<DeclVisit>(&LI)->isFirst()))) 2162 return true; 2163 2164 continue; 2165 } 2166 case VisitorJob::ExplicitTemplateArgsVisitKind: { 2167 const ASTTemplateArgumentListInfo *ArgList = 2168 cast<ExplicitTemplateArgsVisit>(&LI)->get(); 2169 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 2170 *ArgEnd = Arg + ArgList->NumTemplateArgs; 2171 Arg != ArgEnd; ++Arg) { 2172 if (VisitTemplateArgumentLoc(*Arg)) 2173 return true; 2174 } 2175 continue; 2176 } 2177 case VisitorJob::TypeLocVisitKind: { 2178 // Perform default visitation for TypeLocs. 2179 if (Visit(cast<TypeLocVisit>(&LI)->get())) 2180 return true; 2181 continue; 2182 } 2183 case VisitorJob::LabelRefVisitKind: { 2184 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 2185 if (LabelStmt *stmt = LS->getStmt()) { 2186 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 2187 TU))) { 2188 return true; 2189 } 2190 } 2191 continue; 2192 } 2193 2194 case VisitorJob::NestedNameSpecifierLocVisitKind: { 2195 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 2196 if (VisitNestedNameSpecifierLoc(V->get())) 2197 return true; 2198 continue; 2199 } 2200 2201 case VisitorJob::DeclarationNameInfoVisitKind: { 2202 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) 2203 ->get())) 2204 return true; 2205 continue; 2206 } 2207 case VisitorJob::MemberRefVisitKind: { 2208 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 2209 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 2210 return true; 2211 continue; 2212 } 2213 case VisitorJob::StmtVisitKind: { 2214 Stmt *S = cast<StmtVisit>(&LI)->get(); 2215 if (!S) 2216 continue; 2217 2218 // Update the current cursor. 2219 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 2220 if (!IsInRegionOfInterest(Cursor)) 2221 continue; 2222 switch (Visitor(Cursor, Parent, ClientData)) { 2223 case CXChildVisit_Break: return true; 2224 case CXChildVisit_Continue: break; 2225 case CXChildVisit_Recurse: 2226 if (PostChildrenVisitor) 2227 WL.push_back(PostChildrenVisit(0, Cursor)); 2228 EnqueueWorkList(WL, S); 2229 break; 2230 } 2231 continue; 2232 } 2233 case VisitorJob::MemberExprPartsKind: { 2234 // Handle the other pieces in the MemberExpr besides the base. 2235 MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 2236 2237 // Visit the nested-name-specifier 2238 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 2239 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2240 return true; 2241 2242 // Visit the declaration name. 2243 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 2244 return true; 2245 2246 // Visit the explicitly-specified template arguments, if any. 2247 if (M->hasExplicitTemplateArgs()) { 2248 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 2249 *ArgEnd = Arg + M->getNumTemplateArgs(); 2250 Arg != ArgEnd; ++Arg) { 2251 if (VisitTemplateArgumentLoc(*Arg)) 2252 return true; 2253 } 2254 } 2255 continue; 2256 } 2257 case VisitorJob::DeclRefExprPartsKind: { 2258 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 2259 // Visit nested-name-specifier, if present. 2260 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 2261 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2262 return true; 2263 // Visit declaration name. 2264 if (VisitDeclarationNameInfo(DR->getNameInfo())) 2265 return true; 2266 continue; 2267 } 2268 case VisitorJob::OverloadExprPartsKind: { 2269 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 2270 // Visit the nested-name-specifier. 2271 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 2272 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2273 return true; 2274 // Visit the declaration name. 2275 if (VisitDeclarationNameInfo(O->getNameInfo())) 2276 return true; 2277 // Visit the overloaded declaration reference. 2278 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 2279 return true; 2280 continue; 2281 } 2282 case VisitorJob::SizeOfPackExprPartsKind: { 2283 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 2284 NamedDecl *Pack = E->getPack(); 2285 if (isa<TemplateTypeParmDecl>(Pack)) { 2286 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 2287 E->getPackLoc(), TU))) 2288 return true; 2289 2290 continue; 2291 } 2292 2293 if (isa<TemplateTemplateParmDecl>(Pack)) { 2294 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 2295 E->getPackLoc(), TU))) 2296 return true; 2297 2298 continue; 2299 } 2300 2301 // Non-type template parameter packs and function parameter packs are 2302 // treated like DeclRefExpr cursors. 2303 continue; 2304 } 2305 2306 case VisitorJob::LambdaExprPartsKind: { 2307 // Visit captures. 2308 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 2309 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 2310 CEnd = E->explicit_capture_end(); 2311 C != CEnd; ++C) { 2312 if (C->capturesThis()) 2313 continue; 2314 2315 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), 2316 C->getLocation(), 2317 TU))) 2318 return true; 2319 } 2320 2321 // Visit parameters and return type, if present. 2322 if (E->hasExplicitParameters() || E->hasExplicitResultType()) { 2323 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 2324 if (E->hasExplicitParameters() && E->hasExplicitResultType()) { 2325 // Visit the whole type. 2326 if (Visit(TL)) 2327 return true; 2328 } else if (isa<FunctionProtoTypeLoc>(TL)) { 2329 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL); 2330 if (E->hasExplicitParameters()) { 2331 // Visit parameters. 2332 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I) 2333 if (Visit(MakeCXCursor(Proto.getArg(I), TU))) 2334 return true; 2335 } else { 2336 // Visit result type. 2337 if (Visit(Proto.getResultLoc())) 2338 return true; 2339 } 2340 } 2341 } 2342 break; 2343 } 2344 2345 case VisitorJob::PostChildrenVisitKind: 2346 if (PostChildrenVisitor(Parent, ClientData)) 2347 return true; 2348 break; 2349 } 2350 } 2351 return false; 2352} 2353 2354bool CursorVisitor::Visit(Stmt *S) { 2355 VisitorWorkList *WL = 0; 2356 if (!WorkListFreeList.empty()) { 2357 WL = WorkListFreeList.back(); 2358 WL->clear(); 2359 WorkListFreeList.pop_back(); 2360 } 2361 else { 2362 WL = new VisitorWorkList(); 2363 WorkListCache.push_back(WL); 2364 } 2365 EnqueueWorkList(*WL, S); 2366 bool result = RunVisitorWorkList(*WL); 2367 WorkListFreeList.push_back(WL); 2368 return result; 2369} 2370 2371namespace { 2372typedef llvm::SmallVector<SourceRange, 4> RefNamePieces; 2373RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 2374 const DeclarationNameInfo &NI, 2375 const SourceRange &QLoc, 2376 const ASTTemplateArgumentListInfo *TemplateArgs = 0){ 2377 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 2378 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 2379 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 2380 2381 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 2382 2383 RefNamePieces Pieces; 2384 2385 if (WantQualifier && QLoc.isValid()) 2386 Pieces.push_back(QLoc); 2387 2388 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 2389 Pieces.push_back(NI.getLoc()); 2390 2391 if (WantTemplateArgs && TemplateArgs) 2392 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc, 2393 TemplateArgs->RAngleLoc)); 2394 2395 if (Kind == DeclarationName::CXXOperatorName) { 2396 Pieces.push_back(SourceLocation::getFromRawEncoding( 2397 NI.getInfo().CXXOperatorName.BeginOpNameLoc)); 2398 Pieces.push_back(SourceLocation::getFromRawEncoding( 2399 NI.getInfo().CXXOperatorName.EndOpNameLoc)); 2400 } 2401 2402 if (WantSinglePiece) { 2403 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 2404 Pieces.clear(); 2405 Pieces.push_back(R); 2406 } 2407 2408 return Pieces; 2409} 2410} 2411 2412//===----------------------------------------------------------------------===// 2413// Misc. API hooks. 2414//===----------------------------------------------------------------------===// 2415 2416static llvm::sys::Mutex EnableMultithreadingMutex; 2417static bool EnabledMultithreading; 2418 2419static void fatal_error_handler(void *user_data, const std::string& reason) { 2420 // Write the result out to stderr avoiding errs() because raw_ostreams can 2421 // call report_fatal_error. 2422 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); 2423 ::abort(); 2424} 2425 2426extern "C" { 2427CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 2428 int displayDiagnostics) { 2429 // Disable pretty stack trace functionality, which will otherwise be a very 2430 // poor citizen of the world and set up all sorts of signal handlers. 2431 llvm::DisablePrettyStackTrace = true; 2432 2433 // We use crash recovery to make some of our APIs more reliable, implicitly 2434 // enable it. 2435 llvm::CrashRecoveryContext::Enable(); 2436 2437 // Enable support for multithreading in LLVM. 2438 { 2439 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 2440 if (!EnabledMultithreading) { 2441 llvm::install_fatal_error_handler(fatal_error_handler, 0); 2442 llvm::llvm_start_multithreaded(); 2443 EnabledMultithreading = true; 2444 } 2445 } 2446 2447 CIndexer *CIdxr = new CIndexer(); 2448 if (excludeDeclarationsFromPCH) 2449 CIdxr->setOnlyLocalDecls(); 2450 if (displayDiagnostics) 2451 CIdxr->setDisplayDiagnostics(); 2452 2453 if (getenv("LIBCLANG_BGPRIO_INDEX")) 2454 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 2455 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 2456 if (getenv("LIBCLANG_BGPRIO_EDIT")) 2457 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 2458 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 2459 2460 return CIdxr; 2461} 2462 2463void clang_disposeIndex(CXIndex CIdx) { 2464 if (CIdx) 2465 delete static_cast<CIndexer *>(CIdx); 2466} 2467 2468void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 2469 if (CIdx) 2470 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 2471} 2472 2473unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 2474 if (CIdx) 2475 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 2476 return 0; 2477} 2478 2479void clang_toggleCrashRecovery(unsigned isEnabled) { 2480 if (isEnabled) 2481 llvm::CrashRecoveryContext::Enable(); 2482 else 2483 llvm::CrashRecoveryContext::Disable(); 2484} 2485 2486CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 2487 const char *ast_filename) { 2488 if (!CIdx) 2489 return 0; 2490 2491 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2492 FileSystemOptions FileSystemOpts; 2493 2494 IntrusiveRefCntPtr<DiagnosticsEngine> Diags; 2495 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts, 2496 CXXIdx->getOnlyLocalDecls(), 2497 0, 0, 2498 /*CaptureDiagnostics=*/true, 2499 /*AllowPCHWithCompilerErrors=*/true, 2500 /*UserFilesAreVolatile=*/true); 2501 return MakeCXTranslationUnit(CXXIdx, TU); 2502} 2503 2504unsigned clang_defaultEditingTranslationUnitOptions() { 2505 return CXTranslationUnit_PrecompiledPreamble | 2506 CXTranslationUnit_CacheCompletionResults; 2507} 2508 2509CXTranslationUnit 2510clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 2511 const char *source_filename, 2512 int num_command_line_args, 2513 const char * const *command_line_args, 2514 unsigned num_unsaved_files, 2515 struct CXUnsavedFile *unsaved_files) { 2516 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 2517 return clang_parseTranslationUnit(CIdx, source_filename, 2518 command_line_args, num_command_line_args, 2519 unsaved_files, num_unsaved_files, 2520 Options); 2521} 2522 2523struct ParseTranslationUnitInfo { 2524 CXIndex CIdx; 2525 const char *source_filename; 2526 const char *const *command_line_args; 2527 int num_command_line_args; 2528 struct CXUnsavedFile *unsaved_files; 2529 unsigned num_unsaved_files; 2530 unsigned options; 2531 CXTranslationUnit result; 2532}; 2533static void clang_parseTranslationUnit_Impl(void *UserData) { 2534 ParseTranslationUnitInfo *PTUI = 2535 static_cast<ParseTranslationUnitInfo*>(UserData); 2536 CXIndex CIdx = PTUI->CIdx; 2537 const char *source_filename = PTUI->source_filename; 2538 const char * const *command_line_args = PTUI->command_line_args; 2539 int num_command_line_args = PTUI->num_command_line_args; 2540 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 2541 unsigned num_unsaved_files = PTUI->num_unsaved_files; 2542 unsigned options = PTUI->options; 2543 PTUI->result = 0; 2544 2545 if (!CIdx) 2546 return; 2547 2548 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2549 2550 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 2551 setThreadBackgroundPriority(); 2552 2553 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 2554 // FIXME: Add a flag for modules. 2555 TranslationUnitKind TUKind 2556 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete; 2557 bool CacheCodeCompetionResults 2558 = options & CXTranslationUnit_CacheCompletionResults; 2559 bool IncludeBriefCommentsInCodeCompletion 2560 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 2561 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies; 2562 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 2563 2564 // Configure the diagnostics. 2565 IntrusiveRefCntPtr<DiagnosticsEngine> 2566 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions, 2567 num_command_line_args, 2568 command_line_args)); 2569 2570 // Recover resources if we crash before exiting this function. 2571 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 2572 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 2573 DiagCleanup(Diags.getPtr()); 2574 2575 OwningPtr<std::vector<ASTUnit::RemappedFile> > 2576 RemappedFiles(new std::vector<ASTUnit::RemappedFile>()); 2577 2578 // Recover resources if we crash before exiting this function. 2579 llvm::CrashRecoveryContextCleanupRegistrar< 2580 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 2581 2582 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2583 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2584 const llvm::MemoryBuffer *Buffer 2585 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2586 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename, 2587 Buffer)); 2588 } 2589 2590 OwningPtr<std::vector<const char *> > 2591 Args(new std::vector<const char*>()); 2592 2593 // Recover resources if we crash before exiting this method. 2594 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 2595 ArgsCleanup(Args.get()); 2596 2597 // Since the Clang C library is primarily used by batch tools dealing with 2598 // (often very broken) source code, where spell-checking can have a 2599 // significant negative impact on performance (particularly when 2600 // precompiled headers are involved), we disable it by default. 2601 // Only do this if we haven't found a spell-checking-related argument. 2602 bool FoundSpellCheckingArgument = false; 2603 for (int I = 0; I != num_command_line_args; ++I) { 2604 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 2605 strcmp(command_line_args[I], "-fspell-checking") == 0) { 2606 FoundSpellCheckingArgument = true; 2607 break; 2608 } 2609 } 2610 if (!FoundSpellCheckingArgument) 2611 Args->push_back("-fno-spell-checking"); 2612 2613 Args->insert(Args->end(), command_line_args, 2614 command_line_args + num_command_line_args); 2615 2616 // The 'source_filename' argument is optional. If the caller does not 2617 // specify it then it is assumed that the source file is specified 2618 // in the actual argument list. 2619 // Put the source file after command_line_args otherwise if '-x' flag is 2620 // present it will be unused. 2621 if (source_filename) 2622 Args->push_back(source_filename); 2623 2624 // Do we need the detailed preprocessing record? 2625 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2626 Args->push_back("-Xclang"); 2627 Args->push_back("-detailed-preprocessing-record"); 2628 } 2629 2630 unsigned NumErrors = Diags->getClient()->getNumErrors(); 2631 OwningPtr<ASTUnit> ErrUnit; 2632 OwningPtr<ASTUnit> Unit( 2633 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0 2634 /* vector::data() not portable */, 2635 Args->size() ? (&(*Args)[0] + Args->size()) :0, 2636 Diags, 2637 CXXIdx->getClangResourcesPath(), 2638 CXXIdx->getOnlyLocalDecls(), 2639 /*CaptureDiagnostics=*/true, 2640 RemappedFiles->size() ? &(*RemappedFiles)[0]:0, 2641 RemappedFiles->size(), 2642 /*RemappedFilesKeepOriginalName=*/true, 2643 PrecompilePreamble, 2644 TUKind, 2645 CacheCodeCompetionResults, 2646 IncludeBriefCommentsInCodeCompletion, 2647 /*AllowPCHWithCompilerErrors=*/true, 2648 SkipFunctionBodies, 2649 /*UserFilesAreVolatile=*/true, 2650 ForSerialization, 2651 &ErrUnit)); 2652 2653 if (NumErrors != Diags->getClient()->getNumErrors()) { 2654 // Make sure to check that 'Unit' is non-NULL. 2655 if (CXXIdx->getDisplayDiagnostics()) 2656 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 2657 } 2658 2659 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take()); 2660} 2661CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2662 const char *source_filename, 2663 const char * const *command_line_args, 2664 int num_command_line_args, 2665 struct CXUnsavedFile *unsaved_files, 2666 unsigned num_unsaved_files, 2667 unsigned options) { 2668 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2669 num_command_line_args, unsaved_files, 2670 num_unsaved_files, options, 0 }; 2671 llvm::CrashRecoveryContext CRC; 2672 2673 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) { 2674 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2675 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2676 fprintf(stderr, " 'command_line_args' : ["); 2677 for (int i = 0; i != num_command_line_args; ++i) { 2678 if (i) 2679 fprintf(stderr, ", "); 2680 fprintf(stderr, "'%s'", command_line_args[i]); 2681 } 2682 fprintf(stderr, "],\n"); 2683 fprintf(stderr, " 'unsaved_files' : ["); 2684 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2685 if (i) 2686 fprintf(stderr, ", "); 2687 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2688 unsaved_files[i].Length); 2689 } 2690 fprintf(stderr, "],\n"); 2691 fprintf(stderr, " 'options' : %d,\n", options); 2692 fprintf(stderr, "}\n"); 2693 2694 return 0; 2695 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 2696 PrintLibclangResourceUsage(PTUI.result); 2697 } 2698 2699 return PTUI.result; 2700} 2701 2702unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2703 return CXSaveTranslationUnit_None; 2704} 2705 2706namespace { 2707 2708struct SaveTranslationUnitInfo { 2709 CXTranslationUnit TU; 2710 const char *FileName; 2711 unsigned options; 2712 CXSaveError result; 2713}; 2714 2715} 2716 2717static void clang_saveTranslationUnit_Impl(void *UserData) { 2718 SaveTranslationUnitInfo *STUI = 2719 static_cast<SaveTranslationUnitInfo*>(UserData); 2720 2721 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx; 2722 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 2723 setThreadBackgroundPriority(); 2724 2725 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName); 2726 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None; 2727} 2728 2729int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2730 unsigned options) { 2731 if (!TU) 2732 return CXSaveError_InvalidTU; 2733 2734 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2735 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2736 if (!CXXUnit->hasSema()) 2737 return CXSaveError_InvalidTU; 2738 2739 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None }; 2740 2741 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() || 2742 getenv("LIBCLANG_NOTHREADS")) { 2743 clang_saveTranslationUnit_Impl(&STUI); 2744 2745 if (getenv("LIBCLANG_RESOURCE_USAGE")) 2746 PrintLibclangResourceUsage(TU); 2747 2748 return STUI.result; 2749 } 2750 2751 // We have an AST that has invalid nodes due to compiler errors. 2752 // Use a crash recovery thread for protection. 2753 2754 llvm::CrashRecoveryContext CRC; 2755 2756 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) { 2757 fprintf(stderr, "libclang: crash detected during AST saving: {\n"); 2758 fprintf(stderr, " 'filename' : '%s'\n", FileName); 2759 fprintf(stderr, " 'options' : %d,\n", options); 2760 fprintf(stderr, "}\n"); 2761 2762 return CXSaveError_Unknown; 2763 2764 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 2765 PrintLibclangResourceUsage(TU); 2766 } 2767 2768 return STUI.result; 2769} 2770 2771void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2772 if (CTUnit) { 2773 // If the translation unit has been marked as unsafe to free, just discard 2774 // it. 2775 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree()) 2776 return; 2777 2778 delete static_cast<ASTUnit *>(CTUnit->TUData); 2779 disposeCXStringPool(CTUnit->StringPool); 2780 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); 2781 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); 2782 delete CTUnit; 2783 } 2784} 2785 2786unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2787 return CXReparse_None; 2788} 2789 2790struct ReparseTranslationUnitInfo { 2791 CXTranslationUnit TU; 2792 unsigned num_unsaved_files; 2793 struct CXUnsavedFile *unsaved_files; 2794 unsigned options; 2795 int result; 2796}; 2797 2798static void clang_reparseTranslationUnit_Impl(void *UserData) { 2799 ReparseTranslationUnitInfo *RTUI = 2800 static_cast<ReparseTranslationUnitInfo*>(UserData); 2801 CXTranslationUnit TU = RTUI->TU; 2802 2803 // Reset the associated diagnostics. 2804 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); 2805 TU->Diagnostics = 0; 2806 2807 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2808 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2809 unsigned options = RTUI->options; 2810 (void) options; 2811 RTUI->result = 1; 2812 2813 if (!TU) 2814 return; 2815 2816 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 2817 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 2818 setThreadBackgroundPriority(); 2819 2820 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2821 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2822 2823 OwningPtr<std::vector<ASTUnit::RemappedFile> > 2824 RemappedFiles(new std::vector<ASTUnit::RemappedFile>()); 2825 2826 // Recover resources if we crash before exiting this function. 2827 llvm::CrashRecoveryContextCleanupRegistrar< 2828 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 2829 2830 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2831 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2832 const llvm::MemoryBuffer *Buffer 2833 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2834 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename, 2835 Buffer)); 2836 } 2837 2838 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0, 2839 RemappedFiles->size())) 2840 RTUI->result = 0; 2841} 2842 2843int clang_reparseTranslationUnit(CXTranslationUnit TU, 2844 unsigned num_unsaved_files, 2845 struct CXUnsavedFile *unsaved_files, 2846 unsigned options) { 2847 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2848 options, 0 }; 2849 2850 if (getenv("LIBCLANG_NOTHREADS")) { 2851 clang_reparseTranslationUnit_Impl(&RTUI); 2852 return RTUI.result; 2853 } 2854 2855 llvm::CrashRecoveryContext CRC; 2856 2857 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { 2858 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2859 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true); 2860 return 1; 2861 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 2862 PrintLibclangResourceUsage(TU); 2863 2864 return RTUI.result; 2865} 2866 2867 2868CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2869 if (!CTUnit) 2870 return createCXString(""); 2871 2872 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData); 2873 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2874} 2875 2876CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2877 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData); 2878 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); 2879} 2880 2881} // end: extern "C" 2882 2883//===----------------------------------------------------------------------===// 2884// CXFile Operations. 2885//===----------------------------------------------------------------------===// 2886 2887extern "C" { 2888CXString clang_getFileName(CXFile SFile) { 2889 if (!SFile) 2890 return createCXString((const char*)NULL); 2891 2892 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2893 return createCXString(FEnt->getName()); 2894} 2895 2896time_t clang_getFileTime(CXFile SFile) { 2897 if (!SFile) 2898 return 0; 2899 2900 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2901 return FEnt->getModificationTime(); 2902} 2903 2904CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2905 if (!tu) 2906 return 0; 2907 2908 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2909 2910 FileManager &FMgr = CXXUnit->getFileManager(); 2911 return const_cast<FileEntry *>(FMgr.getFile(file_name)); 2912} 2913 2914unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) { 2915 if (!tu || !file) 2916 return 0; 2917 2918 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2919 FileEntry *FEnt = static_cast<FileEntry *>(file); 2920 return CXXUnit->getPreprocessor().getHeaderSearchInfo() 2921 .isFileMultipleIncludeGuarded(FEnt); 2922} 2923 2924} // end: extern "C" 2925 2926//===----------------------------------------------------------------------===// 2927// CXCursor Operations. 2928//===----------------------------------------------------------------------===// 2929 2930static Decl *getDeclFromExpr(Stmt *E) { 2931 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 2932 return getDeclFromExpr(CE->getSubExpr()); 2933 2934 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2935 return RefExpr->getDecl(); 2936 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2937 return ME->getMemberDecl(); 2938 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2939 return RE->getDecl(); 2940 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { 2941 if (PRE->isExplicitProperty()) 2942 return PRE->getExplicitProperty(); 2943 // It could be messaging both getter and setter as in: 2944 // ++myobj.myprop; 2945 // in which case prefer to associate the setter since it is less obvious 2946 // from inspecting the source that the setter is going to get called. 2947 if (PRE->isMessagingSetter()) 2948 return PRE->getImplicitPropertySetter(); 2949 return PRE->getImplicitPropertyGetter(); 2950 } 2951 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 2952 return getDeclFromExpr(POE->getSyntacticForm()); 2953 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 2954 if (Expr *Src = OVE->getSourceExpr()) 2955 return getDeclFromExpr(Src); 2956 2957 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2958 return getDeclFromExpr(CE->getCallee()); 2959 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 2960 if (!CE->isElidable()) 2961 return CE->getConstructor(); 2962 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2963 return OME->getMethodDecl(); 2964 2965 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2966 return PE->getProtocol(); 2967 if (SubstNonTypeTemplateParmPackExpr *NTTP 2968 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 2969 return NTTP->getParameterPack(); 2970 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2971 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 2972 isa<ParmVarDecl>(SizeOfPack->getPack())) 2973 return SizeOfPack->getPack(); 2974 2975 return 0; 2976} 2977 2978static SourceLocation getLocationFromExpr(Expr *E) { 2979 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 2980 return getLocationFromExpr(CE->getSubExpr()); 2981 2982 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2983 return /*FIXME:*/Msg->getLeftLoc(); 2984 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2985 return DRE->getLocation(); 2986 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2987 return Member->getMemberLoc(); 2988 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2989 return Ivar->getLocation(); 2990 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2991 return SizeOfPack->getPackLoc(); 2992 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) 2993 return PropRef->getLocation(); 2994 2995 return E->getLocStart(); 2996} 2997 2998extern "C" { 2999 3000unsigned clang_visitChildren(CXCursor parent, 3001 CXCursorVisitor visitor, 3002 CXClientData client_data) { 3003 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 3004 /*VisitPreprocessorLast=*/false); 3005 return CursorVis.VisitChildren(parent); 3006} 3007 3008#ifndef __has_feature 3009#define __has_feature(x) 0 3010#endif 3011#if __has_feature(blocks) 3012typedef enum CXChildVisitResult 3013 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 3014 3015static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 3016 CXClientData client_data) { 3017 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 3018 return block(cursor, parent); 3019} 3020#else 3021// If we are compiled with a compiler that doesn't have native blocks support, 3022// define and call the block manually, so the 3023typedef struct _CXChildVisitResult 3024{ 3025 void *isa; 3026 int flags; 3027 int reserved; 3028 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 3029 CXCursor); 3030} *CXCursorVisitorBlock; 3031 3032static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 3033 CXClientData client_data) { 3034 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 3035 return block->invoke(block, cursor, parent); 3036} 3037#endif 3038 3039 3040unsigned clang_visitChildrenWithBlock(CXCursor parent, 3041 CXCursorVisitorBlock block) { 3042 return clang_visitChildren(parent, visitWithBlock, block); 3043} 3044 3045static CXString getDeclSpelling(Decl *D) { 3046 if (!D) 3047 return createCXString(""); 3048 3049 NamedDecl *ND = dyn_cast<NamedDecl>(D); 3050 if (!ND) { 3051 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D)) 3052 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 3053 return createCXString(Property->getIdentifier()->getName()); 3054 3055 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) 3056 if (Module *Mod = ImportD->getImportedModule()) 3057 return createCXString(Mod->getFullModuleName()); 3058 3059 return createCXString(""); 3060 } 3061 3062 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 3063 return createCXString(OMD->getSelector().getAsString()); 3064 3065 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 3066 // No, this isn't the same as the code below. getIdentifier() is non-virtual 3067 // and returns different names. NamedDecl returns the class name and 3068 // ObjCCategoryImplDecl returns the category name. 3069 return createCXString(CIMP->getIdentifier()->getNameStart()); 3070 3071 if (isa<UsingDirectiveDecl>(D)) 3072 return createCXString(""); 3073 3074 SmallString<1024> S; 3075 llvm::raw_svector_ostream os(S); 3076 ND->printName(os); 3077 3078 return createCXString(os.str()); 3079} 3080 3081CXString clang_getCursorSpelling(CXCursor C) { 3082 if (clang_isTranslationUnit(C.kind)) 3083 return clang_getTranslationUnitSpelling( 3084 static_cast<CXTranslationUnit>(C.data[2])); 3085 3086 if (clang_isReference(C.kind)) { 3087 switch (C.kind) { 3088 case CXCursor_ObjCSuperClassRef: { 3089 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 3090 return createCXString(Super->getIdentifier()->getNameStart()); 3091 } 3092 case CXCursor_ObjCClassRef: { 3093 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 3094 return createCXString(Class->getIdentifier()->getNameStart()); 3095 } 3096 case CXCursor_ObjCProtocolRef: { 3097 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 3098 assert(OID && "getCursorSpelling(): Missing protocol decl"); 3099 return createCXString(OID->getIdentifier()->getNameStart()); 3100 } 3101 case CXCursor_CXXBaseSpecifier: { 3102 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 3103 return createCXString(B->getType().getAsString()); 3104 } 3105 case CXCursor_TypeRef: { 3106 TypeDecl *Type = getCursorTypeRef(C).first; 3107 assert(Type && "Missing type decl"); 3108 3109 return createCXString(getCursorContext(C).getTypeDeclType(Type). 3110 getAsString()); 3111 } 3112 case CXCursor_TemplateRef: { 3113 TemplateDecl *Template = getCursorTemplateRef(C).first; 3114 assert(Template && "Missing template decl"); 3115 3116 return createCXString(Template->getNameAsString()); 3117 } 3118 3119 case CXCursor_NamespaceRef: { 3120 NamedDecl *NS = getCursorNamespaceRef(C).first; 3121 assert(NS && "Missing namespace decl"); 3122 3123 return createCXString(NS->getNameAsString()); 3124 } 3125 3126 case CXCursor_MemberRef: { 3127 FieldDecl *Field = getCursorMemberRef(C).first; 3128 assert(Field && "Missing member decl"); 3129 3130 return createCXString(Field->getNameAsString()); 3131 } 3132 3133 case CXCursor_LabelRef: { 3134 LabelStmt *Label = getCursorLabelRef(C).first; 3135 assert(Label && "Missing label"); 3136 3137 return createCXString(Label->getName()); 3138 } 3139 3140 case CXCursor_OverloadedDeclRef: { 3141 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3142 if (Decl *D = Storage.dyn_cast<Decl *>()) { 3143 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3144 return createCXString(ND->getNameAsString()); 3145 return createCXString(""); 3146 } 3147 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3148 return createCXString(E->getName().getAsString()); 3149 OverloadedTemplateStorage *Ovl 3150 = Storage.get<OverloadedTemplateStorage*>(); 3151 if (Ovl->size() == 0) 3152 return createCXString(""); 3153 return createCXString((*Ovl->begin())->getNameAsString()); 3154 } 3155 3156 case CXCursor_VariableRef: { 3157 VarDecl *Var = getCursorVariableRef(C).first; 3158 assert(Var && "Missing variable decl"); 3159 3160 return createCXString(Var->getNameAsString()); 3161 } 3162 3163 default: 3164 return createCXString("<not implemented>"); 3165 } 3166 } 3167 3168 if (clang_isExpression(C.kind)) { 3169 Decl *D = getDeclFromExpr(getCursorExpr(C)); 3170 if (D) 3171 return getDeclSpelling(D); 3172 return createCXString(""); 3173 } 3174 3175 if (clang_isStatement(C.kind)) { 3176 Stmt *S = getCursorStmt(C); 3177 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 3178 return createCXString(Label->getName()); 3179 3180 return createCXString(""); 3181 } 3182 3183 if (C.kind == CXCursor_MacroExpansion) 3184 return createCXString(getCursorMacroExpansion(C)->getName() 3185 ->getNameStart()); 3186 3187 if (C.kind == CXCursor_MacroDefinition) 3188 return createCXString(getCursorMacroDefinition(C)->getName() 3189 ->getNameStart()); 3190 3191 if (C.kind == CXCursor_InclusionDirective) 3192 return createCXString(getCursorInclusionDirective(C)->getFileName()); 3193 3194 if (clang_isDeclaration(C.kind)) 3195 return getDeclSpelling(getCursorDecl(C)); 3196 3197 if (C.kind == CXCursor_AnnotateAttr) { 3198 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); 3199 return createCXString(AA->getAnnotation()); 3200 } 3201 3202 if (C.kind == CXCursor_AsmLabelAttr) { 3203 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); 3204 return createCXString(AA->getLabel()); 3205 } 3206 3207 return createCXString(""); 3208} 3209 3210CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, 3211 unsigned pieceIndex, 3212 unsigned options) { 3213 if (clang_Cursor_isNull(C)) 3214 return clang_getNullRange(); 3215 3216 ASTContext &Ctx = getCursorContext(C); 3217 3218 if (clang_isStatement(C.kind)) { 3219 Stmt *S = getCursorStmt(C); 3220 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { 3221 if (pieceIndex > 0) 3222 return clang_getNullRange(); 3223 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); 3224 } 3225 3226 return clang_getNullRange(); 3227 } 3228 3229 if (C.kind == CXCursor_ObjCMessageExpr) { 3230 if (ObjCMessageExpr * 3231 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { 3232 if (pieceIndex >= ME->getNumSelectorLocs()) 3233 return clang_getNullRange(); 3234 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); 3235 } 3236 } 3237 3238 if (C.kind == CXCursor_ObjCInstanceMethodDecl || 3239 C.kind == CXCursor_ObjCClassMethodDecl) { 3240 if (ObjCMethodDecl * 3241 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { 3242 if (pieceIndex >= MD->getNumSelectorLocs()) 3243 return clang_getNullRange(); 3244 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); 3245 } 3246 } 3247 3248 if (C.kind == CXCursor_ObjCCategoryDecl || 3249 C.kind == CXCursor_ObjCCategoryImplDecl) { 3250 if (pieceIndex > 0) 3251 return clang_getNullRange(); 3252 if (ObjCCategoryDecl * 3253 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) 3254 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); 3255 if (ObjCCategoryImplDecl * 3256 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) 3257 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); 3258 } 3259 3260 if (C.kind == CXCursor_ModuleImportDecl) { 3261 if (pieceIndex > 0) 3262 return clang_getNullRange(); 3263 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { 3264 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); 3265 if (!Locs.empty()) 3266 return cxloc::translateSourceRange(Ctx, 3267 SourceRange(Locs.front(), Locs.back())); 3268 } 3269 return clang_getNullRange(); 3270 } 3271 3272 // FIXME: A CXCursor_InclusionDirective should give the location of the 3273 // filename, but we don't keep track of this. 3274 3275 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation 3276 // but we don't keep track of this. 3277 3278 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label 3279 // but we don't keep track of this. 3280 3281 // Default handling, give the location of the cursor. 3282 3283 if (pieceIndex > 0) 3284 return clang_getNullRange(); 3285 3286 CXSourceLocation CXLoc = clang_getCursorLocation(C); 3287 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); 3288 return cxloc::translateSourceRange(Ctx, Loc); 3289} 3290 3291CXString clang_getCursorDisplayName(CXCursor C) { 3292 if (!clang_isDeclaration(C.kind)) 3293 return clang_getCursorSpelling(C); 3294 3295 Decl *D = getCursorDecl(C); 3296 if (!D) 3297 return createCXString(""); 3298 3299 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); 3300 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 3301 D = FunTmpl->getTemplatedDecl(); 3302 3303 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 3304 SmallString<64> Str; 3305 llvm::raw_svector_ostream OS(Str); 3306 OS << *Function; 3307 if (Function->getPrimaryTemplate()) 3308 OS << "<>"; 3309 OS << "("; 3310 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 3311 if (I) 3312 OS << ", "; 3313 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 3314 } 3315 3316 if (Function->isVariadic()) { 3317 if (Function->getNumParams()) 3318 OS << ", "; 3319 OS << "..."; 3320 } 3321 OS << ")"; 3322 return createCXString(OS.str()); 3323 } 3324 3325 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 3326 SmallString<64> Str; 3327 llvm::raw_svector_ostream OS(Str); 3328 OS << *ClassTemplate; 3329 OS << "<"; 3330 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 3331 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 3332 if (I) 3333 OS << ", "; 3334 3335 NamedDecl *Param = Params->getParam(I); 3336 if (Param->getIdentifier()) { 3337 OS << Param->getIdentifier()->getName(); 3338 continue; 3339 } 3340 3341 // There is no parameter name, which makes this tricky. Try to come up 3342 // with something useful that isn't too long. 3343 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3344 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 3345 else if (NonTypeTemplateParmDecl *NTTP 3346 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 3347 OS << NTTP->getType().getAsString(Policy); 3348 else 3349 OS << "template<...> class"; 3350 } 3351 3352 OS << ">"; 3353 return createCXString(OS.str()); 3354 } 3355 3356 if (ClassTemplateSpecializationDecl *ClassSpec 3357 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 3358 // If the type was explicitly written, use that. 3359 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 3360 return createCXString(TSInfo->getType().getAsString(Policy)); 3361 3362 SmallString<64> Str; 3363 llvm::raw_svector_ostream OS(Str); 3364 OS << *ClassSpec; 3365 OS << TemplateSpecializationType::PrintTemplateArgumentList( 3366 ClassSpec->getTemplateArgs().data(), 3367 ClassSpec->getTemplateArgs().size(), 3368 Policy); 3369 return createCXString(OS.str()); 3370 } 3371 3372 return clang_getCursorSpelling(C); 3373} 3374 3375CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 3376 switch (Kind) { 3377 case CXCursor_FunctionDecl: 3378 return createCXString("FunctionDecl"); 3379 case CXCursor_TypedefDecl: 3380 return createCXString("TypedefDecl"); 3381 case CXCursor_EnumDecl: 3382 return createCXString("EnumDecl"); 3383 case CXCursor_EnumConstantDecl: 3384 return createCXString("EnumConstantDecl"); 3385 case CXCursor_StructDecl: 3386 return createCXString("StructDecl"); 3387 case CXCursor_UnionDecl: 3388 return createCXString("UnionDecl"); 3389 case CXCursor_ClassDecl: 3390 return createCXString("ClassDecl"); 3391 case CXCursor_FieldDecl: 3392 return createCXString("FieldDecl"); 3393 case CXCursor_VarDecl: 3394 return createCXString("VarDecl"); 3395 case CXCursor_ParmDecl: 3396 return createCXString("ParmDecl"); 3397 case CXCursor_ObjCInterfaceDecl: 3398 return createCXString("ObjCInterfaceDecl"); 3399 case CXCursor_ObjCCategoryDecl: 3400 return createCXString("ObjCCategoryDecl"); 3401 case CXCursor_ObjCProtocolDecl: 3402 return createCXString("ObjCProtocolDecl"); 3403 case CXCursor_ObjCPropertyDecl: 3404 return createCXString("ObjCPropertyDecl"); 3405 case CXCursor_ObjCIvarDecl: 3406 return createCXString("ObjCIvarDecl"); 3407 case CXCursor_ObjCInstanceMethodDecl: 3408 return createCXString("ObjCInstanceMethodDecl"); 3409 case CXCursor_ObjCClassMethodDecl: 3410 return createCXString("ObjCClassMethodDecl"); 3411 case CXCursor_ObjCImplementationDecl: 3412 return createCXString("ObjCImplementationDecl"); 3413 case CXCursor_ObjCCategoryImplDecl: 3414 return createCXString("ObjCCategoryImplDecl"); 3415 case CXCursor_CXXMethod: 3416 return createCXString("CXXMethod"); 3417 case CXCursor_UnexposedDecl: 3418 return createCXString("UnexposedDecl"); 3419 case CXCursor_ObjCSuperClassRef: 3420 return createCXString("ObjCSuperClassRef"); 3421 case CXCursor_ObjCProtocolRef: 3422 return createCXString("ObjCProtocolRef"); 3423 case CXCursor_ObjCClassRef: 3424 return createCXString("ObjCClassRef"); 3425 case CXCursor_TypeRef: 3426 return createCXString("TypeRef"); 3427 case CXCursor_TemplateRef: 3428 return createCXString("TemplateRef"); 3429 case CXCursor_NamespaceRef: 3430 return createCXString("NamespaceRef"); 3431 case CXCursor_MemberRef: 3432 return createCXString("MemberRef"); 3433 case CXCursor_LabelRef: 3434 return createCXString("LabelRef"); 3435 case CXCursor_OverloadedDeclRef: 3436 return createCXString("OverloadedDeclRef"); 3437 case CXCursor_VariableRef: 3438 return createCXString("VariableRef"); 3439 case CXCursor_IntegerLiteral: 3440 return createCXString("IntegerLiteral"); 3441 case CXCursor_FloatingLiteral: 3442 return createCXString("FloatingLiteral"); 3443 case CXCursor_ImaginaryLiteral: 3444 return createCXString("ImaginaryLiteral"); 3445 case CXCursor_StringLiteral: 3446 return createCXString("StringLiteral"); 3447 case CXCursor_CharacterLiteral: 3448 return createCXString("CharacterLiteral"); 3449 case CXCursor_ParenExpr: 3450 return createCXString("ParenExpr"); 3451 case CXCursor_UnaryOperator: 3452 return createCXString("UnaryOperator"); 3453 case CXCursor_ArraySubscriptExpr: 3454 return createCXString("ArraySubscriptExpr"); 3455 case CXCursor_BinaryOperator: 3456 return createCXString("BinaryOperator"); 3457 case CXCursor_CompoundAssignOperator: 3458 return createCXString("CompoundAssignOperator"); 3459 case CXCursor_ConditionalOperator: 3460 return createCXString("ConditionalOperator"); 3461 case CXCursor_CStyleCastExpr: 3462 return createCXString("CStyleCastExpr"); 3463 case CXCursor_CompoundLiteralExpr: 3464 return createCXString("CompoundLiteralExpr"); 3465 case CXCursor_InitListExpr: 3466 return createCXString("InitListExpr"); 3467 case CXCursor_AddrLabelExpr: 3468 return createCXString("AddrLabelExpr"); 3469 case CXCursor_StmtExpr: 3470 return createCXString("StmtExpr"); 3471 case CXCursor_GenericSelectionExpr: 3472 return createCXString("GenericSelectionExpr"); 3473 case CXCursor_GNUNullExpr: 3474 return createCXString("GNUNullExpr"); 3475 case CXCursor_CXXStaticCastExpr: 3476 return createCXString("CXXStaticCastExpr"); 3477 case CXCursor_CXXDynamicCastExpr: 3478 return createCXString("CXXDynamicCastExpr"); 3479 case CXCursor_CXXReinterpretCastExpr: 3480 return createCXString("CXXReinterpretCastExpr"); 3481 case CXCursor_CXXConstCastExpr: 3482 return createCXString("CXXConstCastExpr"); 3483 case CXCursor_CXXFunctionalCastExpr: 3484 return createCXString("CXXFunctionalCastExpr"); 3485 case CXCursor_CXXTypeidExpr: 3486 return createCXString("CXXTypeidExpr"); 3487 case CXCursor_CXXBoolLiteralExpr: 3488 return createCXString("CXXBoolLiteralExpr"); 3489 case CXCursor_CXXNullPtrLiteralExpr: 3490 return createCXString("CXXNullPtrLiteralExpr"); 3491 case CXCursor_CXXThisExpr: 3492 return createCXString("CXXThisExpr"); 3493 case CXCursor_CXXThrowExpr: 3494 return createCXString("CXXThrowExpr"); 3495 case CXCursor_CXXNewExpr: 3496 return createCXString("CXXNewExpr"); 3497 case CXCursor_CXXDeleteExpr: 3498 return createCXString("CXXDeleteExpr"); 3499 case CXCursor_UnaryExpr: 3500 return createCXString("UnaryExpr"); 3501 case CXCursor_ObjCStringLiteral: 3502 return createCXString("ObjCStringLiteral"); 3503 case CXCursor_ObjCBoolLiteralExpr: 3504 return createCXString("ObjCBoolLiteralExpr"); 3505 case CXCursor_ObjCEncodeExpr: 3506 return createCXString("ObjCEncodeExpr"); 3507 case CXCursor_ObjCSelectorExpr: 3508 return createCXString("ObjCSelectorExpr"); 3509 case CXCursor_ObjCProtocolExpr: 3510 return createCXString("ObjCProtocolExpr"); 3511 case CXCursor_ObjCBridgedCastExpr: 3512 return createCXString("ObjCBridgedCastExpr"); 3513 case CXCursor_BlockExpr: 3514 return createCXString("BlockExpr"); 3515 case CXCursor_PackExpansionExpr: 3516 return createCXString("PackExpansionExpr"); 3517 case CXCursor_SizeOfPackExpr: 3518 return createCXString("SizeOfPackExpr"); 3519 case CXCursor_LambdaExpr: 3520 return createCXString("LambdaExpr"); 3521 case CXCursor_UnexposedExpr: 3522 return createCXString("UnexposedExpr"); 3523 case CXCursor_DeclRefExpr: 3524 return createCXString("DeclRefExpr"); 3525 case CXCursor_MemberRefExpr: 3526 return createCXString("MemberRefExpr"); 3527 case CXCursor_CallExpr: 3528 return createCXString("CallExpr"); 3529 case CXCursor_ObjCMessageExpr: 3530 return createCXString("ObjCMessageExpr"); 3531 case CXCursor_UnexposedStmt: 3532 return createCXString("UnexposedStmt"); 3533 case CXCursor_DeclStmt: 3534 return createCXString("DeclStmt"); 3535 case CXCursor_LabelStmt: 3536 return createCXString("LabelStmt"); 3537 case CXCursor_CompoundStmt: 3538 return createCXString("CompoundStmt"); 3539 case CXCursor_CaseStmt: 3540 return createCXString("CaseStmt"); 3541 case CXCursor_DefaultStmt: 3542 return createCXString("DefaultStmt"); 3543 case CXCursor_IfStmt: 3544 return createCXString("IfStmt"); 3545 case CXCursor_SwitchStmt: 3546 return createCXString("SwitchStmt"); 3547 case CXCursor_WhileStmt: 3548 return createCXString("WhileStmt"); 3549 case CXCursor_DoStmt: 3550 return createCXString("DoStmt"); 3551 case CXCursor_ForStmt: 3552 return createCXString("ForStmt"); 3553 case CXCursor_GotoStmt: 3554 return createCXString("GotoStmt"); 3555 case CXCursor_IndirectGotoStmt: 3556 return createCXString("IndirectGotoStmt"); 3557 case CXCursor_ContinueStmt: 3558 return createCXString("ContinueStmt"); 3559 case CXCursor_BreakStmt: 3560 return createCXString("BreakStmt"); 3561 case CXCursor_ReturnStmt: 3562 return createCXString("ReturnStmt"); 3563 case CXCursor_GCCAsmStmt: 3564 return createCXString("GCCAsmStmt"); 3565 case CXCursor_MSAsmStmt: 3566 return createCXString("MSAsmStmt"); 3567 case CXCursor_ObjCAtTryStmt: 3568 return createCXString("ObjCAtTryStmt"); 3569 case CXCursor_ObjCAtCatchStmt: 3570 return createCXString("ObjCAtCatchStmt"); 3571 case CXCursor_ObjCAtFinallyStmt: 3572 return createCXString("ObjCAtFinallyStmt"); 3573 case CXCursor_ObjCAtThrowStmt: 3574 return createCXString("ObjCAtThrowStmt"); 3575 case CXCursor_ObjCAtSynchronizedStmt: 3576 return createCXString("ObjCAtSynchronizedStmt"); 3577 case CXCursor_ObjCAutoreleasePoolStmt: 3578 return createCXString("ObjCAutoreleasePoolStmt"); 3579 case CXCursor_ObjCForCollectionStmt: 3580 return createCXString("ObjCForCollectionStmt"); 3581 case CXCursor_CXXCatchStmt: 3582 return createCXString("CXXCatchStmt"); 3583 case CXCursor_CXXTryStmt: 3584 return createCXString("CXXTryStmt"); 3585 case CXCursor_CXXForRangeStmt: 3586 return createCXString("CXXForRangeStmt"); 3587 case CXCursor_SEHTryStmt: 3588 return createCXString("SEHTryStmt"); 3589 case CXCursor_SEHExceptStmt: 3590 return createCXString("SEHExceptStmt"); 3591 case CXCursor_SEHFinallyStmt: 3592 return createCXString("SEHFinallyStmt"); 3593 case CXCursor_NullStmt: 3594 return createCXString("NullStmt"); 3595 case CXCursor_InvalidFile: 3596 return createCXString("InvalidFile"); 3597 case CXCursor_InvalidCode: 3598 return createCXString("InvalidCode"); 3599 case CXCursor_NoDeclFound: 3600 return createCXString("NoDeclFound"); 3601 case CXCursor_NotImplemented: 3602 return createCXString("NotImplemented"); 3603 case CXCursor_TranslationUnit: 3604 return createCXString("TranslationUnit"); 3605 case CXCursor_UnexposedAttr: 3606 return createCXString("UnexposedAttr"); 3607 case CXCursor_IBActionAttr: 3608 return createCXString("attribute(ibaction)"); 3609 case CXCursor_IBOutletAttr: 3610 return createCXString("attribute(iboutlet)"); 3611 case CXCursor_IBOutletCollectionAttr: 3612 return createCXString("attribute(iboutletcollection)"); 3613 case CXCursor_CXXFinalAttr: 3614 return createCXString("attribute(final)"); 3615 case CXCursor_CXXOverrideAttr: 3616 return createCXString("attribute(override)"); 3617 case CXCursor_AnnotateAttr: 3618 return createCXString("attribute(annotate)"); 3619 case CXCursor_AsmLabelAttr: 3620 return createCXString("asm label"); 3621 case CXCursor_PreprocessingDirective: 3622 return createCXString("preprocessing directive"); 3623 case CXCursor_MacroDefinition: 3624 return createCXString("macro definition"); 3625 case CXCursor_MacroExpansion: 3626 return createCXString("macro expansion"); 3627 case CXCursor_InclusionDirective: 3628 return createCXString("inclusion directive"); 3629 case CXCursor_Namespace: 3630 return createCXString("Namespace"); 3631 case CXCursor_LinkageSpec: 3632 return createCXString("LinkageSpec"); 3633 case CXCursor_CXXBaseSpecifier: 3634 return createCXString("C++ base class specifier"); 3635 case CXCursor_Constructor: 3636 return createCXString("CXXConstructor"); 3637 case CXCursor_Destructor: 3638 return createCXString("CXXDestructor"); 3639 case CXCursor_ConversionFunction: 3640 return createCXString("CXXConversion"); 3641 case CXCursor_TemplateTypeParameter: 3642 return createCXString("TemplateTypeParameter"); 3643 case CXCursor_NonTypeTemplateParameter: 3644 return createCXString("NonTypeTemplateParameter"); 3645 case CXCursor_TemplateTemplateParameter: 3646 return createCXString("TemplateTemplateParameter"); 3647 case CXCursor_FunctionTemplate: 3648 return createCXString("FunctionTemplate"); 3649 case CXCursor_ClassTemplate: 3650 return createCXString("ClassTemplate"); 3651 case CXCursor_ClassTemplatePartialSpecialization: 3652 return createCXString("ClassTemplatePartialSpecialization"); 3653 case CXCursor_NamespaceAlias: 3654 return createCXString("NamespaceAlias"); 3655 case CXCursor_UsingDirective: 3656 return createCXString("UsingDirective"); 3657 case CXCursor_UsingDeclaration: 3658 return createCXString("UsingDeclaration"); 3659 case CXCursor_TypeAliasDecl: 3660 return createCXString("TypeAliasDecl"); 3661 case CXCursor_ObjCSynthesizeDecl: 3662 return createCXString("ObjCSynthesizeDecl"); 3663 case CXCursor_ObjCDynamicDecl: 3664 return createCXString("ObjCDynamicDecl"); 3665 case CXCursor_CXXAccessSpecifier: 3666 return createCXString("CXXAccessSpecifier"); 3667 case CXCursor_ModuleImportDecl: 3668 return createCXString("ModuleImport"); 3669 } 3670 3671 llvm_unreachable("Unhandled CXCursorKind"); 3672} 3673 3674struct GetCursorData { 3675 SourceLocation TokenBeginLoc; 3676 bool PointsAtMacroArgExpansion; 3677 bool VisitedObjCPropertyImplDecl; 3678 SourceLocation VisitedDeclaratorDeclStartLoc; 3679 CXCursor &BestCursor; 3680 3681 GetCursorData(SourceManager &SM, 3682 SourceLocation tokenBegin, CXCursor &outputCursor) 3683 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 3684 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 3685 VisitedObjCPropertyImplDecl = false; 3686 } 3687}; 3688 3689static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3690 CXCursor parent, 3691 CXClientData client_data) { 3692 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 3693 CXCursor *BestCursor = &Data->BestCursor; 3694 3695 // If we point inside a macro argument we should provide info of what the 3696 // token is so use the actual cursor, don't replace it with a macro expansion 3697 // cursor. 3698 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 3699 return CXChildVisit_Recurse; 3700 3701 if (clang_isDeclaration(cursor.kind)) { 3702 // Avoid having the implicit methods override the property decls. 3703 if (ObjCMethodDecl *MD 3704 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 3705 if (MD->isImplicit()) 3706 return CXChildVisit_Break; 3707 3708 } else if (ObjCInterfaceDecl *ID 3709 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 3710 // Check that when we have multiple @class references in the same line, 3711 // that later ones do not override the previous ones. 3712 // If we have: 3713 // @class Foo, Bar; 3714 // source ranges for both start at '@', so 'Bar' will end up overriding 3715 // 'Foo' even though the cursor location was at 'Foo'. 3716 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 3717 BestCursor->kind == CXCursor_ObjCClassRef) 3718 if (ObjCInterfaceDecl *PrevID 3719 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){ 3720 if (PrevID != ID && 3721 !PrevID->isThisDeclarationADefinition() && 3722 !ID->isThisDeclarationADefinition()) 3723 return CXChildVisit_Break; 3724 } 3725 3726 } else if (DeclaratorDecl *DD 3727 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 3728 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 3729 // Check that when we have multiple declarators in the same line, 3730 // that later ones do not override the previous ones. 3731 // If we have: 3732 // int Foo, Bar; 3733 // source ranges for both start at 'int', so 'Bar' will end up overriding 3734 // 'Foo' even though the cursor location was at 'Foo'. 3735 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 3736 return CXChildVisit_Break; 3737 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 3738 3739 } else if (ObjCPropertyImplDecl *PropImp 3740 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) { 3741 (void)PropImp; 3742 // Check that when we have multiple @synthesize in the same line, 3743 // that later ones do not override the previous ones. 3744 // If we have: 3745 // @synthesize Foo, Bar; 3746 // source ranges for both start at '@', so 'Bar' will end up overriding 3747 // 'Foo' even though the cursor location was at 'Foo'. 3748 if (Data->VisitedObjCPropertyImplDecl) 3749 return CXChildVisit_Break; 3750 Data->VisitedObjCPropertyImplDecl = true; 3751 } 3752 } 3753 3754 if (clang_isExpression(cursor.kind) && 3755 clang_isDeclaration(BestCursor->kind)) { 3756 if (Decl *D = getCursorDecl(*BestCursor)) { 3757 // Avoid having the cursor of an expression replace the declaration cursor 3758 // when the expression source range overlaps the declaration range. 3759 // This can happen for C++ constructor expressions whose range generally 3760 // include the variable declaration, e.g.: 3761 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. 3762 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 3763 D->getLocation() == Data->TokenBeginLoc) 3764 return CXChildVisit_Break; 3765 } 3766 } 3767 3768 // If our current best cursor is the construction of a temporary object, 3769 // don't replace that cursor with a type reference, because we want 3770 // clang_getCursor() to point at the constructor. 3771 if (clang_isExpression(BestCursor->kind) && 3772 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3773 cursor.kind == CXCursor_TypeRef) { 3774 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 3775 // as having the actual point on the type reference. 3776 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 3777 return CXChildVisit_Recurse; 3778 } 3779 3780 *BestCursor = cursor; 3781 return CXChildVisit_Recurse; 3782} 3783 3784CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3785 if (!TU) 3786 return clang_getNullCursor(); 3787 3788 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3789 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3790 3791 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3792 CXCursor Result = cxcursor::getCursor(TU, SLoc); 3793 3794 bool Logging = getenv("LIBCLANG_LOGGING"); 3795 if (Logging) { 3796 CXFile SearchFile; 3797 unsigned SearchLine, SearchColumn; 3798 CXFile ResultFile; 3799 unsigned ResultLine, ResultColumn; 3800 CXString SearchFileName, ResultFileName, KindSpelling, USR; 3801 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 3802 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3803 3804 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0); 3805 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine, 3806 &ResultColumn, 0); 3807 SearchFileName = clang_getFileName(SearchFile); 3808 ResultFileName = clang_getFileName(ResultFile); 3809 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3810 USR = clang_getCursorUSR(Result); 3811 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n", 3812 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3813 clang_getCString(KindSpelling), 3814 clang_getCString(ResultFileName), ResultLine, ResultColumn, 3815 clang_getCString(USR), IsDef); 3816 clang_disposeString(SearchFileName); 3817 clang_disposeString(ResultFileName); 3818 clang_disposeString(KindSpelling); 3819 clang_disposeString(USR); 3820 3821 CXCursor Definition = clang_getCursorDefinition(Result); 3822 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 3823 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 3824 CXString DefinitionKindSpelling 3825 = clang_getCursorKindSpelling(Definition.kind); 3826 CXFile DefinitionFile; 3827 unsigned DefinitionLine, DefinitionColumn; 3828 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile, 3829 &DefinitionLine, &DefinitionColumn, 0); 3830 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 3831 fprintf(stderr, " -> %s(%s:%d:%d)\n", 3832 clang_getCString(DefinitionKindSpelling), 3833 clang_getCString(DefinitionFileName), 3834 DefinitionLine, DefinitionColumn); 3835 clang_disposeString(DefinitionFileName); 3836 clang_disposeString(DefinitionKindSpelling); 3837 } 3838 } 3839 3840 return Result; 3841} 3842 3843CXCursor clang_getNullCursor(void) { 3844 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3845} 3846 3847unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3848 return X == Y; 3849} 3850 3851unsigned clang_hashCursor(CXCursor C) { 3852 unsigned Index = 0; 3853 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 3854 Index = 1; 3855 3856 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue( 3857 std::make_pair(C.kind, C.data[Index])); 3858} 3859 3860unsigned clang_isInvalid(enum CXCursorKind K) { 3861 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3862} 3863 3864unsigned clang_isDeclaration(enum CXCursorKind K) { 3865 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 3866 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 3867} 3868 3869unsigned clang_isReference(enum CXCursorKind K) { 3870 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3871} 3872 3873unsigned clang_isExpression(enum CXCursorKind K) { 3874 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3875} 3876 3877unsigned clang_isStatement(enum CXCursorKind K) { 3878 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3879} 3880 3881unsigned clang_isAttribute(enum CXCursorKind K) { 3882 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 3883} 3884 3885unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3886 return K == CXCursor_TranslationUnit; 3887} 3888 3889unsigned clang_isPreprocessing(enum CXCursorKind K) { 3890 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3891} 3892 3893unsigned clang_isUnexposed(enum CXCursorKind K) { 3894 switch (K) { 3895 case CXCursor_UnexposedDecl: 3896 case CXCursor_UnexposedExpr: 3897 case CXCursor_UnexposedStmt: 3898 case CXCursor_UnexposedAttr: 3899 return true; 3900 default: 3901 return false; 3902 } 3903} 3904 3905CXCursorKind clang_getCursorKind(CXCursor C) { 3906 return C.kind; 3907} 3908 3909CXSourceLocation clang_getCursorLocation(CXCursor C) { 3910 if (clang_isReference(C.kind)) { 3911 switch (C.kind) { 3912 case CXCursor_ObjCSuperClassRef: { 3913 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3914 = getCursorObjCSuperClassRef(C); 3915 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3916 } 3917 3918 case CXCursor_ObjCProtocolRef: { 3919 std::pair<ObjCProtocolDecl *, SourceLocation> P 3920 = getCursorObjCProtocolRef(C); 3921 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3922 } 3923 3924 case CXCursor_ObjCClassRef: { 3925 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3926 = getCursorObjCClassRef(C); 3927 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3928 } 3929 3930 case CXCursor_TypeRef: { 3931 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3932 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3933 } 3934 3935 case CXCursor_TemplateRef: { 3936 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3937 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3938 } 3939 3940 case CXCursor_NamespaceRef: { 3941 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3942 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3943 } 3944 3945 case CXCursor_MemberRef: { 3946 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3947 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3948 } 3949 3950 case CXCursor_VariableRef: { 3951 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C); 3952 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3953 } 3954 3955 case CXCursor_CXXBaseSpecifier: { 3956 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3957 if (!BaseSpec) 3958 return clang_getNullLocation(); 3959 3960 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3961 return cxloc::translateSourceLocation(getCursorContext(C), 3962 TSInfo->getTypeLoc().getBeginLoc()); 3963 3964 return cxloc::translateSourceLocation(getCursorContext(C), 3965 BaseSpec->getLocStart()); 3966 } 3967 3968 case CXCursor_LabelRef: { 3969 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3970 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3971 } 3972 3973 case CXCursor_OverloadedDeclRef: 3974 return cxloc::translateSourceLocation(getCursorContext(C), 3975 getCursorOverloadedDeclRef(C).second); 3976 3977 default: 3978 // FIXME: Need a way to enumerate all non-reference cases. 3979 llvm_unreachable("Missed a reference kind"); 3980 } 3981 } 3982 3983 if (clang_isExpression(C.kind)) 3984 return cxloc::translateSourceLocation(getCursorContext(C), 3985 getLocationFromExpr(getCursorExpr(C))); 3986 3987 if (clang_isStatement(C.kind)) 3988 return cxloc::translateSourceLocation(getCursorContext(C), 3989 getCursorStmt(C)->getLocStart()); 3990 3991 if (C.kind == CXCursor_PreprocessingDirective) { 3992 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3993 return cxloc::translateSourceLocation(getCursorContext(C), L); 3994 } 3995 3996 if (C.kind == CXCursor_MacroExpansion) { 3997 SourceLocation L 3998 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin(); 3999 return cxloc::translateSourceLocation(getCursorContext(C), L); 4000 } 4001 4002 if (C.kind == CXCursor_MacroDefinition) { 4003 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 4004 return cxloc::translateSourceLocation(getCursorContext(C), L); 4005 } 4006 4007 if (C.kind == CXCursor_InclusionDirective) { 4008 SourceLocation L 4009 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 4010 return cxloc::translateSourceLocation(getCursorContext(C), L); 4011 } 4012 4013 if (!clang_isDeclaration(C.kind)) 4014 return clang_getNullLocation(); 4015 4016 Decl *D = getCursorDecl(C); 4017 if (!D) 4018 return clang_getNullLocation(); 4019 4020 SourceLocation Loc = D->getLocation(); 4021 // FIXME: Multiple variables declared in a single declaration 4022 // currently lack the information needed to correctly determine their 4023 // ranges when accounting for the type-specifier. We use context 4024 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4025 // and if so, whether it is the first decl. 4026 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4027 if (!cxcursor::isFirstInDeclGroup(C)) 4028 Loc = VD->getLocation(); 4029 } 4030 4031 // For ObjC methods, give the start location of the method name. 4032 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 4033 Loc = MD->getSelectorStartLoc(); 4034 4035 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 4036} 4037 4038} // end extern "C" 4039 4040CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 4041 assert(TU); 4042 4043 // Guard against an invalid SourceLocation, or we may assert in one 4044 // of the following calls. 4045 if (SLoc.isInvalid()) 4046 return clang_getNullCursor(); 4047 4048 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4049 4050 // Translate the given source location to make it point at the beginning of 4051 // the token under the cursor. 4052 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 4053 CXXUnit->getASTContext().getLangOpts()); 4054 4055 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 4056 if (SLoc.isValid()) { 4057 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 4058 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 4059 /*VisitPreprocessorLast=*/true, 4060 /*VisitIncludedEntities=*/false, 4061 SourceLocation(SLoc)); 4062 CursorVis.visitFileRegion(); 4063 } 4064 4065 return Result; 4066} 4067 4068static SourceRange getRawCursorExtent(CXCursor C) { 4069 if (clang_isReference(C.kind)) { 4070 switch (C.kind) { 4071 case CXCursor_ObjCSuperClassRef: 4072 return getCursorObjCSuperClassRef(C).second; 4073 4074 case CXCursor_ObjCProtocolRef: 4075 return getCursorObjCProtocolRef(C).second; 4076 4077 case CXCursor_ObjCClassRef: 4078 return getCursorObjCClassRef(C).second; 4079 4080 case CXCursor_TypeRef: 4081 return getCursorTypeRef(C).second; 4082 4083 case CXCursor_TemplateRef: 4084 return getCursorTemplateRef(C).second; 4085 4086 case CXCursor_NamespaceRef: 4087 return getCursorNamespaceRef(C).second; 4088 4089 case CXCursor_MemberRef: 4090 return getCursorMemberRef(C).second; 4091 4092 case CXCursor_CXXBaseSpecifier: 4093 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 4094 4095 case CXCursor_LabelRef: 4096 return getCursorLabelRef(C).second; 4097 4098 case CXCursor_OverloadedDeclRef: 4099 return getCursorOverloadedDeclRef(C).second; 4100 4101 case CXCursor_VariableRef: 4102 return getCursorVariableRef(C).second; 4103 4104 default: 4105 // FIXME: Need a way to enumerate all non-reference cases. 4106 llvm_unreachable("Missed a reference kind"); 4107 } 4108 } 4109 4110 if (clang_isExpression(C.kind)) 4111 return getCursorExpr(C)->getSourceRange(); 4112 4113 if (clang_isStatement(C.kind)) 4114 return getCursorStmt(C)->getSourceRange(); 4115 4116 if (clang_isAttribute(C.kind)) 4117 return getCursorAttr(C)->getRange(); 4118 4119 if (C.kind == CXCursor_PreprocessingDirective) 4120 return cxcursor::getCursorPreprocessingDirective(C); 4121 4122 if (C.kind == CXCursor_MacroExpansion) { 4123 ASTUnit *TU = getCursorASTUnit(C); 4124 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange(); 4125 return TU->mapRangeFromPreamble(Range); 4126 } 4127 4128 if (C.kind == CXCursor_MacroDefinition) { 4129 ASTUnit *TU = getCursorASTUnit(C); 4130 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 4131 return TU->mapRangeFromPreamble(Range); 4132 } 4133 4134 if (C.kind == CXCursor_InclusionDirective) { 4135 ASTUnit *TU = getCursorASTUnit(C); 4136 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 4137 return TU->mapRangeFromPreamble(Range); 4138 } 4139 4140 if (C.kind == CXCursor_TranslationUnit) { 4141 ASTUnit *TU = getCursorASTUnit(C); 4142 FileID MainID = TU->getSourceManager().getMainFileID(); 4143 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 4144 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 4145 return SourceRange(Start, End); 4146 } 4147 4148 if (clang_isDeclaration(C.kind)) { 4149 Decl *D = cxcursor::getCursorDecl(C); 4150 if (!D) 4151 return SourceRange(); 4152 4153 SourceRange R = D->getSourceRange(); 4154 // FIXME: Multiple variables declared in a single declaration 4155 // currently lack the information needed to correctly determine their 4156 // ranges when accounting for the type-specifier. We use context 4157 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4158 // and if so, whether it is the first decl. 4159 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4160 if (!cxcursor::isFirstInDeclGroup(C)) 4161 R.setBegin(VD->getLocation()); 4162 } 4163 return R; 4164 } 4165 return SourceRange(); 4166} 4167 4168/// \brief Retrieves the "raw" cursor extent, which is then extended to include 4169/// the decl-specifier-seq for declarations. 4170static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 4171 if (clang_isDeclaration(C.kind)) { 4172 Decl *D = cxcursor::getCursorDecl(C); 4173 if (!D) 4174 return SourceRange(); 4175 4176 SourceRange R = D->getSourceRange(); 4177 4178 // Adjust the start of the location for declarations preceded by 4179 // declaration specifiers. 4180 SourceLocation StartLoc; 4181 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4182 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 4183 StartLoc = TI->getTypeLoc().getLocStart(); 4184 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 4185 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 4186 StartLoc = TI->getTypeLoc().getLocStart(); 4187 } 4188 4189 if (StartLoc.isValid() && R.getBegin().isValid() && 4190 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 4191 R.setBegin(StartLoc); 4192 4193 // FIXME: Multiple variables declared in a single declaration 4194 // currently lack the information needed to correctly determine their 4195 // ranges when accounting for the type-specifier. We use context 4196 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4197 // and if so, whether it is the first decl. 4198 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4199 if (!cxcursor::isFirstInDeclGroup(C)) 4200 R.setBegin(VD->getLocation()); 4201 } 4202 4203 return R; 4204 } 4205 4206 return getRawCursorExtent(C); 4207} 4208 4209extern "C" { 4210 4211CXSourceRange clang_getCursorExtent(CXCursor C) { 4212 SourceRange R = getRawCursorExtent(C); 4213 if (R.isInvalid()) 4214 return clang_getNullRange(); 4215 4216 return cxloc::translateSourceRange(getCursorContext(C), R); 4217} 4218 4219CXCursor clang_getCursorReferenced(CXCursor C) { 4220 if (clang_isInvalid(C.kind)) 4221 return clang_getNullCursor(); 4222 4223 CXTranslationUnit tu = getCursorTU(C); 4224 if (clang_isDeclaration(C.kind)) { 4225 Decl *D = getCursorDecl(C); 4226 if (!D) 4227 return clang_getNullCursor(); 4228 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 4229 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 4230 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D)) 4231 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 4232 return MakeCXCursor(Property, tu); 4233 4234 return C; 4235 } 4236 4237 if (clang_isExpression(C.kind)) { 4238 Expr *E = getCursorExpr(C); 4239 Decl *D = getDeclFromExpr(E); 4240 if (D) { 4241 CXCursor declCursor = MakeCXCursor(D, tu); 4242 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 4243 declCursor); 4244 return declCursor; 4245 } 4246 4247 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 4248 return MakeCursorOverloadedDeclRef(Ovl, tu); 4249 4250 return clang_getNullCursor(); 4251 } 4252 4253 if (clang_isStatement(C.kind)) { 4254 Stmt *S = getCursorStmt(C); 4255 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 4256 if (LabelDecl *label = Goto->getLabel()) 4257 if (LabelStmt *labelS = label->getStmt()) 4258 return MakeCXCursor(labelS, getCursorDecl(C), tu); 4259 4260 return clang_getNullCursor(); 4261 } 4262 4263 if (C.kind == CXCursor_MacroExpansion) { 4264 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition()) 4265 return MakeMacroDefinitionCursor(Def, tu); 4266 } 4267 4268 if (!clang_isReference(C.kind)) 4269 return clang_getNullCursor(); 4270 4271 switch (C.kind) { 4272 case CXCursor_ObjCSuperClassRef: 4273 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 4274 4275 case CXCursor_ObjCProtocolRef: { 4276 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 4277 if (ObjCProtocolDecl *Def = Prot->getDefinition()) 4278 return MakeCXCursor(Def, tu); 4279 4280 return MakeCXCursor(Prot, tu); 4281 } 4282 4283 case CXCursor_ObjCClassRef: { 4284 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 4285 if (ObjCInterfaceDecl *Def = Class->getDefinition()) 4286 return MakeCXCursor(Def, tu); 4287 4288 return MakeCXCursor(Class, tu); 4289 } 4290 4291 case CXCursor_TypeRef: 4292 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 4293 4294 case CXCursor_TemplateRef: 4295 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 4296 4297 case CXCursor_NamespaceRef: 4298 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 4299 4300 case CXCursor_MemberRef: 4301 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 4302 4303 case CXCursor_CXXBaseSpecifier: { 4304 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 4305 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 4306 tu )); 4307 } 4308 4309 case CXCursor_LabelRef: 4310 // FIXME: We end up faking the "parent" declaration here because we 4311 // don't want to make CXCursor larger. 4312 return MakeCXCursor(getCursorLabelRef(C).first, 4313 static_cast<ASTUnit*>(tu->TUData)->getASTContext() 4314 .getTranslationUnitDecl(), 4315 tu); 4316 4317 case CXCursor_OverloadedDeclRef: 4318 return C; 4319 4320 case CXCursor_VariableRef: 4321 return MakeCXCursor(getCursorVariableRef(C).first, tu); 4322 4323 default: 4324 // We would prefer to enumerate all non-reference cursor kinds here. 4325 llvm_unreachable("Unhandled reference cursor kind"); 4326 } 4327} 4328 4329CXCursor clang_getCursorDefinition(CXCursor C) { 4330 if (clang_isInvalid(C.kind)) 4331 return clang_getNullCursor(); 4332 4333 CXTranslationUnit TU = getCursorTU(C); 4334 4335 bool WasReference = false; 4336 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 4337 C = clang_getCursorReferenced(C); 4338 WasReference = true; 4339 } 4340 4341 if (C.kind == CXCursor_MacroExpansion) 4342 return clang_getCursorReferenced(C); 4343 4344 if (!clang_isDeclaration(C.kind)) 4345 return clang_getNullCursor(); 4346 4347 Decl *D = getCursorDecl(C); 4348 if (!D) 4349 return clang_getNullCursor(); 4350 4351 switch (D->getKind()) { 4352 // Declaration kinds that don't really separate the notions of 4353 // declaration and definition. 4354 case Decl::Namespace: 4355 case Decl::Typedef: 4356 case Decl::TypeAlias: 4357 case Decl::TypeAliasTemplate: 4358 case Decl::TemplateTypeParm: 4359 case Decl::EnumConstant: 4360 case Decl::Field: 4361 case Decl::IndirectField: 4362 case Decl::ObjCIvar: 4363 case Decl::ObjCAtDefsField: 4364 case Decl::ImplicitParam: 4365 case Decl::ParmVar: 4366 case Decl::NonTypeTemplateParm: 4367 case Decl::TemplateTemplateParm: 4368 case Decl::ObjCCategoryImpl: 4369 case Decl::ObjCImplementation: 4370 case Decl::AccessSpec: 4371 case Decl::LinkageSpec: 4372 case Decl::ObjCPropertyImpl: 4373 case Decl::FileScopeAsm: 4374 case Decl::StaticAssert: 4375 case Decl::Block: 4376 case Decl::Label: // FIXME: Is this right?? 4377 case Decl::ClassScopeFunctionSpecialization: 4378 case Decl::Import: 4379 return C; 4380 4381 // Declaration kinds that don't make any sense here, but are 4382 // nonetheless harmless. 4383 case Decl::TranslationUnit: 4384 break; 4385 4386 // Declaration kinds for which the definition is not resolvable. 4387 case Decl::UnresolvedUsingTypename: 4388 case Decl::UnresolvedUsingValue: 4389 break; 4390 4391 case Decl::UsingDirective: 4392 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 4393 TU); 4394 4395 case Decl::NamespaceAlias: 4396 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 4397 4398 case Decl::Enum: 4399 case Decl::Record: 4400 case Decl::CXXRecord: 4401 case Decl::ClassTemplateSpecialization: 4402 case Decl::ClassTemplatePartialSpecialization: 4403 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 4404 return MakeCXCursor(Def, TU); 4405 return clang_getNullCursor(); 4406 4407 case Decl::Function: 4408 case Decl::CXXMethod: 4409 case Decl::CXXConstructor: 4410 case Decl::CXXDestructor: 4411 case Decl::CXXConversion: { 4412 const FunctionDecl *Def = 0; 4413 if (cast<FunctionDecl>(D)->getBody(Def)) 4414 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU); 4415 return clang_getNullCursor(); 4416 } 4417 4418 case Decl::Var: { 4419 // Ask the variable if it has a definition. 4420 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 4421 return MakeCXCursor(Def, TU); 4422 return clang_getNullCursor(); 4423 } 4424 4425 case Decl::FunctionTemplate: { 4426 const FunctionDecl *Def = 0; 4427 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 4428 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 4429 return clang_getNullCursor(); 4430 } 4431 4432 case Decl::ClassTemplate: { 4433 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 4434 ->getDefinition()) 4435 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 4436 TU); 4437 return clang_getNullCursor(); 4438 } 4439 4440 case Decl::Using: 4441 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 4442 D->getLocation(), TU); 4443 4444 case Decl::UsingShadow: 4445 return clang_getCursorDefinition( 4446 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 4447 TU)); 4448 4449 case Decl::ObjCMethod: { 4450 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 4451 if (Method->isThisDeclarationADefinition()) 4452 return C; 4453 4454 // Dig out the method definition in the associated 4455 // @implementation, if we have it. 4456 // FIXME: The ASTs should make finding the definition easier. 4457 if (ObjCInterfaceDecl *Class 4458 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 4459 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 4460 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 4461 Method->isInstanceMethod())) 4462 if (Def->isThisDeclarationADefinition()) 4463 return MakeCXCursor(Def, TU); 4464 4465 return clang_getNullCursor(); 4466 } 4467 4468 case Decl::ObjCCategory: 4469 if (ObjCCategoryImplDecl *Impl 4470 = cast<ObjCCategoryDecl>(D)->getImplementation()) 4471 return MakeCXCursor(Impl, TU); 4472 return clang_getNullCursor(); 4473 4474 case Decl::ObjCProtocol: 4475 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition()) 4476 return MakeCXCursor(Def, TU); 4477 return clang_getNullCursor(); 4478 4479 case Decl::ObjCInterface: { 4480 // There are two notions of a "definition" for an Objective-C 4481 // class: the interface and its implementation. When we resolved a 4482 // reference to an Objective-C class, produce the @interface as 4483 // the definition; when we were provided with the interface, 4484 // produce the @implementation as the definition. 4485 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 4486 if (WasReference) { 4487 if (ObjCInterfaceDecl *Def = IFace->getDefinition()) 4488 return MakeCXCursor(Def, TU); 4489 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 4490 return MakeCXCursor(Impl, TU); 4491 return clang_getNullCursor(); 4492 } 4493 4494 case Decl::ObjCProperty: 4495 // FIXME: We don't really know where to find the 4496 // ObjCPropertyImplDecls that implement this property. 4497 return clang_getNullCursor(); 4498 4499 case Decl::ObjCCompatibleAlias: 4500 if (ObjCInterfaceDecl *Class 4501 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 4502 if (ObjCInterfaceDecl *Def = Class->getDefinition()) 4503 return MakeCXCursor(Def, TU); 4504 4505 return clang_getNullCursor(); 4506 4507 case Decl::Friend: 4508 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 4509 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4510 return clang_getNullCursor(); 4511 4512 case Decl::FriendTemplate: 4513 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 4514 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4515 return clang_getNullCursor(); 4516 } 4517 4518 return clang_getNullCursor(); 4519} 4520 4521unsigned clang_isCursorDefinition(CXCursor C) { 4522 if (!clang_isDeclaration(C.kind)) 4523 return 0; 4524 4525 return clang_getCursorDefinition(C) == C; 4526} 4527 4528CXCursor clang_getCanonicalCursor(CXCursor C) { 4529 if (!clang_isDeclaration(C.kind)) 4530 return C; 4531 4532 if (Decl *D = getCursorDecl(C)) { 4533 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) 4534 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 4535 return MakeCXCursor(CatD, getCursorTU(C)); 4536 4537 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 4538 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 4539 return MakeCXCursor(IFD, getCursorTU(C)); 4540 4541 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 4542 } 4543 4544 return C; 4545} 4546 4547int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 4548 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 4549} 4550 4551unsigned clang_getNumOverloadedDecls(CXCursor C) { 4552 if (C.kind != CXCursor_OverloadedDeclRef) 4553 return 0; 4554 4555 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4556 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4557 return E->getNumDecls(); 4558 4559 if (OverloadedTemplateStorage *S 4560 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4561 return S->size(); 4562 4563 Decl *D = Storage.get<Decl*>(); 4564 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 4565 return Using->shadow_size(); 4566 4567 return 0; 4568} 4569 4570CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 4571 if (cursor.kind != CXCursor_OverloadedDeclRef) 4572 return clang_getNullCursor(); 4573 4574 if (index >= clang_getNumOverloadedDecls(cursor)) 4575 return clang_getNullCursor(); 4576 4577 CXTranslationUnit TU = getCursorTU(cursor); 4578 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 4579 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4580 return MakeCXCursor(E->decls_begin()[index], TU); 4581 4582 if (OverloadedTemplateStorage *S 4583 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4584 return MakeCXCursor(S->begin()[index], TU); 4585 4586 Decl *D = Storage.get<Decl*>(); 4587 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 4588 // FIXME: This is, unfortunately, linear time. 4589 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 4590 std::advance(Pos, index); 4591 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 4592 } 4593 4594 return clang_getNullCursor(); 4595} 4596 4597void clang_getDefinitionSpellingAndExtent(CXCursor C, 4598 const char **startBuf, 4599 const char **endBuf, 4600 unsigned *startLine, 4601 unsigned *startColumn, 4602 unsigned *endLine, 4603 unsigned *endColumn) { 4604 assert(getCursorDecl(C) && "CXCursor has null decl"); 4605 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 4606 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 4607 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 4608 4609 SourceManager &SM = FD->getASTContext().getSourceManager(); 4610 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 4611 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 4612 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 4613 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 4614 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 4615 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 4616} 4617 4618 4619CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 4620 unsigned PieceIndex) { 4621 RefNamePieces Pieces; 4622 4623 switch (C.kind) { 4624 case CXCursor_MemberRefExpr: 4625 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 4626 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 4627 E->getQualifierLoc().getSourceRange()); 4628 break; 4629 4630 case CXCursor_DeclRefExpr: 4631 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) 4632 Pieces = buildPieces(NameFlags, false, E->getNameInfo(), 4633 E->getQualifierLoc().getSourceRange(), 4634 E->getOptionalExplicitTemplateArgs()); 4635 break; 4636 4637 case CXCursor_CallExpr: 4638 if (CXXOperatorCallExpr *OCE = 4639 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 4640 Expr *Callee = OCE->getCallee(); 4641 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 4642 Callee = ICE->getSubExpr(); 4643 4644 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 4645 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 4646 DRE->getQualifierLoc().getSourceRange()); 4647 } 4648 break; 4649 4650 default: 4651 break; 4652 } 4653 4654 if (Pieces.empty()) { 4655 if (PieceIndex == 0) 4656 return clang_getCursorExtent(C); 4657 } else if (PieceIndex < Pieces.size()) { 4658 SourceRange R = Pieces[PieceIndex]; 4659 if (R.isValid()) 4660 return cxloc::translateSourceRange(getCursorContext(C), R); 4661 } 4662 4663 return clang_getNullRange(); 4664} 4665 4666void clang_enableStackTraces(void) { 4667 llvm::sys::PrintStackTraceOnErrorSignal(); 4668} 4669 4670void clang_executeOnThread(void (*fn)(void*), void *user_data, 4671 unsigned stack_size) { 4672 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 4673} 4674 4675} // end: extern "C" 4676 4677//===----------------------------------------------------------------------===// 4678// Token-based Operations. 4679//===----------------------------------------------------------------------===// 4680 4681/* CXToken layout: 4682 * int_data[0]: a CXTokenKind 4683 * int_data[1]: starting token location 4684 * int_data[2]: token length 4685 * int_data[3]: reserved 4686 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 4687 * otherwise unused. 4688 */ 4689extern "C" { 4690 4691CXTokenKind clang_getTokenKind(CXToken CXTok) { 4692 return static_cast<CXTokenKind>(CXTok.int_data[0]); 4693} 4694 4695CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 4696 switch (clang_getTokenKind(CXTok)) { 4697 case CXToken_Identifier: 4698 case CXToken_Keyword: 4699 // We know we have an IdentifierInfo*, so use that. 4700 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 4701 ->getNameStart()); 4702 4703 case CXToken_Literal: { 4704 // We have stashed the starting pointer in the ptr_data field. Use it. 4705 const char *Text = static_cast<const char *>(CXTok.ptr_data); 4706 return createCXString(StringRef(Text, CXTok.int_data[2])); 4707 } 4708 4709 case CXToken_Punctuation: 4710 case CXToken_Comment: 4711 break; 4712 } 4713 4714 // We have to find the starting buffer pointer the hard way, by 4715 // deconstructing the source location. 4716 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4717 if (!CXXUnit) 4718 return createCXString(""); 4719 4720 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 4721 std::pair<FileID, unsigned> LocInfo 4722 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 4723 bool Invalid = false; 4724 StringRef Buffer 4725 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 4726 if (Invalid) 4727 return createCXString(""); 4728 4729 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 4730} 4731 4732CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 4733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4734 if (!CXXUnit) 4735 return clang_getNullLocation(); 4736 4737 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 4738 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4739} 4740 4741CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 4742 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4743 if (!CXXUnit) 4744 return clang_getNullRange(); 4745 4746 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 4747 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4748} 4749 4750static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 4751 SmallVectorImpl<CXToken> &CXTokens) { 4752 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4753 std::pair<FileID, unsigned> BeginLocInfo 4754 = SourceMgr.getDecomposedLoc(Range.getBegin()); 4755 std::pair<FileID, unsigned> EndLocInfo 4756 = SourceMgr.getDecomposedLoc(Range.getEnd()); 4757 4758 // Cannot tokenize across files. 4759 if (BeginLocInfo.first != EndLocInfo.first) 4760 return; 4761 4762 // Create a lexer 4763 bool Invalid = false; 4764 StringRef Buffer 4765 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 4766 if (Invalid) 4767 return; 4768 4769 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4770 CXXUnit->getASTContext().getLangOpts(), 4771 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 4772 Lex.SetCommentRetentionState(true); 4773 4774 // Lex tokens until we hit the end of the range. 4775 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 4776 Token Tok; 4777 bool previousWasAt = false; 4778 do { 4779 // Lex the next token 4780 Lex.LexFromRawLexer(Tok); 4781 if (Tok.is(tok::eof)) 4782 break; 4783 4784 // Initialize the CXToken. 4785 CXToken CXTok; 4786 4787 // - Common fields 4788 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 4789 CXTok.int_data[2] = Tok.getLength(); 4790 CXTok.int_data[3] = 0; 4791 4792 // - Kind-specific fields 4793 if (Tok.isLiteral()) { 4794 CXTok.int_data[0] = CXToken_Literal; 4795 CXTok.ptr_data = (void *)Tok.getLiteralData(); 4796 } else if (Tok.is(tok::raw_identifier)) { 4797 // Lookup the identifier to determine whether we have a keyword. 4798 IdentifierInfo *II 4799 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 4800 4801 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 4802 CXTok.int_data[0] = CXToken_Keyword; 4803 } 4804 else { 4805 CXTok.int_data[0] = Tok.is(tok::identifier) 4806 ? CXToken_Identifier 4807 : CXToken_Keyword; 4808 } 4809 CXTok.ptr_data = II; 4810 } else if (Tok.is(tok::comment)) { 4811 CXTok.int_data[0] = CXToken_Comment; 4812 CXTok.ptr_data = 0; 4813 } else { 4814 CXTok.int_data[0] = CXToken_Punctuation; 4815 CXTok.ptr_data = 0; 4816 } 4817 CXTokens.push_back(CXTok); 4818 previousWasAt = Tok.is(tok::at); 4819 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 4820} 4821 4822void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 4823 CXToken **Tokens, unsigned *NumTokens) { 4824 if (Tokens) 4825 *Tokens = 0; 4826 if (NumTokens) 4827 *NumTokens = 0; 4828 4829 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4830 if (!CXXUnit || !Tokens || !NumTokens) 4831 return; 4832 4833 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4834 4835 SourceRange R = cxloc::translateCXSourceRange(Range); 4836 if (R.isInvalid()) 4837 return; 4838 4839 SmallVector<CXToken, 32> CXTokens; 4840 getTokens(CXXUnit, R, CXTokens); 4841 4842 if (CXTokens.empty()) 4843 return; 4844 4845 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 4846 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 4847 *NumTokens = CXTokens.size(); 4848} 4849 4850void clang_disposeTokens(CXTranslationUnit TU, 4851 CXToken *Tokens, unsigned NumTokens) { 4852 free(Tokens); 4853} 4854 4855} // end: extern "C" 4856 4857//===----------------------------------------------------------------------===// 4858// Token annotation APIs. 4859//===----------------------------------------------------------------------===// 4860 4861typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 4862static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4863 CXCursor parent, 4864 CXClientData client_data); 4865static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 4866 CXClientData client_data); 4867 4868namespace { 4869class AnnotateTokensWorker { 4870 AnnotateTokensData &Annotated; 4871 CXToken *Tokens; 4872 CXCursor *Cursors; 4873 unsigned NumTokens; 4874 unsigned TokIdx; 4875 unsigned PreprocessingTokIdx; 4876 CursorVisitor AnnotateVis; 4877 SourceManager &SrcMgr; 4878 bool HasContextSensitiveKeywords; 4879 4880 struct PostChildrenInfo { 4881 CXCursor Cursor; 4882 SourceRange CursorRange; 4883 unsigned BeforeChildrenTokenIdx; 4884 }; 4885 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 4886 4887 bool MoreTokens() const { return TokIdx < NumTokens; } 4888 unsigned NextToken() const { return TokIdx; } 4889 void AdvanceToken() { ++TokIdx; } 4890 SourceLocation GetTokenLoc(unsigned tokI) { 4891 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 4892 } 4893 bool isFunctionMacroToken(unsigned tokI) const { 4894 return Tokens[tokI].int_data[3] != 0; 4895 } 4896 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 4897 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]); 4898 } 4899 4900 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 4901 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 4902 SourceRange); 4903 4904public: 4905 AnnotateTokensWorker(AnnotateTokensData &annotated, 4906 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 4907 CXTranslationUnit tu, SourceRange RegionOfInterest) 4908 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 4909 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 4910 AnnotateVis(tu, 4911 AnnotateTokensVisitor, this, 4912 /*VisitPreprocessorLast=*/true, 4913 /*VisitIncludedEntities=*/false, 4914 RegionOfInterest, 4915 /*VisitDeclsOnly=*/false, 4916 AnnotateTokensPostChildrenVisitor), 4917 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()), 4918 HasContextSensitiveKeywords(false) { } 4919 4920 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 4921 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 4922 bool postVisitChildren(CXCursor cursor); 4923 void AnnotateTokens(); 4924 4925 /// \brief Determine whether the annotator saw any cursors that have 4926 /// context-sensitive keywords. 4927 bool hasContextSensitiveKeywords() const { 4928 return HasContextSensitiveKeywords; 4929 } 4930 4931 ~AnnotateTokensWorker() { 4932 assert(PostChildrenInfos.empty()); 4933 } 4934}; 4935} 4936 4937void AnnotateTokensWorker::AnnotateTokens() { 4938 // Walk the AST within the region of interest, annotating tokens 4939 // along the way. 4940 AnnotateVis.visitFileRegion(); 4941 4942 for (unsigned I = 0 ; I < TokIdx ; ++I) { 4943 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4944 if (Pos != Annotated.end() && !clang_isPreprocessing(Cursors[I].kind)) 4945 Cursors[I] = Pos->second; 4946 } 4947 4948 // Finish up annotating any tokens left. 4949 if (!MoreTokens()) 4950 return; 4951 4952 const CXCursor &C = clang_getNullCursor(); 4953 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 4954 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind)) 4955 continue; 4956 4957 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4958 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 4959 } 4960} 4961 4962/// \brief It annotates and advances tokens with a cursor until the comparison 4963//// between the cursor location and the source range is the same as 4964/// \arg compResult. 4965/// 4966/// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 4967/// Pass RangeOverlap to annotate tokens inside a range. 4968void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC, 4969 RangeComparisonResult compResult, 4970 SourceRange range) { 4971 while (MoreTokens()) { 4972 const unsigned I = NextToken(); 4973 if (isFunctionMacroToken(I)) 4974 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range); 4975 4976 SourceLocation TokLoc = GetTokenLoc(I); 4977 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 4978 Cursors[I] = updateC; 4979 AdvanceToken(); 4980 continue; 4981 } 4982 break; 4983 } 4984} 4985 4986/// \brief Special annotation handling for macro argument tokens. 4987void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 4988 CXCursor updateC, 4989 RangeComparisonResult compResult, 4990 SourceRange range) { 4991 assert(MoreTokens()); 4992 assert(isFunctionMacroToken(NextToken()) && 4993 "Should be called only for macro arg tokens"); 4994 4995 // This works differently than annotateAndAdvanceTokens; because expanded 4996 // macro arguments can have arbitrary translation-unit source order, we do not 4997 // advance the token index one by one until a token fails the range test. 4998 // We only advance once past all of the macro arg tokens if all of them 4999 // pass the range test. If one of them fails we keep the token index pointing 5000 // at the start of the macro arg tokens so that the failing token will be 5001 // annotated by a subsequent annotation try. 5002 5003 bool atLeastOneCompFail = false; 5004 5005 unsigned I = NextToken(); 5006 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 5007 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 5008 if (TokLoc.isFileID()) 5009 continue; // not macro arg token, it's parens or comma. 5010 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 5011 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 5012 Cursors[I] = updateC; 5013 } else 5014 atLeastOneCompFail = true; 5015 } 5016 5017 if (!atLeastOneCompFail) 5018 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 5019} 5020 5021enum CXChildVisitResult 5022AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 5023 CXSourceLocation Loc = clang_getCursorLocation(cursor); 5024 SourceRange cursorRange = getRawCursorExtent(cursor); 5025 if (cursorRange.isInvalid()) 5026 return CXChildVisit_Recurse; 5027 5028 if (!HasContextSensitiveKeywords) { 5029 // Objective-C properties can have context-sensitive keywords. 5030 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 5031 if (ObjCPropertyDecl *Property 5032 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 5033 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; 5034 } 5035 // Objective-C methods can have context-sensitive keywords. 5036 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 5037 cursor.kind == CXCursor_ObjCClassMethodDecl) { 5038 if (ObjCMethodDecl *Method 5039 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5040 if (Method->getObjCDeclQualifier()) 5041 HasContextSensitiveKeywords = true; 5042 else { 5043 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 5044 PEnd = Method->param_end(); 5045 P != PEnd; ++P) { 5046 if ((*P)->getObjCDeclQualifier()) { 5047 HasContextSensitiveKeywords = true; 5048 break; 5049 } 5050 } 5051 } 5052 } 5053 } 5054 // C++ methods can have context-sensitive keywords. 5055 else if (cursor.kind == CXCursor_CXXMethod) { 5056 if (CXXMethodDecl *Method 5057 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 5058 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 5059 HasContextSensitiveKeywords = true; 5060 } 5061 } 5062 // C++ classes can have context-sensitive keywords. 5063 else if (cursor.kind == CXCursor_StructDecl || 5064 cursor.kind == CXCursor_ClassDecl || 5065 cursor.kind == CXCursor_ClassTemplate || 5066 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 5067 if (Decl *D = getCursorDecl(cursor)) 5068 if (D->hasAttr<FinalAttr>()) 5069 HasContextSensitiveKeywords = true; 5070 } 5071 } 5072 5073 if (clang_isPreprocessing(cursor.kind)) { 5074 // Items in the preprocessing record are kept separate from items in 5075 // declarations, so we keep a separate token index. 5076 unsigned SavedTokIdx = TokIdx; 5077 TokIdx = PreprocessingTokIdx; 5078 5079 // Skip tokens up until we catch up to the beginning of the preprocessing 5080 // entry. 5081 while (MoreTokens()) { 5082 const unsigned I = NextToken(); 5083 SourceLocation TokLoc = GetTokenLoc(I); 5084 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 5085 case RangeBefore: 5086 AdvanceToken(); 5087 continue; 5088 case RangeAfter: 5089 case RangeOverlap: 5090 break; 5091 } 5092 break; 5093 } 5094 5095 // Look at all of the tokens within this range. 5096 while (MoreTokens()) { 5097 const unsigned I = NextToken(); 5098 SourceLocation TokLoc = GetTokenLoc(I); 5099 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 5100 case RangeBefore: 5101 llvm_unreachable("Infeasible"); 5102 case RangeAfter: 5103 break; 5104 case RangeOverlap: 5105 Cursors[I] = cursor; 5106 AdvanceToken(); 5107 // For macro expansions, just note where the beginning of the macro 5108 // expansion occurs. 5109 if (cursor.kind == CXCursor_MacroExpansion) 5110 break; 5111 continue; 5112 } 5113 break; 5114 } 5115 5116 // Save the preprocessing token index; restore the non-preprocessing 5117 // token index. 5118 PreprocessingTokIdx = TokIdx; 5119 TokIdx = SavedTokIdx; 5120 return CXChildVisit_Recurse; 5121 } 5122 5123 if (cursorRange.isInvalid()) 5124 return CXChildVisit_Continue; 5125 5126 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 5127 5128 // Adjust the annotated range based specific declarations. 5129 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 5130 if (clang_isDeclaration(cursorK)) { 5131 Decl *D = cxcursor::getCursorDecl(cursor); 5132 5133 SourceLocation StartLoc; 5134 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) { 5135 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 5136 StartLoc = TI->getTypeLoc().getLocStart(); 5137 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) { 5138 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 5139 StartLoc = TI->getTypeLoc().getLocStart(); 5140 } 5141 5142 if (StartLoc.isValid() && L.isValid() && 5143 SrcMgr.isBeforeInTranslationUnit(StartLoc, L)) 5144 cursorRange.setBegin(StartLoc); 5145 } 5146 5147 // If the location of the cursor occurs within a macro instantiation, record 5148 // the spelling location of the cursor in our annotation map. We can then 5149 // paper over the token labelings during a post-processing step to try and 5150 // get cursor mappings for tokens that are the *arguments* of a macro 5151 // instantiation. 5152 if (L.isMacroID()) { 5153 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 5154 // Only invalidate the old annotation if it isn't part of a preprocessing 5155 // directive. Here we assume that the default construction of CXCursor 5156 // results in CXCursor.kind being an initialized value (i.e., 0). If 5157 // this isn't the case, we can fix by doing lookup + insertion. 5158 5159 CXCursor &oldC = Annotated[rawEncoding]; 5160 if (!clang_isPreprocessing(oldC.kind)) 5161 oldC = cursor; 5162 } 5163 5164 const enum CXCursorKind K = clang_getCursorKind(parent); 5165 const CXCursor updateC = 5166 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 5167 ? clang_getNullCursor() : parent; 5168 5169 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 5170 5171 // Avoid having the cursor of an expression "overwrite" the annotation of the 5172 // variable declaration that it belongs to. 5173 // This can happen for C++ constructor expressions whose range generally 5174 // include the variable declaration, e.g.: 5175 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 5176 if (clang_isExpression(cursorK)) { 5177 Expr *E = getCursorExpr(cursor); 5178 if (Decl *D = getCursorParentDecl(cursor)) { 5179 const unsigned I = NextToken(); 5180 if (E->getLocStart().isValid() && D->getLocation().isValid() && 5181 E->getLocStart() == D->getLocation() && 5182 E->getLocStart() == GetTokenLoc(I)) { 5183 Cursors[I] = updateC; 5184 AdvanceToken(); 5185 } 5186 } 5187 } 5188 5189 // Before recursing into the children keep some state that we are going 5190 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 5191 // extra work after the child nodes are visited. 5192 // Note that we don't call VisitChildren here to avoid traversing statements 5193 // code-recursively which can blow the stack. 5194 5195 PostChildrenInfo Info; 5196 Info.Cursor = cursor; 5197 Info.CursorRange = cursorRange; 5198 Info.BeforeChildrenTokenIdx = NextToken(); 5199 PostChildrenInfos.push_back(Info); 5200 5201 return CXChildVisit_Recurse; 5202} 5203 5204bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 5205 if (PostChildrenInfos.empty()) 5206 return false; 5207 const PostChildrenInfo &Info = PostChildrenInfos.back(); 5208 if (!clang_equalCursors(Info.Cursor, cursor)) 5209 return false; 5210 5211 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 5212 const unsigned AfterChildren = NextToken(); 5213 SourceRange cursorRange = Info.CursorRange; 5214 5215 // Scan the tokens that are at the end of the cursor, but are not captured 5216 // but the child cursors. 5217 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 5218 5219 // Scan the tokens that are at the beginning of the cursor, but are not 5220 // capture by the child cursors. 5221 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 5222 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 5223 break; 5224 5225 Cursors[I] = cursor; 5226 } 5227 5228 PostChildrenInfos.pop_back(); 5229 return false; 5230} 5231 5232static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 5233 CXCursor parent, 5234 CXClientData client_data) { 5235 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 5236} 5237 5238static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 5239 CXClientData client_data) { 5240 return static_cast<AnnotateTokensWorker*>(client_data)-> 5241 postVisitChildren(cursor); 5242} 5243 5244namespace { 5245 5246/// \brief Uses the macro expansions in the preprocessing record to find 5247/// and mark tokens that are macro arguments. This info is used by the 5248/// AnnotateTokensWorker. 5249class MarkMacroArgTokensVisitor { 5250 SourceManager &SM; 5251 CXToken *Tokens; 5252 unsigned NumTokens; 5253 unsigned CurIdx; 5254 5255public: 5256 MarkMacroArgTokensVisitor(SourceManager &SM, 5257 CXToken *tokens, unsigned numTokens) 5258 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { } 5259 5260 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 5261 if (cursor.kind != CXCursor_MacroExpansion) 5262 return CXChildVisit_Continue; 5263 5264 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange(); 5265 if (macroRange.getBegin() == macroRange.getEnd()) 5266 return CXChildVisit_Continue; // it's not a function macro. 5267 5268 for (; CurIdx < NumTokens; ++CurIdx) { 5269 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 5270 macroRange.getBegin())) 5271 break; 5272 } 5273 5274 if (CurIdx == NumTokens) 5275 return CXChildVisit_Break; 5276 5277 for (; CurIdx < NumTokens; ++CurIdx) { 5278 SourceLocation tokLoc = getTokenLoc(CurIdx); 5279 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 5280 break; 5281 5282 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 5283 } 5284 5285 if (CurIdx == NumTokens) 5286 return CXChildVisit_Break; 5287 5288 return CXChildVisit_Continue; 5289 } 5290 5291private: 5292 SourceLocation getTokenLoc(unsigned tokI) { 5293 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 5294 } 5295 5296 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 5297 // The third field is reserved and currently not used. Use it here 5298 // to mark macro arg expanded tokens with their expanded locations. 5299 Tokens[tokI].int_data[3] = loc.getRawEncoding(); 5300 } 5301}; 5302 5303} // end anonymous namespace 5304 5305static CXChildVisitResult 5306MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 5307 CXClientData client_data) { 5308 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor, 5309 parent); 5310} 5311 5312namespace { 5313 struct clang_annotateTokens_Data { 5314 CXTranslationUnit TU; 5315 ASTUnit *CXXUnit; 5316 CXToken *Tokens; 5317 unsigned NumTokens; 5318 CXCursor *Cursors; 5319 }; 5320} 5321 5322static void annotatePreprocessorTokens(CXTranslationUnit TU, 5323 SourceRange RegionOfInterest, 5324 AnnotateTokensData &Annotated) { 5325 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 5326 5327 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 5328 std::pair<FileID, unsigned> BeginLocInfo 5329 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 5330 std::pair<FileID, unsigned> EndLocInfo 5331 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 5332 5333 if (BeginLocInfo.first != EndLocInfo.first) 5334 return; 5335 5336 StringRef Buffer; 5337 bool Invalid = false; 5338 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 5339 if (Buffer.empty() || Invalid) 5340 return; 5341 5342 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 5343 CXXUnit->getASTContext().getLangOpts(), 5344 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 5345 Buffer.end()); 5346 Lex.SetCommentRetentionState(true); 5347 5348 // Lex tokens in raw mode until we hit the end of the range, to avoid 5349 // entering #includes or expanding macros. 5350 while (true) { 5351 Token Tok; 5352 Lex.LexFromRawLexer(Tok); 5353 5354 reprocess: 5355 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 5356 // We have found a preprocessing directive. Gobble it up so that we 5357 // don't see it while preprocessing these tokens later, but keep track 5358 // of all of the token locations inside this preprocessing directive so 5359 // that we can annotate them appropriately. 5360 // 5361 // FIXME: Some simple tests here could identify macro definitions and 5362 // #undefs, to provide specific cursor kinds for those. 5363 SmallVector<SourceLocation, 32> Locations; 5364 do { 5365 Locations.push_back(Tok.getLocation()); 5366 Lex.LexFromRawLexer(Tok); 5367 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 5368 5369 using namespace cxcursor; 5370 CXCursor Cursor 5371 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 5372 Locations.back()), 5373 TU); 5374 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 5375 Annotated[Locations[I].getRawEncoding()] = Cursor; 5376 } 5377 5378 if (Tok.isAtStartOfLine()) 5379 goto reprocess; 5380 5381 continue; 5382 } 5383 5384 if (Tok.is(tok::eof)) 5385 break; 5386 } 5387} 5388 5389// This gets run a separate thread to avoid stack blowout. 5390static void clang_annotateTokensImpl(void *UserData) { 5391 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU; 5392 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit; 5393 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens; 5394 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens; 5395 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors; 5396 5397 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 5398 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 5399 setThreadBackgroundPriority(); 5400 5401 // Determine the region of interest, which contains all of the tokens. 5402 SourceRange RegionOfInterest; 5403 RegionOfInterest.setBegin( 5404 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 5405 RegionOfInterest.setEnd( 5406 cxloc::translateSourceLocation(clang_getTokenLocation(TU, 5407 Tokens[NumTokens-1]))); 5408 5409 // A mapping from the source locations found when re-lexing or traversing the 5410 // region of interest to the corresponding cursors. 5411 AnnotateTokensData Annotated; 5412 5413 // Relex the tokens within the source range to look for preprocessing 5414 // directives. 5415 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated); 5416 5417 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 5418 // Search and mark tokens that are macro argument expansions. 5419 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), 5420 Tokens, NumTokens); 5421 CursorVisitor MacroArgMarker(TU, 5422 MarkMacroArgTokensVisitorDelegate, &Visitor, 5423 /*VisitPreprocessorLast=*/true, 5424 /*VisitIncludedEntities=*/false, 5425 RegionOfInterest); 5426 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 5427 } 5428 5429 // Annotate all of the source locations in the region of interest that map to 5430 // a specific cursor. 5431 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 5432 TU, RegionOfInterest); 5433 5434 // FIXME: We use a ridiculous stack size here because the data-recursion 5435 // algorithm uses a large stack frame than the non-data recursive version, 5436 // and AnnotationTokensWorker currently transforms the data-recursion 5437 // algorithm back into a traditional recursion by explicitly calling 5438 // VisitChildren(). We will need to remove this explicit recursive call. 5439 W.AnnotateTokens(); 5440 5441 // If we ran into any entities that involve context-sensitive keywords, 5442 // take another pass through the tokens to mark them as such. 5443 if (W.hasContextSensitiveKeywords()) { 5444 for (unsigned I = 0; I != NumTokens; ++I) { 5445 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 5446 continue; 5447 5448 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 5449 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 5450 if (ObjCPropertyDecl *Property 5451 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 5452 if (Property->getPropertyAttributesAsWritten() != 0 && 5453 llvm::StringSwitch<bool>(II->getName()) 5454 .Case("readonly", true) 5455 .Case("assign", true) 5456 .Case("unsafe_unretained", true) 5457 .Case("readwrite", true) 5458 .Case("retain", true) 5459 .Case("copy", true) 5460 .Case("nonatomic", true) 5461 .Case("atomic", true) 5462 .Case("getter", true) 5463 .Case("setter", true) 5464 .Case("strong", true) 5465 .Case("weak", true) 5466 .Default(false)) 5467 Tokens[I].int_data[0] = CXToken_Keyword; 5468 } 5469 continue; 5470 } 5471 5472 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 5473 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 5474 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 5475 if (llvm::StringSwitch<bool>(II->getName()) 5476 .Case("in", true) 5477 .Case("out", true) 5478 .Case("inout", true) 5479 .Case("oneway", true) 5480 .Case("bycopy", true) 5481 .Case("byref", true) 5482 .Default(false)) 5483 Tokens[I].int_data[0] = CXToken_Keyword; 5484 continue; 5485 } 5486 5487 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 5488 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 5489 Tokens[I].int_data[0] = CXToken_Keyword; 5490 continue; 5491 } 5492 } 5493 } 5494} 5495 5496extern "C" { 5497 5498void clang_annotateTokens(CXTranslationUnit TU, 5499 CXToken *Tokens, unsigned NumTokens, 5500 CXCursor *Cursors) { 5501 5502 if (NumTokens == 0 || !Tokens || !Cursors) 5503 return; 5504 5505 // Any token we don't specifically annotate will have a NULL cursor. 5506 CXCursor C = clang_getNullCursor(); 5507 for (unsigned I = 0; I != NumTokens; ++I) 5508 Cursors[I] = C; 5509 5510 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 5511 if (!CXXUnit) 5512 return; 5513 5514 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5515 5516 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors }; 5517 llvm::CrashRecoveryContext CRC; 5518 if (!RunSafely(CRC, clang_annotateTokensImpl, &data, 5519 GetSafetyThreadStackSize() * 2)) { 5520 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 5521 } 5522} 5523 5524} // end: extern "C" 5525 5526//===----------------------------------------------------------------------===// 5527// Operations for querying linkage of a cursor. 5528//===----------------------------------------------------------------------===// 5529 5530extern "C" { 5531CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 5532 if (!clang_isDeclaration(cursor.kind)) 5533 return CXLinkage_Invalid; 5534 5535 Decl *D = cxcursor::getCursorDecl(cursor); 5536 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 5537 switch (ND->getLinkage()) { 5538 case NoLinkage: return CXLinkage_NoLinkage; 5539 case InternalLinkage: return CXLinkage_Internal; 5540 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 5541 case ExternalLinkage: return CXLinkage_External; 5542 }; 5543 5544 return CXLinkage_Invalid; 5545} 5546} // end: extern "C" 5547 5548//===----------------------------------------------------------------------===// 5549// Operations for querying language of a cursor. 5550//===----------------------------------------------------------------------===// 5551 5552static CXLanguageKind getDeclLanguage(const Decl *D) { 5553 if (!D) 5554 return CXLanguage_C; 5555 5556 switch (D->getKind()) { 5557 default: 5558 break; 5559 case Decl::ImplicitParam: 5560 case Decl::ObjCAtDefsField: 5561 case Decl::ObjCCategory: 5562 case Decl::ObjCCategoryImpl: 5563 case Decl::ObjCCompatibleAlias: 5564 case Decl::ObjCImplementation: 5565 case Decl::ObjCInterface: 5566 case Decl::ObjCIvar: 5567 case Decl::ObjCMethod: 5568 case Decl::ObjCProperty: 5569 case Decl::ObjCPropertyImpl: 5570 case Decl::ObjCProtocol: 5571 return CXLanguage_ObjC; 5572 case Decl::CXXConstructor: 5573 case Decl::CXXConversion: 5574 case Decl::CXXDestructor: 5575 case Decl::CXXMethod: 5576 case Decl::CXXRecord: 5577 case Decl::ClassTemplate: 5578 case Decl::ClassTemplatePartialSpecialization: 5579 case Decl::ClassTemplateSpecialization: 5580 case Decl::Friend: 5581 case Decl::FriendTemplate: 5582 case Decl::FunctionTemplate: 5583 case Decl::LinkageSpec: 5584 case Decl::Namespace: 5585 case Decl::NamespaceAlias: 5586 case Decl::NonTypeTemplateParm: 5587 case Decl::StaticAssert: 5588 case Decl::TemplateTemplateParm: 5589 case Decl::TemplateTypeParm: 5590 case Decl::UnresolvedUsingTypename: 5591 case Decl::UnresolvedUsingValue: 5592 case Decl::Using: 5593 case Decl::UsingDirective: 5594 case Decl::UsingShadow: 5595 return CXLanguage_CPlusPlus; 5596 } 5597 5598 return CXLanguage_C; 5599} 5600 5601extern "C" { 5602 5603enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 5604 if (clang_isDeclaration(cursor.kind)) 5605 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 5606 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 5607 return CXAvailability_Available; 5608 5609 switch (D->getAvailability()) { 5610 case AR_Available: 5611 case AR_NotYetIntroduced: 5612 return CXAvailability_Available; 5613 5614 case AR_Deprecated: 5615 return CXAvailability_Deprecated; 5616 5617 case AR_Unavailable: 5618 return CXAvailability_NotAvailable; 5619 } 5620 } 5621 5622 return CXAvailability_Available; 5623} 5624 5625static CXVersion convertVersion(VersionTuple In) { 5626 CXVersion Out = { -1, -1, -1 }; 5627 if (In.empty()) 5628 return Out; 5629 5630 Out.Major = In.getMajor(); 5631 5632 if (llvm::Optional<unsigned> Minor = In.getMinor()) 5633 Out.Minor = *Minor; 5634 else 5635 return Out; 5636 5637 if (llvm::Optional<unsigned> Subminor = In.getSubminor()) 5638 Out.Subminor = *Subminor; 5639 5640 return Out; 5641} 5642 5643int clang_getCursorPlatformAvailability(CXCursor cursor, 5644 int *always_deprecated, 5645 CXString *deprecated_message, 5646 int *always_unavailable, 5647 CXString *unavailable_message, 5648 CXPlatformAvailability *availability, 5649 int availability_size) { 5650 if (always_deprecated) 5651 *always_deprecated = 0; 5652 if (deprecated_message) 5653 *deprecated_message = cxstring::createCXString("", /*DupString=*/false); 5654 if (always_unavailable) 5655 *always_unavailable = 0; 5656 if (unavailable_message) 5657 *unavailable_message = cxstring::createCXString("", /*DupString=*/false); 5658 5659 if (!clang_isDeclaration(cursor.kind)) 5660 return 0; 5661 5662 Decl *D = cxcursor::getCursorDecl(cursor); 5663 if (!D) 5664 return 0; 5665 5666 int N = 0; 5667 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd; 5668 ++A) { 5669 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) { 5670 if (always_deprecated) 5671 *always_deprecated = 1; 5672 if (deprecated_message) 5673 *deprecated_message = cxstring::createCXString(Deprecated->getMessage()); 5674 continue; 5675 } 5676 5677 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) { 5678 if (always_unavailable) 5679 *always_unavailable = 1; 5680 if (unavailable_message) { 5681 *unavailable_message 5682 = cxstring::createCXString(Unavailable->getMessage()); 5683 } 5684 continue; 5685 } 5686 5687 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) { 5688 if (N < availability_size) { 5689 availability[N].Platform 5690 = cxstring::createCXString(Avail->getPlatform()->getName()); 5691 availability[N].Introduced = convertVersion(Avail->getIntroduced()); 5692 availability[N].Deprecated = convertVersion(Avail->getDeprecated()); 5693 availability[N].Obsoleted = convertVersion(Avail->getObsoleted()); 5694 availability[N].Unavailable = Avail->getUnavailable(); 5695 availability[N].Message = cxstring::createCXString(Avail->getMessage()); 5696 } 5697 ++N; 5698 } 5699 } 5700 5701 return N; 5702} 5703 5704void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 5705 clang_disposeString(availability->Platform); 5706 clang_disposeString(availability->Message); 5707} 5708 5709CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 5710 if (clang_isDeclaration(cursor.kind)) 5711 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 5712 5713 return CXLanguage_Invalid; 5714} 5715 5716 /// \brief If the given cursor is the "templated" declaration 5717 /// descibing a class or function template, return the class or 5718 /// function template. 5719static Decl *maybeGetTemplateCursor(Decl *D) { 5720 if (!D) 5721 return 0; 5722 5723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 5724 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 5725 return FunTmpl; 5726 5727 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 5728 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 5729 return ClassTmpl; 5730 5731 return D; 5732} 5733 5734CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 5735 if (clang_isDeclaration(cursor.kind)) { 5736 if (Decl *D = getCursorDecl(cursor)) { 5737 DeclContext *DC = D->getDeclContext(); 5738 if (!DC) 5739 return clang_getNullCursor(); 5740 5741 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 5742 getCursorTU(cursor)); 5743 } 5744 } 5745 5746 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 5747 if (Decl *D = getCursorDecl(cursor)) 5748 return MakeCXCursor(D, getCursorTU(cursor)); 5749 } 5750 5751 return clang_getNullCursor(); 5752} 5753 5754CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 5755 if (clang_isDeclaration(cursor.kind)) { 5756 if (Decl *D = getCursorDecl(cursor)) { 5757 DeclContext *DC = D->getLexicalDeclContext(); 5758 if (!DC) 5759 return clang_getNullCursor(); 5760 5761 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 5762 getCursorTU(cursor)); 5763 } 5764 } 5765 5766 // FIXME: Note that we can't easily compute the lexical context of a 5767 // statement or expression, so we return nothing. 5768 return clang_getNullCursor(); 5769} 5770 5771CXFile clang_getIncludedFile(CXCursor cursor) { 5772 if (cursor.kind != CXCursor_InclusionDirective) 5773 return 0; 5774 5775 InclusionDirective *ID = getCursorInclusionDirective(cursor); 5776 return (void *)ID->getFile(); 5777} 5778 5779CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 5780 if (!clang_isDeclaration(C.kind)) 5781 return clang_getNullRange(); 5782 5783 const Decl *D = getCursorDecl(C); 5784 ASTContext &Context = getCursorContext(C); 5785 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5786 if (!RC) 5787 return clang_getNullRange(); 5788 5789 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 5790} 5791 5792CXString clang_Cursor_getRawCommentText(CXCursor C) { 5793 if (!clang_isDeclaration(C.kind)) 5794 return createCXString((const char *) NULL); 5795 5796 const Decl *D = getCursorDecl(C); 5797 ASTContext &Context = getCursorContext(C); 5798 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5799 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) : 5800 StringRef(); 5801 5802 // Don't duplicate the string because RawText points directly into source 5803 // code. 5804 return createCXString(RawText, false); 5805} 5806 5807CXString clang_Cursor_getBriefCommentText(CXCursor C) { 5808 if (!clang_isDeclaration(C.kind)) 5809 return createCXString((const char *) NULL); 5810 5811 const Decl *D = getCursorDecl(C); 5812 const ASTContext &Context = getCursorContext(C); 5813 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5814 5815 if (RC) { 5816 StringRef BriefText = RC->getBriefText(Context); 5817 5818 // Don't duplicate the string because RawComment ensures that this memory 5819 // will not go away. 5820 return createCXString(BriefText, false); 5821 } 5822 5823 return createCXString((const char *) NULL); 5824} 5825 5826CXComment clang_Cursor_getParsedComment(CXCursor C) { 5827 if (!clang_isDeclaration(C.kind)) 5828 return cxcomment::createCXComment(NULL, NULL); 5829 5830 const Decl *D = getCursorDecl(C); 5831 const ASTContext &Context = getCursorContext(C); 5832 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL); 5833 5834 return cxcomment::createCXComment(FC, getCursorTU(C)); 5835} 5836 5837CXModule clang_Cursor_getModule(CXCursor C) { 5838 if (C.kind == CXCursor_ModuleImportDecl) { 5839 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 5840 return ImportD->getImportedModule(); 5841 } 5842 5843 return 0; 5844} 5845 5846CXModule clang_Module_getParent(CXModule CXMod) { 5847 if (!CXMod) 5848 return 0; 5849 Module *Mod = static_cast<Module*>(CXMod); 5850 return Mod->Parent; 5851} 5852 5853CXString clang_Module_getName(CXModule CXMod) { 5854 if (!CXMod) 5855 return createCXString(""); 5856 Module *Mod = static_cast<Module*>(CXMod); 5857 return createCXString(Mod->Name); 5858} 5859 5860CXString clang_Module_getFullName(CXModule CXMod) { 5861 if (!CXMod) 5862 return createCXString(""); 5863 Module *Mod = static_cast<Module*>(CXMod); 5864 return createCXString(Mod->getFullModuleName()); 5865} 5866 5867unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) { 5868 if (!CXMod) 5869 return 0; 5870 Module *Mod = static_cast<Module*>(CXMod); 5871 return Mod->TopHeaders.size(); 5872} 5873 5874CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) { 5875 if (!CXMod) 5876 return 0; 5877 Module *Mod = static_cast<Module*>(CXMod); 5878 5879 if (Index < Mod->TopHeaders.size()) 5880 return const_cast<FileEntry *>(Mod->TopHeaders[Index]); 5881 5882 return 0; 5883} 5884 5885} // end: extern "C" 5886 5887//===----------------------------------------------------------------------===// 5888// C++ AST instrospection. 5889//===----------------------------------------------------------------------===// 5890 5891extern "C" { 5892unsigned clang_CXXMethod_isStatic(CXCursor C) { 5893 if (!clang_isDeclaration(C.kind)) 5894 return 0; 5895 5896 CXXMethodDecl *Method = 0; 5897 Decl *D = cxcursor::getCursorDecl(C); 5898 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 5899 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 5900 else 5901 Method = dyn_cast_or_null<CXXMethodDecl>(D); 5902 return (Method && Method->isStatic()) ? 1 : 0; 5903} 5904 5905unsigned clang_CXXMethod_isVirtual(CXCursor C) { 5906 if (!clang_isDeclaration(C.kind)) 5907 return 0; 5908 5909 CXXMethodDecl *Method = 0; 5910 Decl *D = cxcursor::getCursorDecl(C); 5911 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 5912 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 5913 else 5914 Method = dyn_cast_or_null<CXXMethodDecl>(D); 5915 return (Method && Method->isVirtual()) ? 1 : 0; 5916} 5917} // end: extern "C" 5918 5919//===----------------------------------------------------------------------===// 5920// Attribute introspection. 5921//===----------------------------------------------------------------------===// 5922 5923extern "C" { 5924CXType clang_getIBOutletCollectionType(CXCursor C) { 5925 if (C.kind != CXCursor_IBOutletCollectionAttr) 5926 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 5927 5928 IBOutletCollectionAttr *A = 5929 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 5930 5931 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 5932} 5933} // end: extern "C" 5934 5935//===----------------------------------------------------------------------===// 5936// Inspecting memory usage. 5937//===----------------------------------------------------------------------===// 5938 5939typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 5940 5941static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 5942 enum CXTUResourceUsageKind k, 5943 unsigned long amount) { 5944 CXTUResourceUsageEntry entry = { k, amount }; 5945 entries.push_back(entry); 5946} 5947 5948extern "C" { 5949 5950const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 5951 const char *str = ""; 5952 switch (kind) { 5953 case CXTUResourceUsage_AST: 5954 str = "ASTContext: expressions, declarations, and types"; 5955 break; 5956 case CXTUResourceUsage_Identifiers: 5957 str = "ASTContext: identifiers"; 5958 break; 5959 case CXTUResourceUsage_Selectors: 5960 str = "ASTContext: selectors"; 5961 break; 5962 case CXTUResourceUsage_GlobalCompletionResults: 5963 str = "Code completion: cached global results"; 5964 break; 5965 case CXTUResourceUsage_SourceManagerContentCache: 5966 str = "SourceManager: content cache allocator"; 5967 break; 5968 case CXTUResourceUsage_AST_SideTables: 5969 str = "ASTContext: side tables"; 5970 break; 5971 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 5972 str = "SourceManager: malloc'ed memory buffers"; 5973 break; 5974 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 5975 str = "SourceManager: mmap'ed memory buffers"; 5976 break; 5977 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 5978 str = "ExternalASTSource: malloc'ed memory buffers"; 5979 break; 5980 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 5981 str = "ExternalASTSource: mmap'ed memory buffers"; 5982 break; 5983 case CXTUResourceUsage_Preprocessor: 5984 str = "Preprocessor: malloc'ed memory"; 5985 break; 5986 case CXTUResourceUsage_PreprocessingRecord: 5987 str = "Preprocessor: PreprocessingRecord"; 5988 break; 5989 case CXTUResourceUsage_SourceManager_DataStructures: 5990 str = "SourceManager: data structures and tables"; 5991 break; 5992 case CXTUResourceUsage_Preprocessor_HeaderSearch: 5993 str = "Preprocessor: header search tables"; 5994 break; 5995 } 5996 return str; 5997} 5998 5999CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 6000 if (!TU) { 6001 CXTUResourceUsage usage = { (void*) 0, 0, 0 }; 6002 return usage; 6003 } 6004 6005 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData); 6006 OwningPtr<MemUsageEntries> entries(new MemUsageEntries()); 6007 ASTContext &astContext = astUnit->getASTContext(); 6008 6009 // How much memory is used by AST nodes and types? 6010 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, 6011 (unsigned long) astContext.getASTAllocatedMemory()); 6012 6013 // How much memory is used by identifiers? 6014 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, 6015 (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); 6016 6017 // How much memory is used for selectors? 6018 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, 6019 (unsigned long) astContext.Selectors.getTotalMemory()); 6020 6021 // How much memory is used by ASTContext's side tables? 6022 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables, 6023 (unsigned long) astContext.getSideTableAllocatedMemory()); 6024 6025 // How much memory is used for caching global code completion results? 6026 unsigned long completionBytes = 0; 6027 if (GlobalCodeCompletionAllocator *completionAllocator = 6028 astUnit->getCachedCompletionAllocator().getPtr()) { 6029 completionBytes = completionAllocator->getTotalMemory(); 6030 } 6031 createCXTUResourceUsageEntry(*entries, 6032 CXTUResourceUsage_GlobalCompletionResults, 6033 completionBytes); 6034 6035 // How much memory is being used by SourceManager's content cache? 6036 createCXTUResourceUsageEntry(*entries, 6037 CXTUResourceUsage_SourceManagerContentCache, 6038 (unsigned long) astContext.getSourceManager().getContentCacheSize()); 6039 6040 // How much memory is being used by the MemoryBuffer's in SourceManager? 6041 const SourceManager::MemoryBufferSizes &srcBufs = 6042 astUnit->getSourceManager().getMemoryBufferSizes(); 6043 6044 createCXTUResourceUsageEntry(*entries, 6045 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 6046 (unsigned long) srcBufs.malloc_bytes); 6047 createCXTUResourceUsageEntry(*entries, 6048 CXTUResourceUsage_SourceManager_Membuffer_MMap, 6049 (unsigned long) srcBufs.mmap_bytes); 6050 createCXTUResourceUsageEntry(*entries, 6051 CXTUResourceUsage_SourceManager_DataStructures, 6052 (unsigned long) astContext.getSourceManager() 6053 .getDataStructureSizes()); 6054 6055 // How much memory is being used by the ExternalASTSource? 6056 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 6057 const ExternalASTSource::MemoryBufferSizes &sizes = 6058 esrc->getMemoryBufferSizes(); 6059 6060 createCXTUResourceUsageEntry(*entries, 6061 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 6062 (unsigned long) sizes.malloc_bytes); 6063 createCXTUResourceUsageEntry(*entries, 6064 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 6065 (unsigned long) sizes.mmap_bytes); 6066 } 6067 6068 // How much memory is being used by the Preprocessor? 6069 Preprocessor &pp = astUnit->getPreprocessor(); 6070 createCXTUResourceUsageEntry(*entries, 6071 CXTUResourceUsage_Preprocessor, 6072 pp.getTotalMemory()); 6073 6074 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 6075 createCXTUResourceUsageEntry(*entries, 6076 CXTUResourceUsage_PreprocessingRecord, 6077 pRec->getTotalMemory()); 6078 } 6079 6080 createCXTUResourceUsageEntry(*entries, 6081 CXTUResourceUsage_Preprocessor_HeaderSearch, 6082 pp.getHeaderSearchInfo().getTotalMemory()); 6083 6084 CXTUResourceUsage usage = { (void*) entries.get(), 6085 (unsigned) entries->size(), 6086 entries->size() ? &(*entries)[0] : 0 }; 6087 entries.take(); 6088 return usage; 6089} 6090 6091void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 6092 if (usage.data) 6093 delete (MemUsageEntries*) usage.data; 6094} 6095 6096} // end extern "C" 6097 6098void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 6099 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 6100 for (unsigned I = 0; I != Usage.numEntries; ++I) 6101 fprintf(stderr, " %s: %lu\n", 6102 clang_getTUResourceUsageName(Usage.entries[I].kind), 6103 Usage.entries[I].amount); 6104 6105 clang_disposeCXTUResourceUsage(Usage); 6106} 6107 6108//===----------------------------------------------------------------------===// 6109// Misc. utility functions. 6110//===----------------------------------------------------------------------===// 6111 6112/// Default to using an 8 MB stack size on "safety" threads. 6113static unsigned SafetyStackThreadSize = 8 << 20; 6114 6115namespace clang { 6116 6117bool RunSafely(llvm::CrashRecoveryContext &CRC, 6118 void (*Fn)(void*), void *UserData, 6119 unsigned Size) { 6120 if (!Size) 6121 Size = GetSafetyThreadStackSize(); 6122 if (Size) 6123 return CRC.RunSafelyOnThread(Fn, UserData, Size); 6124 return CRC.RunSafely(Fn, UserData); 6125} 6126 6127unsigned GetSafetyThreadStackSize() { 6128 return SafetyStackThreadSize; 6129} 6130 6131void SetSafetyThreadStackSize(unsigned Value) { 6132 SafetyStackThreadSize = Value; 6133} 6134 6135} 6136 6137void clang::setThreadBackgroundPriority() { 6138 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 6139 return; 6140 6141 // FIXME: Move to llvm/Support and make it cross-platform. 6142#ifdef __APPLE__ 6143 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); 6144#endif 6145} 6146 6147void cxindex::printDiagsToStderr(ASTUnit *Unit) { 6148 if (!Unit) 6149 return; 6150 6151 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 6152 DEnd = Unit->stored_diag_end(); 6153 D != DEnd; ++D) { 6154 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts()); 6155 CXString Msg = clang_formatDiagnostic(&Diag, 6156 clang_defaultDiagnosticDisplayOptions()); 6157 fprintf(stderr, "%s\n", clang_getCString(Msg)); 6158 clang_disposeString(Msg); 6159 } 6160#ifdef LLVM_ON_WIN32 6161 // On Windows, force a flush, since there may be multiple copies of 6162 // stderr and stdout in the file system, all with different buffers 6163 // but writing to the same device. 6164 fflush(stderr); 6165#endif 6166} 6167 6168extern "C" { 6169 6170CXString clang_getClangVersion() { 6171 return createCXString(getClangFullVersion()); 6172} 6173 6174} // end: extern "C" 6175 6176