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