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