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