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