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