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