1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the main API hooks in the Clang-C Source Indexing 11 // library. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CIndexDiagnostic.h" 16 #include "CIndexer.h" 17 #include "CLog.h" 18 #include "CXCursor.h" 19 #include "CXSourceLocation.h" 20 #include "CXString.h" 21 #include "CXTranslationUnit.h" 22 #include "CXType.h" 23 #include "CursorVisitor.h" 24 #include "clang/AST/Attr.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Basic/Diagnostic.h" 27 #include "clang/Basic/DiagnosticCategories.h" 28 #include "clang/Basic/DiagnosticIDs.h" 29 #include "clang/Basic/Stack.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Basic/Version.h" 32 #include "clang/Frontend/ASTUnit.h" 33 #include "clang/Frontend/CompilerInstance.h" 34 #include "clang/Frontend/FrontendDiagnostic.h" 35 #include "clang/Index/CodegenNameGenerator.h" 36 #include "clang/Index/CommentToXML.h" 37 #include "clang/Lex/HeaderSearch.h" 38 #include "clang/Lex/Lexer.h" 39 #include "clang/Lex/PreprocessingRecord.h" 40 #include "clang/Lex/Preprocessor.h" 41 #include "clang/Serialization/SerializationDiagnostic.h" 42 #include "llvm/ADT/Optional.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringSwitch.h" 45 #include "llvm/Config/llvm-config.h" 46 #include "llvm/Support/Compiler.h" 47 #include "llvm/Support/CrashRecoveryContext.h" 48 #include "llvm/Support/Format.h" 49 #include "llvm/Support/ManagedStatic.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Mutex.h" 52 #include "llvm/Support/Program.h" 53 #include "llvm/Support/SaveAndRestore.h" 54 #include "llvm/Support/Signals.h" 55 #include "llvm/Support/TargetSelect.h" 56 #include "llvm/Support/Threading.h" 57 #include "llvm/Support/Timer.h" 58 #include "llvm/Support/raw_ostream.h" 59 60 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) 61 #define USE_DARWIN_THREADS 62 #endif 63 64 #ifdef USE_DARWIN_THREADS 65 #include <pthread.h> 66 #endif 67 68 using namespace clang; 69 using namespace clang::cxcursor; 70 using namespace clang::cxtu; 71 using namespace clang::cxindex; 72 73 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, 74 std::unique_ptr<ASTUnit> AU) { 75 if (!AU) 76 return nullptr; 77 assert(CIdx); 78 CXTranslationUnit D = new CXTranslationUnitImpl(); 79 D->CIdx = CIdx; 80 D->TheASTUnit = AU.release(); 81 D->StringPool = new cxstring::CXStringPool(); 82 D->Diagnostics = nullptr; 83 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 84 D->CommentToXML = nullptr; 85 D->ParsingOptions = 0; 86 D->Arguments = {}; 87 return D; 88 } 89 90 bool cxtu::isASTReadError(ASTUnit *AU) { 91 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), 92 DEnd = AU->stored_diag_end(); 93 D != DEnd; ++D) { 94 if (D->getLevel() >= DiagnosticsEngine::Error && 95 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == 96 diag::DiagCat_AST_Deserialization_Issue) 97 return true; 98 } 99 return false; 100 } 101 102 cxtu::CXTUOwner::~CXTUOwner() { 103 if (TU) 104 clang_disposeTranslationUnit(TU); 105 } 106 107 /// Compare two source ranges to determine their relative position in 108 /// the translation unit. 109 static RangeComparisonResult RangeCompare(SourceManager &SM, 110 SourceRange R1, 111 SourceRange R2) { 112 assert(R1.isValid() && "First range is invalid?"); 113 assert(R2.isValid() && "Second range is invalid?"); 114 if (R1.getEnd() != R2.getBegin() && 115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 116 return RangeBefore; 117 if (R2.getEnd() != R1.getBegin() && 118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 119 return RangeAfter; 120 return RangeOverlap; 121 } 122 123 /// Determine if a source location falls within, before, or after a 124 /// a given source range. 125 static RangeComparisonResult LocationCompare(SourceManager &SM, 126 SourceLocation L, SourceRange R) { 127 assert(R.isValid() && "First range is invalid?"); 128 assert(L.isValid() && "Second range is invalid?"); 129 if (L == R.getBegin() || L == R.getEnd()) 130 return RangeOverlap; 131 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 132 return RangeBefore; 133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 134 return RangeAfter; 135 return RangeOverlap; 136 } 137 138 /// Translate a Clang source range into a CIndex source range. 139 /// 140 /// Clang internally represents ranges where the end location points to the 141 /// start of the token at the end. However, for external clients it is more 142 /// useful to have a CXSourceRange be a proper half-open interval. This routine 143 /// does the appropriate translation. 144 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 145 const LangOptions &LangOpts, 146 const CharSourceRange &R) { 147 // We want the last character in this location, so we will adjust the 148 // location accordingly. 149 SourceLocation EndLoc = R.getEnd(); 150 bool IsTokenRange = R.isTokenRange(); 151 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) { 152 CharSourceRange Expansion = SM.getExpansionRange(EndLoc); 153 EndLoc = Expansion.getEnd(); 154 IsTokenRange = Expansion.isTokenRange(); 155 } 156 if (IsTokenRange && EndLoc.isValid()) { 157 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), 158 SM, LangOpts); 159 EndLoc = EndLoc.getLocWithOffset(Length); 160 } 161 162 CXSourceRange Result = { 163 { &SM, &LangOpts }, 164 R.getBegin().getRawEncoding(), 165 EndLoc.getRawEncoding() 166 }; 167 return Result; 168 } 169 170 //===----------------------------------------------------------------------===// 171 // Cursor visitor. 172 //===----------------------------------------------------------------------===// 173 174 static SourceRange getRawCursorExtent(CXCursor C); 175 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 176 177 178 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 179 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 180 } 181 182 /// Visit the given cursor and, if requested by the visitor, 183 /// its children. 184 /// 185 /// \param Cursor the cursor to visit. 186 /// 187 /// \param CheckedRegionOfInterest if true, then the caller already checked 188 /// that this cursor is within the region of interest. 189 /// 190 /// \returns true if the visitation should be aborted, false if it 191 /// should continue. 192 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 193 if (clang_isInvalid(Cursor.kind)) 194 return false; 195 196 if (clang_isDeclaration(Cursor.kind)) { 197 const Decl *D = getCursorDecl(Cursor); 198 if (!D) { 199 assert(0 && "Invalid declaration cursor"); 200 return true; // abort. 201 } 202 203 // Ignore implicit declarations, unless it's an objc method because 204 // currently we should report implicit methods for properties when indexing. 205 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 206 return false; 207 } 208 209 // If we have a range of interest, and this cursor doesn't intersect with it, 210 // we're done. 211 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 212 SourceRange Range = getRawCursorExtent(Cursor); 213 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 214 return false; 215 } 216 217 switch (Visitor(Cursor, Parent, ClientData)) { 218 case CXChildVisit_Break: 219 return true; 220 221 case CXChildVisit_Continue: 222 return false; 223 224 case CXChildVisit_Recurse: { 225 bool ret = VisitChildren(Cursor); 226 if (PostChildrenVisitor) 227 if (PostChildrenVisitor(Cursor, ClientData)) 228 return true; 229 return ret; 230 } 231 } 232 233 llvm_unreachable("Invalid CXChildVisitResult!"); 234 } 235 236 static bool visitPreprocessedEntitiesInRange(SourceRange R, 237 PreprocessingRecord &PPRec, 238 CursorVisitor &Visitor) { 239 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 240 FileID FID; 241 242 if (!Visitor.shouldVisitIncludedEntities()) { 243 // If the begin/end of the range lie in the same FileID, do the optimization 244 // where we skip preprocessed entities that do not come from the same FileID. 245 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 246 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 247 FID = FileID(); 248 } 249 250 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); 251 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), 252 PPRec, FID); 253 } 254 255 bool CursorVisitor::visitFileRegion() { 256 if (RegionOfInterest.isInvalid()) 257 return false; 258 259 ASTUnit *Unit = cxtu::getASTUnit(TU); 260 SourceManager &SM = Unit->getSourceManager(); 261 262 std::pair<FileID, unsigned> 263 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 264 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 265 266 if (End.first != Begin.first) { 267 // If the end does not reside in the same file, try to recover by 268 // picking the end of the file of begin location. 269 End.first = Begin.first; 270 End.second = SM.getFileIDSize(Begin.first); 271 } 272 273 assert(Begin.first == End.first); 274 if (Begin.second > End.second) 275 return false; 276 277 FileID File = Begin.first; 278 unsigned Offset = Begin.second; 279 unsigned Length = End.second - Begin.second; 280 281 if (!VisitDeclsOnly && !VisitPreprocessorLast) 282 if (visitPreprocessedEntitiesInRegion()) 283 return true; // visitation break. 284 285 if (visitDeclsFromFileRegion(File, Offset, Length)) 286 return true; // visitation break. 287 288 if (!VisitDeclsOnly && VisitPreprocessorLast) 289 return visitPreprocessedEntitiesInRegion(); 290 291 return false; 292 } 293 294 static bool isInLexicalContext(Decl *D, DeclContext *DC) { 295 if (!DC) 296 return false; 297 298 for (DeclContext *DeclDC = D->getLexicalDeclContext(); 299 DeclDC; DeclDC = DeclDC->getLexicalParent()) { 300 if (DeclDC == DC) 301 return true; 302 } 303 return false; 304 } 305 306 bool CursorVisitor::visitDeclsFromFileRegion(FileID File, 307 unsigned Offset, unsigned Length) { 308 ASTUnit *Unit = cxtu::getASTUnit(TU); 309 SourceManager &SM = Unit->getSourceManager(); 310 SourceRange Range = RegionOfInterest; 311 312 SmallVector<Decl *, 16> Decls; 313 Unit->findFileRegionDecls(File, Offset, Length, Decls); 314 315 // If we didn't find any file level decls for the file, try looking at the 316 // file that it was included from. 317 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 318 bool Invalid = false; 319 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 320 if (Invalid) 321 return false; 322 323 SourceLocation Outer; 324 if (SLEntry.isFile()) 325 Outer = SLEntry.getFile().getIncludeLoc(); 326 else 327 Outer = SLEntry.getExpansion().getExpansionLocStart(); 328 if (Outer.isInvalid()) 329 return false; 330 331 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 332 Length = 0; 333 Unit->findFileRegionDecls(File, Offset, Length, Decls); 334 } 335 336 assert(!Decls.empty()); 337 338 bool VisitedAtLeastOnce = false; 339 DeclContext *CurDC = nullptr; 340 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin(); 341 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 342 Decl *D = *DIt; 343 if (D->getSourceRange().isInvalid()) 344 continue; 345 346 if (isInLexicalContext(D, CurDC)) 347 continue; 348 349 CurDC = dyn_cast<DeclContext>(D); 350 351 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 352 if (!TD->isFreeStanding()) 353 continue; 354 355 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); 356 if (CompRes == RangeBefore) 357 continue; 358 if (CompRes == RangeAfter) 359 break; 360 361 assert(CompRes == RangeOverlap); 362 VisitedAtLeastOnce = true; 363 364 if (isa<ObjCContainerDecl>(D)) { 365 FileDI_current = &DIt; 366 FileDE_current = DE; 367 } else { 368 FileDI_current = nullptr; 369 } 370 371 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 372 return true; // visitation break. 373 } 374 375 if (VisitedAtLeastOnce) 376 return false; 377 378 // No Decls overlapped with the range. Move up the lexical context until there 379 // is a context that contains the range or we reach the translation unit 380 // level. 381 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() 382 : (*(DIt-1))->getLexicalDeclContext(); 383 384 while (DC && !DC->isTranslationUnit()) { 385 Decl *D = cast<Decl>(DC); 386 SourceRange CurDeclRange = D->getSourceRange(); 387 if (CurDeclRange.isInvalid()) 388 break; 389 390 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 391 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 392 return true; // visitation break. 393 } 394 395 DC = D->getLexicalDeclContext(); 396 } 397 398 return false; 399 } 400 401 bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 402 if (!AU->getPreprocessor().getPreprocessingRecord()) 403 return false; 404 405 PreprocessingRecord &PPRec 406 = *AU->getPreprocessor().getPreprocessingRecord(); 407 SourceManager &SM = AU->getSourceManager(); 408 409 if (RegionOfInterest.isValid()) { 410 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 411 SourceLocation B = MappedRange.getBegin(); 412 SourceLocation E = MappedRange.getEnd(); 413 414 if (AU->isInPreambleFileID(B)) { 415 if (SM.isLoadedSourceLocation(E)) 416 return visitPreprocessedEntitiesInRange(SourceRange(B, E), 417 PPRec, *this); 418 419 // Beginning of range lies in the preamble but it also extends beyond 420 // it into the main file. Split the range into 2 parts, one covering 421 // the preamble and another covering the main file. This allows subsequent 422 // calls to visitPreprocessedEntitiesInRange to accept a source range that 423 // lies in the same FileID, allowing it to skip preprocessed entities that 424 // do not come from the same FileID. 425 bool breaked = 426 visitPreprocessedEntitiesInRange( 427 SourceRange(B, AU->getEndOfPreambleFileID()), 428 PPRec, *this); 429 if (breaked) return true; 430 return visitPreprocessedEntitiesInRange( 431 SourceRange(AU->getStartOfMainFileID(), E), 432 PPRec, *this); 433 } 434 435 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 436 } 437 438 bool OnlyLocalDecls 439 = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 440 441 if (OnlyLocalDecls) 442 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 443 PPRec); 444 445 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 446 } 447 448 template<typename InputIterator> 449 bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 450 InputIterator Last, 451 PreprocessingRecord &PPRec, 452 FileID FID) { 453 for (; First != Last; ++First) { 454 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 455 continue; 456 457 PreprocessedEntity *PPE = *First; 458 if (!PPE) 459 continue; 460 461 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 462 if (Visit(MakeMacroExpansionCursor(ME, TU))) 463 return true; 464 465 continue; 466 } 467 468 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) { 469 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 470 return true; 471 472 continue; 473 } 474 475 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 476 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 477 return true; 478 479 continue; 480 } 481 } 482 483 return false; 484 } 485 486 /// Visit the children of the given cursor. 487 /// 488 /// \returns true if the visitation should be aborted, false if it 489 /// should continue. 490 bool CursorVisitor::VisitChildren(CXCursor Cursor) { 491 if (clang_isReference(Cursor.kind) && 492 Cursor.kind != CXCursor_CXXBaseSpecifier) { 493 // By definition, references have no children. 494 return false; 495 } 496 497 // Set the Parent field to Cursor, then back to its old value once we're 498 // done. 499 SetParentRAII SetParent(Parent, StmtParent, Cursor); 500 501 if (clang_isDeclaration(Cursor.kind)) { 502 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor)); 503 if (!D) 504 return false; 505 506 return VisitAttributes(D) || Visit(D); 507 } 508 509 if (clang_isStatement(Cursor.kind)) { 510 if (const Stmt *S = getCursorStmt(Cursor)) 511 return Visit(S); 512 513 return false; 514 } 515 516 if (clang_isExpression(Cursor.kind)) { 517 if (const Expr *E = getCursorExpr(Cursor)) 518 return Visit(E); 519 520 return false; 521 } 522 523 if (clang_isTranslationUnit(Cursor.kind)) { 524 CXTranslationUnit TU = getCursorTU(Cursor); 525 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 526 527 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; 528 for (unsigned I = 0; I != 2; ++I) { 529 if (VisitOrder[I]) { 530 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 531 RegionOfInterest.isInvalid()) { 532 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 533 TLEnd = CXXUnit->top_level_end(); 534 TL != TLEnd; ++TL) { 535 const Optional<bool> V = handleDeclForVisitation(*TL); 536 if (!V.hasValue()) 537 continue; 538 return V.getValue(); 539 } 540 } else if (VisitDeclContext( 541 CXXUnit->getASTContext().getTranslationUnitDecl())) 542 return true; 543 continue; 544 } 545 546 // Walk the preprocessing record. 547 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 548 visitPreprocessedEntitiesInRegion(); 549 } 550 551 return false; 552 } 553 554 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 555 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 556 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 557 return Visit(BaseTSInfo->getTypeLoc()); 558 } 559 } 560 } 561 562 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 563 const IBOutletCollectionAttr *A = 564 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 565 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>()) 566 return Visit(cxcursor::MakeCursorObjCClassRef( 567 ObjT->getInterface(), 568 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU)); 569 } 570 571 // If pointing inside a macro definition, check if the token is an identifier 572 // that was ever defined as a macro. In such a case, create a "pseudo" macro 573 // expansion cursor for that token. 574 SourceLocation BeginLoc = RegionOfInterest.getBegin(); 575 if (Cursor.kind == CXCursor_MacroDefinition && 576 BeginLoc == RegionOfInterest.getEnd()) { 577 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); 578 const MacroInfo *MI = 579 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); 580 if (MacroDefinitionRecord *MacroDef = 581 checkForMacroInMacroDefinition(MI, Loc, TU)) 582 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); 583 } 584 585 // Nothing to visit at the moment. 586 return false; 587 } 588 589 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 590 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 591 if (Visit(TSInfo->getTypeLoc())) 592 return true; 593 594 if (Stmt *Body = B->getBody()) 595 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 596 597 return false; 598 } 599 600 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 601 if (RegionOfInterest.isValid()) { 602 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 603 if (Range.isInvalid()) 604 return None; 605 606 switch (CompareRegionOfInterest(Range)) { 607 case RangeBefore: 608 // This declaration comes before the region of interest; skip it. 609 return None; 610 611 case RangeAfter: 612 // This declaration comes after the region of interest; we're done. 613 return false; 614 615 case RangeOverlap: 616 // This declaration overlaps the region of interest; visit it. 617 break; 618 } 619 } 620 return true; 621 } 622 623 bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 624 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 625 626 // FIXME: Eventually remove. This part of a hack to support proper 627 // iteration over all Decls contained lexically within an ObjC container. 628 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 629 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 630 631 for ( ; I != E; ++I) { 632 Decl *D = *I; 633 if (D->getLexicalDeclContext() != DC) 634 continue; 635 const Optional<bool> V = handleDeclForVisitation(D); 636 if (!V.hasValue()) 637 continue; 638 return V.getValue(); 639 } 640 return false; 641 } 642 643 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { 644 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 645 646 // Ignore synthesized ivars here, otherwise if we have something like: 647 // @synthesize prop = _prop; 648 // and '_prop' is not declared, we will encounter a '_prop' ivar before 649 // encountering the 'prop' synthesize declaration and we will think that 650 // we passed the region-of-interest. 651 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 652 if (ivarD->getSynthesize()) 653 return None; 654 } 655 656 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 657 // declarations is a mismatch with the compiler semantics. 658 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 659 auto *ID = cast<ObjCInterfaceDecl>(D); 660 if (!ID->isThisDeclarationADefinition()) 661 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 662 663 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 664 auto *PD = cast<ObjCProtocolDecl>(D); 665 if (!PD->isThisDeclarationADefinition()) 666 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 667 } 668 669 const Optional<bool> V = shouldVisitCursor(Cursor); 670 if (!V.hasValue()) 671 return None; 672 if (!V.getValue()) 673 return false; 674 if (Visit(Cursor, true)) 675 return true; 676 return None; 677 } 678 679 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 680 llvm_unreachable("Translation units are visited directly by Visit()"); 681 } 682 683 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 684 if (VisitTemplateParameters(D->getTemplateParameters())) 685 return true; 686 687 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest)); 688 } 689 690 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 692 return Visit(TSInfo->getTypeLoc()); 693 694 return false; 695 } 696 697 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 698 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 699 return Visit(TSInfo->getTypeLoc()); 700 701 return false; 702 } 703 704 bool CursorVisitor::VisitTagDecl(TagDecl *D) { 705 return VisitDeclContext(D); 706 } 707 708 bool CursorVisitor::VisitClassTemplateSpecializationDecl( 709 ClassTemplateSpecializationDecl *D) { 710 bool ShouldVisitBody = false; 711 switch (D->getSpecializationKind()) { 712 case TSK_Undeclared: 713 case TSK_ImplicitInstantiation: 714 // Nothing to visit 715 return false; 716 717 case TSK_ExplicitInstantiationDeclaration: 718 case TSK_ExplicitInstantiationDefinition: 719 break; 720 721 case TSK_ExplicitSpecialization: 722 ShouldVisitBody = true; 723 break; 724 } 725 726 // Visit the template arguments used in the specialization. 727 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 728 TypeLoc TL = SpecType->getTypeLoc(); 729 if (TemplateSpecializationTypeLoc TSTLoc = 730 TL.getAs<TemplateSpecializationTypeLoc>()) { 731 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) 732 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) 733 return true; 734 } 735 } 736 737 return ShouldVisitBody && VisitCXXRecordDecl(D); 738 } 739 740 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 741 ClassTemplatePartialSpecializationDecl *D) { 742 // FIXME: Visit the "outer" template parameter lists on the TagDecl 743 // before visiting these template parameters. 744 if (VisitTemplateParameters(D->getTemplateParameters())) 745 return true; 746 747 // Visit the partial specialization arguments. 748 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); 749 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); 750 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) 751 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 752 return true; 753 754 return VisitCXXRecordDecl(D); 755 } 756 757 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 758 // Visit the default argument. 759 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 760 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 761 if (Visit(DefArg->getTypeLoc())) 762 return true; 763 764 return false; 765 } 766 767 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 768 if (Expr *Init = D->getInitExpr()) 769 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 770 return false; 771 } 772 773 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 774 unsigned NumParamList = DD->getNumTemplateParameterLists(); 775 for (unsigned i = 0; i < NumParamList; i++) { 776 TemplateParameterList* Params = DD->getTemplateParameterList(i); 777 if (VisitTemplateParameters(Params)) 778 return true; 779 } 780 781 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 782 if (Visit(TSInfo->getTypeLoc())) 783 return true; 784 785 // Visit the nested-name-specifier, if present. 786 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 787 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 788 return true; 789 790 return false; 791 } 792 793 static bool HasTrailingReturnType(FunctionDecl *ND) { 794 const QualType Ty = ND->getType(); 795 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) { 796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT)) 797 return FT->hasTrailingReturn(); 798 } 799 800 return false; 801 } 802 803 /// Compare two base or member initializers based on their source order. 804 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X, 805 CXXCtorInitializer *const *Y) { 806 return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); 807 } 808 809 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 810 unsigned NumParamList = ND->getNumTemplateParameterLists(); 811 for (unsigned i = 0; i < NumParamList; i++) { 812 TemplateParameterList* Params = ND->getTemplateParameterList(i); 813 if (VisitTemplateParameters(Params)) 814 return true; 815 } 816 817 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 818 // Visit the function declaration's syntactic components in the order 819 // written. This requires a bit of work. 820 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 821 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>(); 822 const bool HasTrailingRT = HasTrailingReturnType(ND); 823 824 // If we have a function declared directly (without the use of a typedef), 825 // visit just the return type. Otherwise, just visit the function's type 826 // now. 827 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT && 828 Visit(FTL.getReturnLoc())) || 829 (!FTL && Visit(TL))) 830 return true; 831 832 // Visit the nested-name-specifier, if present. 833 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 834 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 835 return true; 836 837 // Visit the declaration name. 838 if (!isa<CXXDestructorDecl>(ND)) 839 if (VisitDeclarationNameInfo(ND->getNameInfo())) 840 return true; 841 842 // FIXME: Visit explicitly-specified template arguments! 843 844 // Visit the function parameters, if we have a function type. 845 if (FTL && VisitFunctionTypeLoc(FTL, true)) 846 return true; 847 848 // Visit the function's trailing return type. 849 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc())) 850 return true; 851 852 // FIXME: Attributes? 853 } 854 855 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 856 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 857 // Find the initializers that were written in the source. 858 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 859 for (auto *I : Constructor->inits()) { 860 if (!I->isWritten()) 861 continue; 862 863 WrittenInits.push_back(I); 864 } 865 866 // Sort the initializers in source order 867 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 868 &CompareCXXCtorInitializers); 869 870 // Visit the initializers in source order 871 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 872 CXXCtorInitializer *Init = WrittenInits[I]; 873 if (Init->isAnyMemberInitializer()) { 874 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 875 Init->getMemberLocation(), TU))) 876 return true; 877 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 878 if (Visit(TInfo->getTypeLoc())) 879 return true; 880 } 881 882 // Visit the initializer value. 883 if (Expr *Initializer = Init->getInit()) 884 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 885 return true; 886 } 887 } 888 889 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 890 return true; 891 } 892 893 return false; 894 } 895 896 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 897 if (VisitDeclaratorDecl(D)) 898 return true; 899 900 if (Expr *BitWidth = D->getBitWidth()) 901 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 902 903 if (Expr *Init = D->getInClassInitializer()) 904 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 905 906 return false; 907 } 908 909 bool CursorVisitor::VisitVarDecl(VarDecl *D) { 910 if (VisitDeclaratorDecl(D)) 911 return true; 912 913 if (Expr *Init = D->getInit()) 914 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 915 916 return false; 917 } 918 919 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 920 if (VisitDeclaratorDecl(D)) 921 return true; 922 923 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 924 if (Expr *DefArg = D->getDefaultArgument()) 925 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 926 927 return false; 928 } 929 930 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 931 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 932 // before visiting these template parameters. 933 if (VisitTemplateParameters(D->getTemplateParameters())) 934 return true; 935 936 auto* FD = D->getTemplatedDecl(); 937 return VisitAttributes(FD) || VisitFunctionDecl(FD); 938 } 939 940 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 941 // FIXME: Visit the "outer" template parameter lists on the TagDecl 942 // before visiting these template parameters. 943 if (VisitTemplateParameters(D->getTemplateParameters())) 944 return true; 945 946 auto* CD = D->getTemplatedDecl(); 947 return VisitAttributes(CD) || VisitCXXRecordDecl(CD); 948 } 949 950 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 951 if (VisitTemplateParameters(D->getTemplateParameters())) 952 return true; 953 954 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 955 VisitTemplateArgumentLoc(D->getDefaultArgument())) 956 return true; 957 958 return false; 959 } 960 961 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 962 // Visit the bound, if it's explicit. 963 if (D->hasExplicitBound()) { 964 if (auto TInfo = D->getTypeSourceInfo()) { 965 if (Visit(TInfo->getTypeLoc())) 966 return true; 967 } 968 } 969 970 return false; 971 } 972 973 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 974 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) 975 if (Visit(TSInfo->getTypeLoc())) 976 return true; 977 978 for (const auto *P : ND->parameters()) { 979 if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) 980 return true; 981 } 982 983 return ND->isThisDeclarationADefinition() && 984 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)); 985 } 986 987 template <typename DeclIt> 988 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 989 SourceManager &SM, SourceLocation EndLoc, 990 SmallVectorImpl<Decl *> &Decls) { 991 DeclIt next = *DI_current; 992 while (++next != DE_current) { 993 Decl *D_next = *next; 994 if (!D_next) 995 break; 996 SourceLocation L = D_next->getBeginLoc(); 997 if (!L.isValid()) 998 break; 999 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 1000 *DI_current = next; 1001 Decls.push_back(D_next); 1002 continue; 1003 } 1004 break; 1005 } 1006 } 1007 1008 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 1009 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 1010 // an @implementation can lexically contain Decls that are not properly 1011 // nested in the AST. When we identify such cases, we need to retrofit 1012 // this nesting here. 1013 if (!DI_current && !FileDI_current) 1014 return VisitDeclContext(D); 1015 1016 // Scan the Decls that immediately come after the container 1017 // in the current DeclContext. If any fall within the 1018 // container's lexical region, stash them into a vector 1019 // for later processing. 1020 SmallVector<Decl *, 24> DeclsInContainer; 1021 SourceLocation EndLoc = D->getSourceRange().getEnd(); 1022 SourceManager &SM = AU->getSourceManager(); 1023 if (EndLoc.isValid()) { 1024 if (DI_current) { 1025 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 1026 DeclsInContainer); 1027 } else { 1028 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 1029 DeclsInContainer); 1030 } 1031 } 1032 1033 // The common case. 1034 if (DeclsInContainer.empty()) 1035 return VisitDeclContext(D); 1036 1037 // Get all the Decls in the DeclContext, and sort them with the 1038 // additional ones we've collected. Then visit them. 1039 for (auto *SubDecl : D->decls()) { 1040 if (!SubDecl || SubDecl->getLexicalDeclContext() != D || 1041 SubDecl->getBeginLoc().isInvalid()) 1042 continue; 1043 DeclsInContainer.push_back(SubDecl); 1044 } 1045 1046 // Now sort the Decls so that they appear in lexical order. 1047 llvm::sort(DeclsInContainer, 1048 [&SM](Decl *A, Decl *B) { 1049 SourceLocation L_A = A->getBeginLoc(); 1050 SourceLocation L_B = B->getBeginLoc(); 1051 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B) 1052 : SM.isBeforeInTranslationUnit(A->getEndLoc(), 1053 B->getEndLoc()); 1054 }); 1055 1056 // Now visit the decls. 1057 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 1058 E = DeclsInContainer.end(); I != E; ++I) { 1059 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 1060 const Optional<bool> &V = shouldVisitCursor(Cursor); 1061 if (!V.hasValue()) 1062 continue; 1063 if (!V.getValue()) 1064 return false; 1065 if (Visit(Cursor, true)) 1066 return true; 1067 } 1068 return false; 1069 } 1070 1071 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 1072 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 1073 TU))) 1074 return true; 1075 1076 if (VisitObjCTypeParamList(ND->getTypeParamList())) 1077 return true; 1078 1079 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 1080 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 1081 E = ND->protocol_end(); I != E; ++I, ++PL) 1082 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1083 return true; 1084 1085 return VisitObjCContainerDecl(ND); 1086 } 1087 1088 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1089 if (!PID->isThisDeclarationADefinition()) 1090 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 1091 1092 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 1093 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 1094 E = PID->protocol_end(); I != E; ++I, ++PL) 1095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1096 return true; 1097 1098 return VisitObjCContainerDecl(PID); 1099 } 1100 1101 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 1102 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 1103 return true; 1104 1105 // FIXME: This implements a workaround with @property declarations also being 1106 // installed in the DeclContext for the @interface. Eventually this code 1107 // should be removed. 1108 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1109 if (!CDecl || !CDecl->IsClassExtension()) 1110 return false; 1111 1112 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1113 if (!ID) 1114 return false; 1115 1116 IdentifierInfo *PropertyId = PD->getIdentifier(); 1117 ObjCPropertyDecl *prevDecl = 1118 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId, 1119 PD->getQueryKind()); 1120 1121 if (!prevDecl) 1122 return false; 1123 1124 // Visit synthesized methods since they will be skipped when visiting 1125 // the @interface. 1126 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1127 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1128 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1129 return true; 1130 1131 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1132 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1133 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1134 return true; 1135 1136 return false; 1137 } 1138 1139 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { 1140 if (!typeParamList) 1141 return false; 1142 1143 for (auto *typeParam : *typeParamList) { 1144 // Visit the type parameter. 1145 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) 1146 return true; 1147 } 1148 1149 return false; 1150 } 1151 1152 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1153 if (!D->isThisDeclarationADefinition()) { 1154 // Forward declaration is treated like a reference. 1155 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1156 } 1157 1158 // Objective-C type parameters. 1159 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) 1160 return true; 1161 1162 // Issue callbacks for super class. 1163 if (D->getSuperClass() && 1164 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1165 D->getSuperClassLoc(), 1166 TU))) 1167 return true; 1168 1169 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) 1170 if (Visit(SuperClassTInfo->getTypeLoc())) 1171 return true; 1172 1173 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1174 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1175 E = D->protocol_end(); I != E; ++I, ++PL) 1176 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1177 return true; 1178 1179 return VisitObjCContainerDecl(D); 1180 } 1181 1182 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1183 return VisitObjCContainerDecl(D); 1184 } 1185 1186 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1187 // 'ID' could be null when dealing with invalid code. 1188 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1189 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1190 return true; 1191 1192 return VisitObjCImplDecl(D); 1193 } 1194 1195 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1196 #if 0 1197 // Issue callbacks for super class. 1198 // FIXME: No source location information! 1199 if (D->getSuperClass() && 1200 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1201 D->getSuperClassLoc(), 1202 TU))) 1203 return true; 1204 #endif 1205 1206 return VisitObjCImplDecl(D); 1207 } 1208 1209 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1210 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1211 if (PD->isIvarNameSpecified()) 1212 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1213 1214 return false; 1215 } 1216 1217 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1218 return VisitDeclContext(D); 1219 } 1220 1221 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1222 // Visit nested-name-specifier. 1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1224 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1225 return true; 1226 1227 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1228 D->getTargetNameLoc(), TU)); 1229 } 1230 1231 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1232 // Visit nested-name-specifier. 1233 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1234 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1235 return true; 1236 } 1237 1238 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1239 return true; 1240 1241 return VisitDeclarationNameInfo(D->getNameInfo()); 1242 } 1243 1244 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1245 // Visit nested-name-specifier. 1246 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1247 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1248 return true; 1249 1250 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1251 D->getIdentLocation(), TU)); 1252 } 1253 1254 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1255 // Visit nested-name-specifier. 1256 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1257 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1258 return true; 1259 } 1260 1261 return VisitDeclarationNameInfo(D->getNameInfo()); 1262 } 1263 1264 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1265 UnresolvedUsingTypenameDecl *D) { 1266 // Visit nested-name-specifier. 1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1268 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1269 return true; 1270 1271 return false; 1272 } 1273 1274 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) { 1275 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest))) 1276 return true; 1277 if (StringLiteral *Message = D->getMessage()) 1278 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest))) 1279 return true; 1280 return false; 1281 } 1282 1283 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) { 1284 if (NamedDecl *FriendD = D->getFriendDecl()) { 1285 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest))) 1286 return true; 1287 } else if (TypeSourceInfo *TI = D->getFriendType()) { 1288 if (Visit(TI->getTypeLoc())) 1289 return true; 1290 } 1291 return false; 1292 } 1293 1294 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1295 switch (Name.getName().getNameKind()) { 1296 case clang::DeclarationName::Identifier: 1297 case clang::DeclarationName::CXXLiteralOperatorName: 1298 case clang::DeclarationName::CXXDeductionGuideName: 1299 case clang::DeclarationName::CXXOperatorName: 1300 case clang::DeclarationName::CXXUsingDirective: 1301 return false; 1302 1303 case clang::DeclarationName::CXXConstructorName: 1304 case clang::DeclarationName::CXXDestructorName: 1305 case clang::DeclarationName::CXXConversionFunctionName: 1306 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1307 return Visit(TSInfo->getTypeLoc()); 1308 return false; 1309 1310 case clang::DeclarationName::ObjCZeroArgSelector: 1311 case clang::DeclarationName::ObjCOneArgSelector: 1312 case clang::DeclarationName::ObjCMultiArgSelector: 1313 // FIXME: Per-identifier location info? 1314 return false; 1315 } 1316 1317 llvm_unreachable("Invalid DeclarationName::Kind!"); 1318 } 1319 1320 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1321 SourceRange Range) { 1322 // FIXME: This whole routine is a hack to work around the lack of proper 1323 // source information in nested-name-specifiers (PR5791). Since we do have 1324 // a beginning source location, we can visit the first component of the 1325 // nested-name-specifier, if it's a single-token component. 1326 if (!NNS) 1327 return false; 1328 1329 // Get the first component in the nested-name-specifier. 1330 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1331 NNS = Prefix; 1332 1333 switch (NNS->getKind()) { 1334 case NestedNameSpecifier::Namespace: 1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1336 TU)); 1337 1338 case NestedNameSpecifier::NamespaceAlias: 1339 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1340 Range.getBegin(), TU)); 1341 1342 case NestedNameSpecifier::TypeSpec: { 1343 // If the type has a form where we know that the beginning of the source 1344 // range matches up with a reference cursor. Visit the appropriate reference 1345 // cursor. 1346 const Type *T = NNS->getAsType(); 1347 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1348 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1349 if (const TagType *Tag = dyn_cast<TagType>(T)) 1350 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1351 if (const TemplateSpecializationType *TST 1352 = dyn_cast<TemplateSpecializationType>(T)) 1353 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1354 break; 1355 } 1356 1357 case NestedNameSpecifier::TypeSpecWithTemplate: 1358 case NestedNameSpecifier::Global: 1359 case NestedNameSpecifier::Identifier: 1360 case NestedNameSpecifier::Super: 1361 break; 1362 } 1363 1364 return false; 1365 } 1366 1367 bool 1368 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1369 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1370 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1371 Qualifiers.push_back(Qualifier); 1372 1373 while (!Qualifiers.empty()) { 1374 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1375 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1376 switch (NNS->getKind()) { 1377 case NestedNameSpecifier::Namespace: 1378 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1379 Q.getLocalBeginLoc(), 1380 TU))) 1381 return true; 1382 1383 break; 1384 1385 case NestedNameSpecifier::NamespaceAlias: 1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1387 Q.getLocalBeginLoc(), 1388 TU))) 1389 return true; 1390 1391 break; 1392 1393 case NestedNameSpecifier::TypeSpec: 1394 case NestedNameSpecifier::TypeSpecWithTemplate: 1395 if (Visit(Q.getTypeLoc())) 1396 return true; 1397 1398 break; 1399 1400 case NestedNameSpecifier::Global: 1401 case NestedNameSpecifier::Identifier: 1402 case NestedNameSpecifier::Super: 1403 break; 1404 } 1405 } 1406 1407 return false; 1408 } 1409 1410 bool CursorVisitor::VisitTemplateParameters( 1411 const TemplateParameterList *Params) { 1412 if (!Params) 1413 return false; 1414 1415 for (TemplateParameterList::const_iterator P = Params->begin(), 1416 PEnd = Params->end(); 1417 P != PEnd; ++P) { 1418 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1419 return true; 1420 } 1421 1422 return false; 1423 } 1424 1425 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1426 switch (Name.getKind()) { 1427 case TemplateName::Template: 1428 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1429 1430 case TemplateName::OverloadedTemplate: 1431 // Visit the overloaded template set. 1432 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1433 return true; 1434 1435 return false; 1436 1437 case TemplateName::DependentTemplate: 1438 // FIXME: Visit nested-name-specifier. 1439 return false; 1440 1441 case TemplateName::QualifiedTemplate: 1442 // FIXME: Visit nested-name-specifier. 1443 return Visit(MakeCursorTemplateRef( 1444 Name.getAsQualifiedTemplateName()->getDecl(), 1445 Loc, TU)); 1446 1447 case TemplateName::SubstTemplateTemplateParm: 1448 return Visit(MakeCursorTemplateRef( 1449 Name.getAsSubstTemplateTemplateParm()->getParameter(), 1450 Loc, TU)); 1451 1452 case TemplateName::SubstTemplateTemplateParmPack: 1453 return Visit(MakeCursorTemplateRef( 1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), 1455 Loc, TU)); 1456 } 1457 1458 llvm_unreachable("Invalid TemplateName::Kind!"); 1459 } 1460 1461 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1462 switch (TAL.getArgument().getKind()) { 1463 case TemplateArgument::Null: 1464 case TemplateArgument::Integral: 1465 case TemplateArgument::Pack: 1466 return false; 1467 1468 case TemplateArgument::Type: 1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1470 return Visit(TSInfo->getTypeLoc()); 1471 return false; 1472 1473 case TemplateArgument::Declaration: 1474 if (Expr *E = TAL.getSourceDeclExpression()) 1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1476 return false; 1477 1478 case TemplateArgument::NullPtr: 1479 if (Expr *E = TAL.getSourceNullPtrExpression()) 1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1481 return false; 1482 1483 case TemplateArgument::Expression: 1484 if (Expr *E = TAL.getSourceExpression()) 1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1486 return false; 1487 1488 case TemplateArgument::Template: 1489 case TemplateArgument::TemplateExpansion: 1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1491 return true; 1492 1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1494 TAL.getTemplateNameLoc()); 1495 } 1496 1497 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1498 } 1499 1500 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1501 return VisitDeclContext(D); 1502 } 1503 1504 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1505 return Visit(TL.getUnqualifiedLoc()); 1506 } 1507 1508 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1509 ASTContext &Context = AU->getASTContext(); 1510 1511 // Some builtin types (such as Objective-C's "id", "sel", and 1512 // "Class") have associated declarations. Create cursors for those. 1513 QualType VisitType; 1514 switch (TL.getTypePtr()->getKind()) { 1515 1516 case BuiltinType::Void: 1517 case BuiltinType::NullPtr: 1518 case BuiltinType::Dependent: 1519 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1520 case BuiltinType::Id: 1521 #include "clang/Basic/OpenCLImageTypes.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::VisitOMPCollapseClause(const OMPCollapseClause *C) { 2172 Visitor->AddStmt(C->getNumForLoops()); 2173 } 2174 2175 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { } 2176 2177 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { } 2178 2179 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { 2180 VisitOMPClauseWithPreInit(C); 2181 Visitor->AddStmt(C->getChunkSize()); 2182 } 2183 2184 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) { 2185 Visitor->AddStmt(C->getNumForLoops()); 2186 } 2187 2188 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} 2189 2190 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} 2191 2192 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} 2193 2194 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} 2195 2196 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} 2197 2198 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} 2199 2200 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} 2201 2202 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} 2203 2204 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {} 2205 2206 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {} 2207 2208 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {} 2209 2210 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause( 2211 const OMPUnifiedAddressClause *) {} 2212 2213 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause( 2214 const OMPUnifiedSharedMemoryClause *) {} 2215 2216 void OMPClauseEnqueue::VisitOMPReverseOffloadClause( 2217 const OMPReverseOffloadClause *) {} 2218 2219 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause( 2220 const OMPDynamicAllocatorsClause *) {} 2221 2222 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) { 2223 Visitor->AddStmt(C->getDevice()); 2224 } 2225 2226 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) { 2227 VisitOMPClauseWithPreInit(C); 2228 Visitor->AddStmt(C->getNumTeams()); 2229 } 2230 2231 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) { 2232 VisitOMPClauseWithPreInit(C); 2233 Visitor->AddStmt(C->getThreadLimit()); 2234 } 2235 2236 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) { 2237 Visitor->AddStmt(C->getPriority()); 2238 } 2239 2240 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) { 2241 Visitor->AddStmt(C->getGrainsize()); 2242 } 2243 2244 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) { 2245 Visitor->AddStmt(C->getNumTasks()); 2246 } 2247 2248 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) { 2249 Visitor->AddStmt(C->getHint()); 2250 } 2251 2252 template<typename T> 2253 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { 2254 for (const auto *I : Node->varlists()) { 2255 Visitor->AddStmt(I); 2256 } 2257 } 2258 2259 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { 2260 VisitOMPClauseList(C); 2261 for (const auto *E : C->private_copies()) { 2262 Visitor->AddStmt(E); 2263 } 2264 } 2265 void OMPClauseEnqueue::VisitOMPFirstprivateClause( 2266 const OMPFirstprivateClause *C) { 2267 VisitOMPClauseList(C); 2268 VisitOMPClauseWithPreInit(C); 2269 for (const auto *E : C->private_copies()) { 2270 Visitor->AddStmt(E); 2271 } 2272 for (const auto *E : C->inits()) { 2273 Visitor->AddStmt(E); 2274 } 2275 } 2276 void OMPClauseEnqueue::VisitOMPLastprivateClause( 2277 const OMPLastprivateClause *C) { 2278 VisitOMPClauseList(C); 2279 VisitOMPClauseWithPostUpdate(C); 2280 for (auto *E : C->private_copies()) { 2281 Visitor->AddStmt(E); 2282 } 2283 for (auto *E : C->source_exprs()) { 2284 Visitor->AddStmt(E); 2285 } 2286 for (auto *E : C->destination_exprs()) { 2287 Visitor->AddStmt(E); 2288 } 2289 for (auto *E : C->assignment_ops()) { 2290 Visitor->AddStmt(E); 2291 } 2292 } 2293 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { 2294 VisitOMPClauseList(C); 2295 } 2296 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { 2297 VisitOMPClauseList(C); 2298 VisitOMPClauseWithPostUpdate(C); 2299 for (auto *E : C->privates()) { 2300 Visitor->AddStmt(E); 2301 } 2302 for (auto *E : C->lhs_exprs()) { 2303 Visitor->AddStmt(E); 2304 } 2305 for (auto *E : C->rhs_exprs()) { 2306 Visitor->AddStmt(E); 2307 } 2308 for (auto *E : C->reduction_ops()) { 2309 Visitor->AddStmt(E); 2310 } 2311 } 2312 void OMPClauseEnqueue::VisitOMPTaskReductionClause( 2313 const OMPTaskReductionClause *C) { 2314 VisitOMPClauseList(C); 2315 VisitOMPClauseWithPostUpdate(C); 2316 for (auto *E : C->privates()) { 2317 Visitor->AddStmt(E); 2318 } 2319 for (auto *E : C->lhs_exprs()) { 2320 Visitor->AddStmt(E); 2321 } 2322 for (auto *E : C->rhs_exprs()) { 2323 Visitor->AddStmt(E); 2324 } 2325 for (auto *E : C->reduction_ops()) { 2326 Visitor->AddStmt(E); 2327 } 2328 } 2329 void OMPClauseEnqueue::VisitOMPInReductionClause( 2330 const OMPInReductionClause *C) { 2331 VisitOMPClauseList(C); 2332 VisitOMPClauseWithPostUpdate(C); 2333 for (auto *E : C->privates()) { 2334 Visitor->AddStmt(E); 2335 } 2336 for (auto *E : C->lhs_exprs()) { 2337 Visitor->AddStmt(E); 2338 } 2339 for (auto *E : C->rhs_exprs()) { 2340 Visitor->AddStmt(E); 2341 } 2342 for (auto *E : C->reduction_ops()) { 2343 Visitor->AddStmt(E); 2344 } 2345 for (auto *E : C->taskgroup_descriptors()) 2346 Visitor->AddStmt(E); 2347 } 2348 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { 2349 VisitOMPClauseList(C); 2350 VisitOMPClauseWithPostUpdate(C); 2351 for (const auto *E : C->privates()) { 2352 Visitor->AddStmt(E); 2353 } 2354 for (const auto *E : C->inits()) { 2355 Visitor->AddStmt(E); 2356 } 2357 for (const auto *E : C->updates()) { 2358 Visitor->AddStmt(E); 2359 } 2360 for (const auto *E : C->finals()) { 2361 Visitor->AddStmt(E); 2362 } 2363 Visitor->AddStmt(C->getStep()); 2364 Visitor->AddStmt(C->getCalcStep()); 2365 } 2366 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { 2367 VisitOMPClauseList(C); 2368 Visitor->AddStmt(C->getAlignment()); 2369 } 2370 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { 2371 VisitOMPClauseList(C); 2372 for (auto *E : C->source_exprs()) { 2373 Visitor->AddStmt(E); 2374 } 2375 for (auto *E : C->destination_exprs()) { 2376 Visitor->AddStmt(E); 2377 } 2378 for (auto *E : C->assignment_ops()) { 2379 Visitor->AddStmt(E); 2380 } 2381 } 2382 void 2383 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) { 2384 VisitOMPClauseList(C); 2385 for (auto *E : C->source_exprs()) { 2386 Visitor->AddStmt(E); 2387 } 2388 for (auto *E : C->destination_exprs()) { 2389 Visitor->AddStmt(E); 2390 } 2391 for (auto *E : C->assignment_ops()) { 2392 Visitor->AddStmt(E); 2393 } 2394 } 2395 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { 2396 VisitOMPClauseList(C); 2397 } 2398 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { 2399 VisitOMPClauseList(C); 2400 } 2401 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) { 2402 VisitOMPClauseList(C); 2403 } 2404 void OMPClauseEnqueue::VisitOMPDistScheduleClause( 2405 const OMPDistScheduleClause *C) { 2406 VisitOMPClauseWithPreInit(C); 2407 Visitor->AddStmt(C->getChunkSize()); 2408 } 2409 void OMPClauseEnqueue::VisitOMPDefaultmapClause( 2410 const OMPDefaultmapClause * /*C*/) {} 2411 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) { 2412 VisitOMPClauseList(C); 2413 } 2414 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) { 2415 VisitOMPClauseList(C); 2416 } 2417 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) { 2418 VisitOMPClauseList(C); 2419 } 2420 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) { 2421 VisitOMPClauseList(C); 2422 } 2423 } 2424 2425 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { 2426 unsigned size = WL.size(); 2427 OMPClauseEnqueue Visitor(this); 2428 Visitor.Visit(S); 2429 if (size == WL.size()) 2430 return; 2431 // Now reverse the entries we just added. This will match the DFS 2432 // ordering performed by the worklist. 2433 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2434 std::reverse(I, E); 2435 } 2436 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { 2437 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 2438 } 2439 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { 2440 AddDecl(B->getBlockDecl()); 2441 } 2442 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2443 EnqueueChildren(E); 2444 AddTypeLoc(E->getTypeSourceInfo()); 2445 } 2446 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { 2447 for (auto &I : llvm::reverse(S->body())) 2448 AddStmt(I); 2449 } 2450 void EnqueueVisitor:: 2451 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) { 2452 AddStmt(S->getSubStmt()); 2453 AddDeclarationNameInfo(S); 2454 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 2455 AddNestedNameSpecifierLoc(QualifierLoc); 2456 } 2457 2458 void EnqueueVisitor:: 2459 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 2460 if (E->hasExplicitTemplateArgs()) 2461 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2462 AddDeclarationNameInfo(E); 2463 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2464 AddNestedNameSpecifierLoc(QualifierLoc); 2465 if (!E->isImplicitAccess()) 2466 AddStmt(E->getBase()); 2467 } 2468 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { 2469 // Enqueue the initializer , if any. 2470 AddStmt(E->getInitializer()); 2471 // Enqueue the array size, if any. 2472 AddStmt(E->getArraySize()); 2473 // Enqueue the allocated type. 2474 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 2475 // Enqueue the placement arguments. 2476 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 2477 AddStmt(E->getPlacementArg(I-1)); 2478 } 2479 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { 2480 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 2481 AddStmt(CE->getArg(I-1)); 2482 AddStmt(CE->getCallee()); 2483 AddStmt(CE->getArg(0)); 2484 } 2485 void EnqueueVisitor::VisitCXXPseudoDestructorExpr( 2486 const CXXPseudoDestructorExpr *E) { 2487 // Visit the name of the type being destroyed. 2488 AddTypeLoc(E->getDestroyedTypeInfo()); 2489 // Visit the scope type that looks disturbingly like the nested-name-specifier 2490 // but isn't. 2491 AddTypeLoc(E->getScopeTypeInfo()); 2492 // Visit the nested-name-specifier. 2493 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2494 AddNestedNameSpecifierLoc(QualifierLoc); 2495 // Visit base expression. 2496 AddStmt(E->getBase()); 2497 } 2498 void EnqueueVisitor::VisitCXXScalarValueInitExpr( 2499 const CXXScalarValueInitExpr *E) { 2500 AddTypeLoc(E->getTypeSourceInfo()); 2501 } 2502 void EnqueueVisitor::VisitCXXTemporaryObjectExpr( 2503 const CXXTemporaryObjectExpr *E) { 2504 EnqueueChildren(E); 2505 AddTypeLoc(E->getTypeSourceInfo()); 2506 } 2507 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2508 EnqueueChildren(E); 2509 if (E->isTypeOperand()) 2510 AddTypeLoc(E->getTypeOperandSourceInfo()); 2511 } 2512 2513 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( 2514 const CXXUnresolvedConstructExpr *E) { 2515 EnqueueChildren(E); 2516 AddTypeLoc(E->getTypeSourceInfo()); 2517 } 2518 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 2519 EnqueueChildren(E); 2520 if (E->isTypeOperand()) 2521 AddTypeLoc(E->getTypeOperandSourceInfo()); 2522 } 2523 2524 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { 2525 EnqueueChildren(S); 2526 AddDecl(S->getExceptionDecl()); 2527 } 2528 2529 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 2530 AddStmt(S->getBody()); 2531 AddStmt(S->getRangeInit()); 2532 AddDecl(S->getLoopVariable()); 2533 } 2534 2535 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { 2536 if (DR->hasExplicitTemplateArgs()) 2537 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs()); 2538 WL.push_back(DeclRefExprParts(DR, Parent)); 2539 } 2540 void EnqueueVisitor::VisitDependentScopeDeclRefExpr( 2541 const DependentScopeDeclRefExpr *E) { 2542 if (E->hasExplicitTemplateArgs()) 2543 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2544 AddDeclarationNameInfo(E); 2545 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 2546 } 2547 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { 2548 unsigned size = WL.size(); 2549 bool isFirst = true; 2550 for (const auto *D : S->decls()) { 2551 AddDecl(D, isFirst); 2552 isFirst = false; 2553 } 2554 if (size == WL.size()) 2555 return; 2556 // Now reverse the entries we just added. This will match the DFS 2557 // ordering performed by the worklist. 2558 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2559 std::reverse(I, E); 2560 } 2561 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { 2562 AddStmt(E->getInit()); 2563 for (const DesignatedInitExpr::Designator &D : 2564 llvm::reverse(E->designators())) { 2565 if (D.isFieldDesignator()) { 2566 if (FieldDecl *Field = D.getField()) 2567 AddMemberRef(Field, D.getFieldLoc()); 2568 continue; 2569 } 2570 if (D.isArrayDesignator()) { 2571 AddStmt(E->getArrayIndex(D)); 2572 continue; 2573 } 2574 assert(D.isArrayRangeDesignator() && "Unknown designator kind"); 2575 AddStmt(E->getArrayRangeEnd(D)); 2576 AddStmt(E->getArrayRangeStart(D)); 2577 } 2578 } 2579 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { 2580 EnqueueChildren(E); 2581 AddTypeLoc(E->getTypeInfoAsWritten()); 2582 } 2583 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { 2584 AddStmt(FS->getBody()); 2585 AddStmt(FS->getInc()); 2586 AddStmt(FS->getCond()); 2587 AddDecl(FS->getConditionVariable()); 2588 AddStmt(FS->getInit()); 2589 } 2590 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { 2591 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2592 } 2593 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { 2594 AddStmt(If->getElse()); 2595 AddStmt(If->getThen()); 2596 AddStmt(If->getCond()); 2597 AddDecl(If->getConditionVariable()); 2598 } 2599 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { 2600 // We care about the syntactic form of the initializer list, only. 2601 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2602 IE = Syntactic; 2603 EnqueueChildren(IE); 2604 } 2605 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { 2606 WL.push_back(MemberExprParts(M, Parent)); 2607 2608 // If the base of the member access expression is an implicit 'this', don't 2609 // visit it. 2610 // FIXME: If we ever want to show these implicit accesses, this will be 2611 // unfortunate. However, clang_getCursor() relies on this behavior. 2612 if (M->isImplicitAccess()) 2613 return; 2614 2615 // Ignore base anonymous struct/union fields, otherwise they will shadow the 2616 // real field that we are interested in. 2617 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) { 2618 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) { 2619 if (FD->isAnonymousStructOrUnion()) { 2620 AddStmt(SubME->getBase()); 2621 return; 2622 } 2623 } 2624 } 2625 2626 AddStmt(M->getBase()); 2627 } 2628 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2629 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2630 } 2631 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { 2632 EnqueueChildren(M); 2633 AddTypeLoc(M->getClassReceiverTypeInfo()); 2634 } 2635 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2636 // Visit the components of the offsetof expression. 2637 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2638 const OffsetOfNode &Node = E->getComponent(I-1); 2639 switch (Node.getKind()) { 2640 case OffsetOfNode::Array: 2641 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2642 break; 2643 case OffsetOfNode::Field: 2644 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2645 break; 2646 case OffsetOfNode::Identifier: 2647 case OffsetOfNode::Base: 2648 continue; 2649 } 2650 } 2651 // Visit the type into which we're computing the offset. 2652 AddTypeLoc(E->getTypeSourceInfo()); 2653 } 2654 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { 2655 if (E->hasExplicitTemplateArgs()) 2656 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2657 WL.push_back(OverloadExprParts(E, Parent)); 2658 } 2659 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2660 const UnaryExprOrTypeTraitExpr *E) { 2661 EnqueueChildren(E); 2662 if (E->isArgumentType()) 2663 AddTypeLoc(E->getArgumentTypeInfo()); 2664 } 2665 void EnqueueVisitor::VisitStmt(const Stmt *S) { 2666 EnqueueChildren(S); 2667 } 2668 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { 2669 AddStmt(S->getBody()); 2670 AddStmt(S->getCond()); 2671 AddDecl(S->getConditionVariable()); 2672 } 2673 2674 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { 2675 AddStmt(W->getBody()); 2676 AddStmt(W->getCond()); 2677 AddDecl(W->getConditionVariable()); 2678 } 2679 2680 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2681 for (unsigned I = E->getNumArgs(); I > 0; --I) 2682 AddTypeLoc(E->getArg(I-1)); 2683 } 2684 2685 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2686 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2687 } 2688 2689 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2690 EnqueueChildren(E); 2691 } 2692 2693 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { 2694 VisitOverloadExpr(U); 2695 if (!U->isImplicitAccess()) 2696 AddStmt(U->getBase()); 2697 } 2698 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { 2699 AddStmt(E->getSubExpr()); 2700 AddTypeLoc(E->getWrittenTypeInfo()); 2701 } 2702 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2703 WL.push_back(SizeOfPackExprParts(E, Parent)); 2704 } 2705 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 2706 // If the opaque value has a source expression, just transparently 2707 // visit that. This is useful for (e.g.) pseudo-object expressions. 2708 if (Expr *SourceExpr = E->getSourceExpr()) 2709 return Visit(SourceExpr); 2710 } 2711 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { 2712 AddStmt(E->getBody()); 2713 WL.push_back(LambdaExprParts(E, Parent)); 2714 } 2715 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 2716 // Treat the expression like its syntactic form. 2717 Visit(E->getSyntacticForm()); 2718 } 2719 2720 void EnqueueVisitor::VisitOMPExecutableDirective( 2721 const OMPExecutableDirective *D) { 2722 EnqueueChildren(D); 2723 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(), 2724 E = D->clauses().end(); 2725 I != E; ++I) 2726 EnqueueChildren(*I); 2727 } 2728 2729 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { 2730 VisitOMPExecutableDirective(D); 2731 } 2732 2733 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { 2734 VisitOMPExecutableDirective(D); 2735 } 2736 2737 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { 2738 VisitOMPLoopDirective(D); 2739 } 2740 2741 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { 2742 VisitOMPLoopDirective(D); 2743 } 2744 2745 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { 2746 VisitOMPLoopDirective(D); 2747 } 2748 2749 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { 2750 VisitOMPExecutableDirective(D); 2751 } 2752 2753 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { 2754 VisitOMPExecutableDirective(D); 2755 } 2756 2757 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { 2758 VisitOMPExecutableDirective(D); 2759 } 2760 2761 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { 2762 VisitOMPExecutableDirective(D); 2763 } 2764 2765 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { 2766 VisitOMPExecutableDirective(D); 2767 AddDeclarationNameInfo(D); 2768 } 2769 2770 void 2771 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) { 2772 VisitOMPLoopDirective(D); 2773 } 2774 2775 void EnqueueVisitor::VisitOMPParallelForSimdDirective( 2776 const OMPParallelForSimdDirective *D) { 2777 VisitOMPLoopDirective(D); 2778 } 2779 2780 void EnqueueVisitor::VisitOMPParallelSectionsDirective( 2781 const OMPParallelSectionsDirective *D) { 2782 VisitOMPExecutableDirective(D); 2783 } 2784 2785 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { 2786 VisitOMPExecutableDirective(D); 2787 } 2788 2789 void 2790 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) { 2791 VisitOMPExecutableDirective(D); 2792 } 2793 2794 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { 2795 VisitOMPExecutableDirective(D); 2796 } 2797 2798 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { 2799 VisitOMPExecutableDirective(D); 2800 } 2801 2802 void EnqueueVisitor::VisitOMPTaskgroupDirective( 2803 const OMPTaskgroupDirective *D) { 2804 VisitOMPExecutableDirective(D); 2805 if (const Expr *E = D->getReductionRef()) 2806 VisitStmt(E); 2807 } 2808 2809 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { 2810 VisitOMPExecutableDirective(D); 2811 } 2812 2813 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { 2814 VisitOMPExecutableDirective(D); 2815 } 2816 2817 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { 2818 VisitOMPExecutableDirective(D); 2819 } 2820 2821 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { 2822 VisitOMPExecutableDirective(D); 2823 } 2824 2825 void EnqueueVisitor::VisitOMPTargetDataDirective(const 2826 OMPTargetDataDirective *D) { 2827 VisitOMPExecutableDirective(D); 2828 } 2829 2830 void EnqueueVisitor::VisitOMPTargetEnterDataDirective( 2831 const OMPTargetEnterDataDirective *D) { 2832 VisitOMPExecutableDirective(D); 2833 } 2834 2835 void EnqueueVisitor::VisitOMPTargetExitDataDirective( 2836 const OMPTargetExitDataDirective *D) { 2837 VisitOMPExecutableDirective(D); 2838 } 2839 2840 void EnqueueVisitor::VisitOMPTargetParallelDirective( 2841 const OMPTargetParallelDirective *D) { 2842 VisitOMPExecutableDirective(D); 2843 } 2844 2845 void EnqueueVisitor::VisitOMPTargetParallelForDirective( 2846 const OMPTargetParallelForDirective *D) { 2847 VisitOMPLoopDirective(D); 2848 } 2849 2850 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { 2851 VisitOMPExecutableDirective(D); 2852 } 2853 2854 void EnqueueVisitor::VisitOMPCancellationPointDirective( 2855 const OMPCancellationPointDirective *D) { 2856 VisitOMPExecutableDirective(D); 2857 } 2858 2859 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { 2860 VisitOMPExecutableDirective(D); 2861 } 2862 2863 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) { 2864 VisitOMPLoopDirective(D); 2865 } 2866 2867 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective( 2868 const OMPTaskLoopSimdDirective *D) { 2869 VisitOMPLoopDirective(D); 2870 } 2871 2872 void EnqueueVisitor::VisitOMPDistributeDirective( 2873 const OMPDistributeDirective *D) { 2874 VisitOMPLoopDirective(D); 2875 } 2876 2877 void EnqueueVisitor::VisitOMPDistributeParallelForDirective( 2878 const OMPDistributeParallelForDirective *D) { 2879 VisitOMPLoopDirective(D); 2880 } 2881 2882 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective( 2883 const OMPDistributeParallelForSimdDirective *D) { 2884 VisitOMPLoopDirective(D); 2885 } 2886 2887 void EnqueueVisitor::VisitOMPDistributeSimdDirective( 2888 const OMPDistributeSimdDirective *D) { 2889 VisitOMPLoopDirective(D); 2890 } 2891 2892 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective( 2893 const OMPTargetParallelForSimdDirective *D) { 2894 VisitOMPLoopDirective(D); 2895 } 2896 2897 void EnqueueVisitor::VisitOMPTargetSimdDirective( 2898 const OMPTargetSimdDirective *D) { 2899 VisitOMPLoopDirective(D); 2900 } 2901 2902 void EnqueueVisitor::VisitOMPTeamsDistributeDirective( 2903 const OMPTeamsDistributeDirective *D) { 2904 VisitOMPLoopDirective(D); 2905 } 2906 2907 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective( 2908 const OMPTeamsDistributeSimdDirective *D) { 2909 VisitOMPLoopDirective(D); 2910 } 2911 2912 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective( 2913 const OMPTeamsDistributeParallelForSimdDirective *D) { 2914 VisitOMPLoopDirective(D); 2915 } 2916 2917 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective( 2918 const OMPTeamsDistributeParallelForDirective *D) { 2919 VisitOMPLoopDirective(D); 2920 } 2921 2922 void EnqueueVisitor::VisitOMPTargetTeamsDirective( 2923 const OMPTargetTeamsDirective *D) { 2924 VisitOMPExecutableDirective(D); 2925 } 2926 2927 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective( 2928 const OMPTargetTeamsDistributeDirective *D) { 2929 VisitOMPLoopDirective(D); 2930 } 2931 2932 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective( 2933 const OMPTargetTeamsDistributeParallelForDirective *D) { 2934 VisitOMPLoopDirective(D); 2935 } 2936 2937 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective( 2938 const OMPTargetTeamsDistributeParallelForSimdDirective *D) { 2939 VisitOMPLoopDirective(D); 2940 } 2941 2942 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective( 2943 const OMPTargetTeamsDistributeSimdDirective *D) { 2944 VisitOMPLoopDirective(D); 2945 } 2946 2947 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { 2948 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); 2949 } 2950 2951 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 2952 if (RegionOfInterest.isValid()) { 2953 SourceRange Range = getRawCursorExtent(C); 2954 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 2955 return false; 2956 } 2957 return true; 2958 } 2959 2960 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 2961 while (!WL.empty()) { 2962 // Dequeue the worklist item. 2963 VisitorJob LI = WL.pop_back_val(); 2964 2965 // Set the Parent field, then back to its old value once we're done. 2966 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 2967 2968 switch (LI.getKind()) { 2969 case VisitorJob::DeclVisitKind: { 2970 const Decl *D = cast<DeclVisit>(&LI)->get(); 2971 if (!D) 2972 continue; 2973 2974 // For now, perform default visitation for Decls. 2975 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 2976 cast<DeclVisit>(&LI)->isFirst()))) 2977 return true; 2978 2979 continue; 2980 } 2981 case VisitorJob::ExplicitTemplateArgsVisitKind: { 2982 for (const TemplateArgumentLoc &Arg : 2983 *cast<ExplicitTemplateArgsVisit>(&LI)) { 2984 if (VisitTemplateArgumentLoc(Arg)) 2985 return true; 2986 } 2987 continue; 2988 } 2989 case VisitorJob::TypeLocVisitKind: { 2990 // Perform default visitation for TypeLocs. 2991 if (Visit(cast<TypeLocVisit>(&LI)->get())) 2992 return true; 2993 continue; 2994 } 2995 case VisitorJob::LabelRefVisitKind: { 2996 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 2997 if (LabelStmt *stmt = LS->getStmt()) { 2998 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 2999 TU))) { 3000 return true; 3001 } 3002 } 3003 continue; 3004 } 3005 3006 case VisitorJob::NestedNameSpecifierLocVisitKind: { 3007 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 3008 if (VisitNestedNameSpecifierLoc(V->get())) 3009 return true; 3010 continue; 3011 } 3012 3013 case VisitorJob::DeclarationNameInfoVisitKind: { 3014 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) 3015 ->get())) 3016 return true; 3017 continue; 3018 } 3019 case VisitorJob::MemberRefVisitKind: { 3020 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 3021 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 3022 return true; 3023 continue; 3024 } 3025 case VisitorJob::StmtVisitKind: { 3026 const Stmt *S = cast<StmtVisit>(&LI)->get(); 3027 if (!S) 3028 continue; 3029 3030 // Update the current cursor. 3031 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 3032 if (!IsInRegionOfInterest(Cursor)) 3033 continue; 3034 switch (Visitor(Cursor, Parent, ClientData)) { 3035 case CXChildVisit_Break: return true; 3036 case CXChildVisit_Continue: break; 3037 case CXChildVisit_Recurse: 3038 if (PostChildrenVisitor) 3039 WL.push_back(PostChildrenVisit(nullptr, Cursor)); 3040 EnqueueWorkList(WL, S); 3041 break; 3042 } 3043 continue; 3044 } 3045 case VisitorJob::MemberExprPartsKind: { 3046 // Handle the other pieces in the MemberExpr besides the base. 3047 const MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 3048 3049 // Visit the nested-name-specifier 3050 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 3051 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3052 return true; 3053 3054 // Visit the declaration name. 3055 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 3056 return true; 3057 3058 // Visit the explicitly-specified template arguments, if any. 3059 if (M->hasExplicitTemplateArgs()) { 3060 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 3061 *ArgEnd = Arg + M->getNumTemplateArgs(); 3062 Arg != ArgEnd; ++Arg) { 3063 if (VisitTemplateArgumentLoc(*Arg)) 3064 return true; 3065 } 3066 } 3067 continue; 3068 } 3069 case VisitorJob::DeclRefExprPartsKind: { 3070 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 3071 // Visit nested-name-specifier, if present. 3072 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 3073 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3074 return true; 3075 // Visit declaration name. 3076 if (VisitDeclarationNameInfo(DR->getNameInfo())) 3077 return true; 3078 continue; 3079 } 3080 case VisitorJob::OverloadExprPartsKind: { 3081 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 3082 // Visit the nested-name-specifier. 3083 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 3084 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3085 return true; 3086 // Visit the declaration name. 3087 if (VisitDeclarationNameInfo(O->getNameInfo())) 3088 return true; 3089 // Visit the overloaded declaration reference. 3090 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 3091 return true; 3092 continue; 3093 } 3094 case VisitorJob::SizeOfPackExprPartsKind: { 3095 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 3096 NamedDecl *Pack = E->getPack(); 3097 if (isa<TemplateTypeParmDecl>(Pack)) { 3098 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 3099 E->getPackLoc(), TU))) 3100 return true; 3101 3102 continue; 3103 } 3104 3105 if (isa<TemplateTemplateParmDecl>(Pack)) { 3106 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 3107 E->getPackLoc(), TU))) 3108 return true; 3109 3110 continue; 3111 } 3112 3113 // Non-type template parameter packs and function parameter packs are 3114 // treated like DeclRefExpr cursors. 3115 continue; 3116 } 3117 3118 case VisitorJob::LambdaExprPartsKind: { 3119 // Visit captures. 3120 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 3121 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 3122 CEnd = E->explicit_capture_end(); 3123 C != CEnd; ++C) { 3124 // FIXME: Lambda init-captures. 3125 if (!C->capturesVariable()) 3126 continue; 3127 3128 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), 3129 C->getLocation(), 3130 TU))) 3131 return true; 3132 } 3133 3134 // Visit parameters and return type, if present. 3135 if (E->hasExplicitParameters() || E->hasExplicitResultType()) { 3136 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 3137 if (E->hasExplicitParameters() && E->hasExplicitResultType()) { 3138 // Visit the whole type. 3139 if (Visit(TL)) 3140 return true; 3141 } else if (FunctionProtoTypeLoc Proto = 3142 TL.getAs<FunctionProtoTypeLoc>()) { 3143 if (E->hasExplicitParameters()) { 3144 // Visit parameters. 3145 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) 3146 if (Visit(MakeCXCursor(Proto.getParam(I), TU))) 3147 return true; 3148 } else { 3149 // Visit result type. 3150 if (Visit(Proto.getReturnLoc())) 3151 return true; 3152 } 3153 } 3154 } 3155 break; 3156 } 3157 3158 case VisitorJob::PostChildrenVisitKind: 3159 if (PostChildrenVisitor(Parent, ClientData)) 3160 return true; 3161 break; 3162 } 3163 } 3164 return false; 3165 } 3166 3167 bool CursorVisitor::Visit(const Stmt *S) { 3168 VisitorWorkList *WL = nullptr; 3169 if (!WorkListFreeList.empty()) { 3170 WL = WorkListFreeList.back(); 3171 WL->clear(); 3172 WorkListFreeList.pop_back(); 3173 } 3174 else { 3175 WL = new VisitorWorkList(); 3176 WorkListCache.push_back(WL); 3177 } 3178 EnqueueWorkList(*WL, S); 3179 bool result = RunVisitorWorkList(*WL); 3180 WorkListFreeList.push_back(WL); 3181 return result; 3182 } 3183 3184 namespace { 3185 typedef SmallVector<SourceRange, 4> RefNamePieces; 3186 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 3187 const DeclarationNameInfo &NI, SourceRange QLoc, 3188 const SourceRange *TemplateArgsLoc = nullptr) { 3189 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 3190 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 3191 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 3192 3193 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 3194 3195 RefNamePieces Pieces; 3196 3197 if (WantQualifier && QLoc.isValid()) 3198 Pieces.push_back(QLoc); 3199 3200 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 3201 Pieces.push_back(NI.getLoc()); 3202 3203 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid()) 3204 Pieces.push_back(*TemplateArgsLoc); 3205 3206 if (Kind == DeclarationName::CXXOperatorName) { 3207 Pieces.push_back(SourceLocation::getFromRawEncoding( 3208 NI.getInfo().CXXOperatorName.BeginOpNameLoc)); 3209 Pieces.push_back(SourceLocation::getFromRawEncoding( 3210 NI.getInfo().CXXOperatorName.EndOpNameLoc)); 3211 } 3212 3213 if (WantSinglePiece) { 3214 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 3215 Pieces.clear(); 3216 Pieces.push_back(R); 3217 } 3218 3219 return Pieces; 3220 } 3221 } 3222 3223 //===----------------------------------------------------------------------===// 3224 // Misc. API hooks. 3225 //===----------------------------------------------------------------------===// 3226 3227 static void fatal_error_handler(void *user_data, const std::string& reason, 3228 bool gen_crash_diag) { 3229 // Write the result out to stderr avoiding errs() because raw_ostreams can 3230 // call report_fatal_error. 3231 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); 3232 ::abort(); 3233 } 3234 3235 namespace { 3236 struct RegisterFatalErrorHandler { 3237 RegisterFatalErrorHandler() { 3238 llvm::install_fatal_error_handler(fatal_error_handler, nullptr); 3239 } 3240 }; 3241 } 3242 3243 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce; 3244 3245 CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 3246 int displayDiagnostics) { 3247 // We use crash recovery to make some of our APIs more reliable, implicitly 3248 // enable it. 3249 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) 3250 llvm::CrashRecoveryContext::Enable(); 3251 3252 // Look through the managed static to trigger construction of the managed 3253 // static which registers our fatal error handler. This ensures it is only 3254 // registered once. 3255 (void)*RegisterFatalErrorHandlerOnce; 3256 3257 // Initialize targets for clang module support. 3258 llvm::InitializeAllTargets(); 3259 llvm::InitializeAllTargetMCs(); 3260 llvm::InitializeAllAsmPrinters(); 3261 llvm::InitializeAllAsmParsers(); 3262 3263 CIndexer *CIdxr = new CIndexer(); 3264 3265 if (excludeDeclarationsFromPCH) 3266 CIdxr->setOnlyLocalDecls(); 3267 if (displayDiagnostics) 3268 CIdxr->setDisplayDiagnostics(); 3269 3270 if (getenv("LIBCLANG_BGPRIO_INDEX")) 3271 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3272 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 3273 if (getenv("LIBCLANG_BGPRIO_EDIT")) 3274 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3275 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 3276 3277 return CIdxr; 3278 } 3279 3280 void clang_disposeIndex(CXIndex CIdx) { 3281 if (CIdx) 3282 delete static_cast<CIndexer *>(CIdx); 3283 } 3284 3285 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 3286 if (CIdx) 3287 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 3288 } 3289 3290 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 3291 if (CIdx) 3292 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 3293 return 0; 3294 } 3295 3296 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx, 3297 const char *Path) { 3298 if (CIdx) 3299 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : ""); 3300 } 3301 3302 void clang_toggleCrashRecovery(unsigned isEnabled) { 3303 if (isEnabled) 3304 llvm::CrashRecoveryContext::Enable(); 3305 else 3306 llvm::CrashRecoveryContext::Disable(); 3307 } 3308 3309 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 3310 const char *ast_filename) { 3311 CXTranslationUnit TU; 3312 enum CXErrorCode Result = 3313 clang_createTranslationUnit2(CIdx, ast_filename, &TU); 3314 (void)Result; 3315 assert((TU && Result == CXError_Success) || 3316 (!TU && Result != CXError_Success)); 3317 return TU; 3318 } 3319 3320 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, 3321 const char *ast_filename, 3322 CXTranslationUnit *out_TU) { 3323 if (out_TU) 3324 *out_TU = nullptr; 3325 3326 if (!CIdx || !ast_filename || !out_TU) 3327 return CXError_InvalidArguments; 3328 3329 LOG_FUNC_SECTION { 3330 *Log << ast_filename; 3331 } 3332 3333 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3334 FileSystemOptions FileSystemOpts; 3335 3336 IntrusiveRefCntPtr<DiagnosticsEngine> Diags = 3337 CompilerInstance::createDiagnostics(new DiagnosticOptions()); 3338 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile( 3339 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), 3340 ASTUnit::LoadEverything, Diags, 3341 FileSystemOpts, /*UseDebugInfo=*/false, 3342 CXXIdx->getOnlyLocalDecls(), None, 3343 /*CaptureDiagnostics=*/true, 3344 /*AllowPCHWithCompilerErrors=*/true, 3345 /*UserFilesAreVolatile=*/true); 3346 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU)); 3347 return *out_TU ? CXError_Success : CXError_Failure; 3348 } 3349 3350 unsigned clang_defaultEditingTranslationUnitOptions() { 3351 return CXTranslationUnit_PrecompiledPreamble | 3352 CXTranslationUnit_CacheCompletionResults; 3353 } 3354 3355 CXTranslationUnit 3356 clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 3357 const char *source_filename, 3358 int num_command_line_args, 3359 const char * const *command_line_args, 3360 unsigned num_unsaved_files, 3361 struct CXUnsavedFile *unsaved_files) { 3362 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 3363 return clang_parseTranslationUnit(CIdx, source_filename, 3364 command_line_args, num_command_line_args, 3365 unsaved_files, num_unsaved_files, 3366 Options); 3367 } 3368 3369 static CXErrorCode 3370 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename, 3371 const char *const *command_line_args, 3372 int num_command_line_args, 3373 ArrayRef<CXUnsavedFile> unsaved_files, 3374 unsigned options, CXTranslationUnit *out_TU) { 3375 // Set up the initial return values. 3376 if (out_TU) 3377 *out_TU = nullptr; 3378 3379 // Check arguments. 3380 if (!CIdx || !out_TU) 3381 return CXError_InvalidArguments; 3382 3383 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3384 3385 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 3386 setThreadBackgroundPriority(); 3387 3388 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 3389 bool CreatePreambleOnFirstParse = 3390 options & CXTranslationUnit_CreatePreambleOnFirstParse; 3391 // FIXME: Add a flag for modules. 3392 TranslationUnitKind TUKind 3393 = (options & (CXTranslationUnit_Incomplete | 3394 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete; 3395 bool CacheCodeCompletionResults 3396 = options & CXTranslationUnit_CacheCompletionResults; 3397 bool IncludeBriefCommentsInCodeCompletion 3398 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 3399 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse; 3400 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 3401 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None; 3402 if (options & CXTranslationUnit_SkipFunctionBodies) { 3403 SkipFunctionBodies = 3404 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble) 3405 ? SkipFunctionBodiesScope::Preamble 3406 : SkipFunctionBodiesScope::PreambleAndMainFile; 3407 } 3408 3409 // Configure the diagnostics. 3410 IntrusiveRefCntPtr<DiagnosticsEngine> 3411 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)); 3412 3413 if (options & CXTranslationUnit_KeepGoing) 3414 Diags->setSuppressAfterFatalError(false); 3415 3416 // Recover resources if we crash before exiting this function. 3417 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 3418 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 3419 DiagCleanup(Diags.get()); 3420 3421 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 3422 new std::vector<ASTUnit::RemappedFile>()); 3423 3424 // Recover resources if we crash before exiting this function. 3425 llvm::CrashRecoveryContextCleanupRegistrar< 3426 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 3427 3428 for (auto &UF : unsaved_files) { 3429 std::unique_ptr<llvm::MemoryBuffer> MB = 3430 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 3431 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 3432 } 3433 3434 std::unique_ptr<std::vector<const char *>> Args( 3435 new std::vector<const char *>()); 3436 3437 // Recover resources if we crash before exiting this method. 3438 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 3439 ArgsCleanup(Args.get()); 3440 3441 // Since the Clang C library is primarily used by batch tools dealing with 3442 // (often very broken) source code, where spell-checking can have a 3443 // significant negative impact on performance (particularly when 3444 // precompiled headers are involved), we disable it by default. 3445 // Only do this if we haven't found a spell-checking-related argument. 3446 bool FoundSpellCheckingArgument = false; 3447 for (int I = 0; I != num_command_line_args; ++I) { 3448 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 3449 strcmp(command_line_args[I], "-fspell-checking") == 0) { 3450 FoundSpellCheckingArgument = true; 3451 break; 3452 } 3453 } 3454 Args->insert(Args->end(), command_line_args, 3455 command_line_args + num_command_line_args); 3456 3457 if (!FoundSpellCheckingArgument) 3458 Args->insert(Args->begin() + 1, "-fno-spell-checking"); 3459 3460 // The 'source_filename' argument is optional. If the caller does not 3461 // specify it then it is assumed that the source file is specified 3462 // in the actual argument list. 3463 // Put the source file after command_line_args otherwise if '-x' flag is 3464 // present it will be unused. 3465 if (source_filename) 3466 Args->push_back(source_filename); 3467 3468 // Do we need the detailed preprocessing record? 3469 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 3470 Args->push_back("-Xclang"); 3471 Args->push_back("-detailed-preprocessing-record"); 3472 } 3473 3474 // Suppress any editor placeholder diagnostics. 3475 Args->push_back("-fallow-editor-placeholders"); 3476 3477 unsigned NumErrors = Diags->getClient()->getNumErrors(); 3478 std::unique_ptr<ASTUnit> ErrUnit; 3479 // Unless the user specified that they want the preamble on the first parse 3480 // set it up to be created on the first reparse. This makes the first parse 3481 // faster, trading for a slower (first) reparse. 3482 unsigned PrecompilePreambleAfterNParses = 3483 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse; 3484 3485 LibclangInvocationReporter InvocationReporter( 3486 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation, 3487 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None, 3488 unsaved_files); 3489 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine( 3490 Args->data(), Args->data() + Args->size(), 3491 CXXIdx->getPCHContainerOperations(), Diags, 3492 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), 3493 /*CaptureDiagnostics=*/true, *RemappedFiles.get(), 3494 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses, 3495 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, 3496 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse, 3497 /*UserFilesAreVolatile=*/true, ForSerialization, 3498 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(), 3499 &ErrUnit)); 3500 3501 // Early failures in LoadFromCommandLine may return with ErrUnit unset. 3502 if (!Unit && !ErrUnit) 3503 return CXError_ASTReadError; 3504 3505 if (NumErrors != Diags->getClient()->getNumErrors()) { 3506 // Make sure to check that 'Unit' is non-NULL. 3507 if (CXXIdx->getDisplayDiagnostics()) 3508 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 3509 } 3510 3511 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) 3512 return CXError_ASTReadError; 3513 3514 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit)); 3515 if (CXTranslationUnitImpl *TU = *out_TU) { 3516 TU->ParsingOptions = options; 3517 TU->Arguments.reserve(Args->size()); 3518 for (const char *Arg : *Args) 3519 TU->Arguments.push_back(Arg); 3520 return CXError_Success; 3521 } 3522 return CXError_Failure; 3523 } 3524 3525 CXTranslationUnit 3526 clang_parseTranslationUnit(CXIndex CIdx, 3527 const char *source_filename, 3528 const char *const *command_line_args, 3529 int num_command_line_args, 3530 struct CXUnsavedFile *unsaved_files, 3531 unsigned num_unsaved_files, 3532 unsigned options) { 3533 CXTranslationUnit TU; 3534 enum CXErrorCode Result = clang_parseTranslationUnit2( 3535 CIdx, source_filename, command_line_args, num_command_line_args, 3536 unsaved_files, num_unsaved_files, options, &TU); 3537 (void)Result; 3538 assert((TU && Result == CXError_Success) || 3539 (!TU && Result != CXError_Success)); 3540 return TU; 3541 } 3542 3543 enum CXErrorCode clang_parseTranslationUnit2( 3544 CXIndex CIdx, const char *source_filename, 3545 const char *const *command_line_args, int num_command_line_args, 3546 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3547 unsigned options, CXTranslationUnit *out_TU) { 3548 SmallVector<const char *, 4> Args; 3549 Args.push_back("clang"); 3550 Args.append(command_line_args, command_line_args + num_command_line_args); 3551 return clang_parseTranslationUnit2FullArgv( 3552 CIdx, source_filename, Args.data(), Args.size(), unsaved_files, 3553 num_unsaved_files, options, out_TU); 3554 } 3555 3556 enum CXErrorCode clang_parseTranslationUnit2FullArgv( 3557 CXIndex CIdx, const char *source_filename, 3558 const char *const *command_line_args, int num_command_line_args, 3559 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3560 unsigned options, CXTranslationUnit *out_TU) { 3561 LOG_FUNC_SECTION { 3562 *Log << source_filename << ": "; 3563 for (int i = 0; i != num_command_line_args; ++i) 3564 *Log << command_line_args[i] << " "; 3565 } 3566 3567 if (num_unsaved_files && !unsaved_files) 3568 return CXError_InvalidArguments; 3569 3570 CXErrorCode result = CXError_Failure; 3571 auto ParseTranslationUnitImpl = [=, &result] { 3572 result = clang_parseTranslationUnit_Impl( 3573 CIdx, source_filename, command_line_args, num_command_line_args, 3574 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU); 3575 }; 3576 3577 llvm::CrashRecoveryContext CRC; 3578 3579 if (!RunSafely(CRC, ParseTranslationUnitImpl)) { 3580 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 3581 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 3582 fprintf(stderr, " 'command_line_args' : ["); 3583 for (int i = 0; i != num_command_line_args; ++i) { 3584 if (i) 3585 fprintf(stderr, ", "); 3586 fprintf(stderr, "'%s'", command_line_args[i]); 3587 } 3588 fprintf(stderr, "],\n"); 3589 fprintf(stderr, " 'unsaved_files' : ["); 3590 for (unsigned i = 0; i != num_unsaved_files; ++i) { 3591 if (i) 3592 fprintf(stderr, ", "); 3593 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 3594 unsaved_files[i].Length); 3595 } 3596 fprintf(stderr, "],\n"); 3597 fprintf(stderr, " 'options' : %d,\n", options); 3598 fprintf(stderr, "}\n"); 3599 3600 return CXError_Crashed; 3601 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 3602 if (CXTranslationUnit *TU = out_TU) 3603 PrintLibclangResourceUsage(*TU); 3604 } 3605 3606 return result; 3607 } 3608 3609 CXString clang_Type_getObjCEncoding(CXType CT) { 3610 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]); 3611 ASTContext &Ctx = getASTUnit(tu)->getASTContext(); 3612 std::string encoding; 3613 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), 3614 encoding); 3615 3616 return cxstring::createDup(encoding); 3617 } 3618 3619 static const IdentifierInfo *getMacroIdentifier(CXCursor C) { 3620 if (C.kind == CXCursor_MacroDefinition) { 3621 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C)) 3622 return MDR->getName(); 3623 } else if (C.kind == CXCursor_MacroExpansion) { 3624 MacroExpansionCursor ME = getCursorMacroExpansion(C); 3625 return ME.getName(); 3626 } 3627 return nullptr; 3628 } 3629 3630 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) { 3631 const IdentifierInfo *II = getMacroIdentifier(C); 3632 if (!II) { 3633 return false; 3634 } 3635 ASTUnit *ASTU = getCursorASTUnit(C); 3636 Preprocessor &PP = ASTU->getPreprocessor(); 3637 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3638 return MI->isFunctionLike(); 3639 return false; 3640 } 3641 3642 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) { 3643 const IdentifierInfo *II = getMacroIdentifier(C); 3644 if (!II) { 3645 return false; 3646 } 3647 ASTUnit *ASTU = getCursorASTUnit(C); 3648 Preprocessor &PP = ASTU->getPreprocessor(); 3649 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3650 return MI->isBuiltinMacro(); 3651 return false; 3652 } 3653 3654 unsigned clang_Cursor_isFunctionInlined(CXCursor C) { 3655 const Decl *D = getCursorDecl(C); 3656 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 3657 if (!FD) { 3658 return false; 3659 } 3660 return FD->isInlined(); 3661 } 3662 3663 static StringLiteral* getCFSTR_value(CallExpr *callExpr) { 3664 if (callExpr->getNumArgs() != 1) { 3665 return nullptr; 3666 } 3667 3668 StringLiteral *S = nullptr; 3669 auto *arg = callExpr->getArg(0); 3670 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) { 3671 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg); 3672 auto *subExpr = I->getSubExprAsWritten(); 3673 3674 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){ 3675 return nullptr; 3676 } 3677 3678 S = static_cast<StringLiteral *>(I->getSubExprAsWritten()); 3679 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) { 3680 S = static_cast<StringLiteral *>(callExpr->getArg(0)); 3681 } else { 3682 return nullptr; 3683 } 3684 return S; 3685 } 3686 3687 struct ExprEvalResult { 3688 CXEvalResultKind EvalType; 3689 union { 3690 unsigned long long unsignedVal; 3691 long long intVal; 3692 double floatVal; 3693 char *stringVal; 3694 } EvalData; 3695 bool IsUnsignedInt; 3696 ~ExprEvalResult() { 3697 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float && 3698 EvalType != CXEval_Int) { 3699 delete EvalData.stringVal; 3700 } 3701 } 3702 }; 3703 3704 void clang_EvalResult_dispose(CXEvalResult E) { 3705 delete static_cast<ExprEvalResult *>(E); 3706 } 3707 3708 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) { 3709 if (!E) { 3710 return CXEval_UnExposed; 3711 } 3712 return ((ExprEvalResult *)E)->EvalType; 3713 } 3714 3715 int clang_EvalResult_getAsInt(CXEvalResult E) { 3716 return clang_EvalResult_getAsLongLong(E); 3717 } 3718 3719 long long clang_EvalResult_getAsLongLong(CXEvalResult E) { 3720 if (!E) { 3721 return 0; 3722 } 3723 ExprEvalResult *Result = (ExprEvalResult*)E; 3724 if (Result->IsUnsignedInt) 3725 return Result->EvalData.unsignedVal; 3726 return Result->EvalData.intVal; 3727 } 3728 3729 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) { 3730 return ((ExprEvalResult *)E)->IsUnsignedInt; 3731 } 3732 3733 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) { 3734 if (!E) { 3735 return 0; 3736 } 3737 3738 ExprEvalResult *Result = (ExprEvalResult*)E; 3739 if (Result->IsUnsignedInt) 3740 return Result->EvalData.unsignedVal; 3741 return Result->EvalData.intVal; 3742 } 3743 3744 double clang_EvalResult_getAsDouble(CXEvalResult E) { 3745 if (!E) { 3746 return 0; 3747 } 3748 return ((ExprEvalResult *)E)->EvalData.floatVal; 3749 } 3750 3751 const char* clang_EvalResult_getAsStr(CXEvalResult E) { 3752 if (!E) { 3753 return nullptr; 3754 } 3755 return ((ExprEvalResult *)E)->EvalData.stringVal; 3756 } 3757 3758 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) { 3759 Expr::EvalResult ER; 3760 ASTContext &ctx = getCursorContext(C); 3761 if (!expr) 3762 return nullptr; 3763 3764 expr = expr->IgnoreParens(); 3765 if (!expr->EvaluateAsRValue(ER, ctx)) 3766 return nullptr; 3767 3768 QualType rettype; 3769 CallExpr *callExpr; 3770 auto result = llvm::make_unique<ExprEvalResult>(); 3771 result->EvalType = CXEval_UnExposed; 3772 result->IsUnsignedInt = false; 3773 3774 if (ER.Val.isInt()) { 3775 result->EvalType = CXEval_Int; 3776 3777 auto& val = ER.Val.getInt(); 3778 if (val.isUnsigned()) { 3779 result->IsUnsignedInt = true; 3780 result->EvalData.unsignedVal = val.getZExtValue(); 3781 } else { 3782 result->EvalData.intVal = val.getExtValue(); 3783 } 3784 3785 return result.release(); 3786 } 3787 3788 if (ER.Val.isFloat()) { 3789 llvm::SmallVector<char, 100> Buffer; 3790 ER.Val.getFloat().toString(Buffer); 3791 std::string floatStr(Buffer.data(), Buffer.size()); 3792 result->EvalType = CXEval_Float; 3793 bool ignored; 3794 llvm::APFloat apFloat = ER.Val.getFloat(); 3795 apFloat.convert(llvm::APFloat::IEEEdouble(), 3796 llvm::APFloat::rmNearestTiesToEven, &ignored); 3797 result->EvalData.floatVal = apFloat.convertToDouble(); 3798 return result.release(); 3799 } 3800 3801 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) { 3802 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr); 3803 auto *subExpr = I->getSubExprAsWritten(); 3804 if (subExpr->getStmtClass() == Stmt::StringLiteralClass || 3805 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) { 3806 const StringLiteral *StrE = nullptr; 3807 const ObjCStringLiteral *ObjCExpr; 3808 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr); 3809 3810 if (ObjCExpr) { 3811 StrE = ObjCExpr->getString(); 3812 result->EvalType = CXEval_ObjCStrLiteral; 3813 } else { 3814 StrE = cast<StringLiteral>(I->getSubExprAsWritten()); 3815 result->EvalType = CXEval_StrLiteral; 3816 } 3817 3818 std::string strRef(StrE->getString().str()); 3819 result->EvalData.stringVal = new char[strRef.size() + 1]; 3820 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), 3821 strRef.size()); 3822 result->EvalData.stringVal[strRef.size()] = '\0'; 3823 return result.release(); 3824 } 3825 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass || 3826 expr->getStmtClass() == Stmt::StringLiteralClass) { 3827 const StringLiteral *StrE = nullptr; 3828 const ObjCStringLiteral *ObjCExpr; 3829 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr); 3830 3831 if (ObjCExpr) { 3832 StrE = ObjCExpr->getString(); 3833 result->EvalType = CXEval_ObjCStrLiteral; 3834 } else { 3835 StrE = cast<StringLiteral>(expr); 3836 result->EvalType = CXEval_StrLiteral; 3837 } 3838 3839 std::string strRef(StrE->getString().str()); 3840 result->EvalData.stringVal = new char[strRef.size() + 1]; 3841 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); 3842 result->EvalData.stringVal[strRef.size()] = '\0'; 3843 return result.release(); 3844 } 3845 3846 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) { 3847 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr); 3848 3849 rettype = CC->getType(); 3850 if (rettype.getAsString() == "CFStringRef" && 3851 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) { 3852 3853 callExpr = static_cast<CallExpr *>(CC->getSubExpr()); 3854 StringLiteral *S = getCFSTR_value(callExpr); 3855 if (S) { 3856 std::string strLiteral(S->getString().str()); 3857 result->EvalType = CXEval_CFStr; 3858 3859 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 3860 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 3861 strLiteral.size()); 3862 result->EvalData.stringVal[strLiteral.size()] = '\0'; 3863 return result.release(); 3864 } 3865 } 3866 3867 } else if (expr->getStmtClass() == Stmt::CallExprClass) { 3868 callExpr = static_cast<CallExpr *>(expr); 3869 rettype = callExpr->getCallReturnType(ctx); 3870 3871 if (rettype->isVectorType() || callExpr->getNumArgs() > 1) 3872 return nullptr; 3873 3874 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) { 3875 if (callExpr->getNumArgs() == 1 && 3876 !callExpr->getArg(0)->getType()->isIntegralType(ctx)) 3877 return nullptr; 3878 } else if (rettype.getAsString() == "CFStringRef") { 3879 3880 StringLiteral *S = getCFSTR_value(callExpr); 3881 if (S) { 3882 std::string strLiteral(S->getString().str()); 3883 result->EvalType = CXEval_CFStr; 3884 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 3885 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 3886 strLiteral.size()); 3887 result->EvalData.stringVal[strLiteral.size()] = '\0'; 3888 return result.release(); 3889 } 3890 } 3891 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) { 3892 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr); 3893 ValueDecl *V = D->getDecl(); 3894 if (V->getKind() == Decl::Function) { 3895 std::string strName = V->getNameAsString(); 3896 result->EvalType = CXEval_Other; 3897 result->EvalData.stringVal = new char[strName.size() + 1]; 3898 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size()); 3899 result->EvalData.stringVal[strName.size()] = '\0'; 3900 return result.release(); 3901 } 3902 } 3903 3904 return nullptr; 3905 } 3906 3907 CXEvalResult clang_Cursor_Evaluate(CXCursor C) { 3908 const Decl *D = getCursorDecl(C); 3909 if (D) { 3910 const Expr *expr = nullptr; 3911 if (auto *Var = dyn_cast<VarDecl>(D)) { 3912 expr = Var->getInit(); 3913 } else if (auto *Field = dyn_cast<FieldDecl>(D)) { 3914 expr = Field->getInClassInitializer(); 3915 } 3916 if (expr) 3917 return const_cast<CXEvalResult>(reinterpret_cast<const void *>( 3918 evaluateExpr(const_cast<Expr *>(expr), C))); 3919 return nullptr; 3920 } 3921 3922 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C)); 3923 if (compoundStmt) { 3924 Expr *expr = nullptr; 3925 for (auto *bodyIterator : compoundStmt->body()) { 3926 if ((expr = dyn_cast<Expr>(bodyIterator))) { 3927 break; 3928 } 3929 } 3930 if (expr) 3931 return const_cast<CXEvalResult>( 3932 reinterpret_cast<const void *>(evaluateExpr(expr, C))); 3933 } 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 } 5482 5483 llvm_unreachable("Unhandled CXCursorKind"); 5484 } 5485 5486 struct GetCursorData { 5487 SourceLocation TokenBeginLoc; 5488 bool PointsAtMacroArgExpansion; 5489 bool VisitedObjCPropertyImplDecl; 5490 SourceLocation VisitedDeclaratorDeclStartLoc; 5491 CXCursor &BestCursor; 5492 5493 GetCursorData(SourceManager &SM, 5494 SourceLocation tokenBegin, CXCursor &outputCursor) 5495 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 5496 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 5497 VisitedObjCPropertyImplDecl = false; 5498 } 5499 }; 5500 5501 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 5502 CXCursor parent, 5503 CXClientData client_data) { 5504 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 5505 CXCursor *BestCursor = &Data->BestCursor; 5506 5507 // If we point inside a macro argument we should provide info of what the 5508 // token is so use the actual cursor, don't replace it with a macro expansion 5509 // cursor. 5510 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 5511 return CXChildVisit_Recurse; 5512 5513 if (clang_isDeclaration(cursor.kind)) { 5514 // Avoid having the implicit methods override the property decls. 5515 if (const ObjCMethodDecl *MD 5516 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5517 if (MD->isImplicit()) 5518 return CXChildVisit_Break; 5519 5520 } else if (const ObjCInterfaceDecl *ID 5521 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 5522 // Check that when we have multiple @class references in the same line, 5523 // that later ones do not override the previous ones. 5524 // If we have: 5525 // @class Foo, Bar; 5526 // source ranges for both start at '@', so 'Bar' will end up overriding 5527 // 'Foo' even though the cursor location was at 'Foo'. 5528 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 5529 BestCursor->kind == CXCursor_ObjCClassRef) 5530 if (const ObjCInterfaceDecl *PrevID 5531 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){ 5532 if (PrevID != ID && 5533 !PrevID->isThisDeclarationADefinition() && 5534 !ID->isThisDeclarationADefinition()) 5535 return CXChildVisit_Break; 5536 } 5537 5538 } else if (const DeclaratorDecl *DD 5539 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 5540 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 5541 // Check that when we have multiple declarators in the same line, 5542 // that later ones do not override the previous ones. 5543 // If we have: 5544 // int Foo, Bar; 5545 // source ranges for both start at 'int', so 'Bar' will end up overriding 5546 // 'Foo' even though the cursor location was at 'Foo'. 5547 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 5548 return CXChildVisit_Break; 5549 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 5550 5551 } else if (const ObjCPropertyImplDecl *PropImp 5552 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) { 5553 (void)PropImp; 5554 // Check that when we have multiple @synthesize in the same line, 5555 // that later ones do not override the previous ones. 5556 // If we have: 5557 // @synthesize Foo, Bar; 5558 // source ranges for both start at '@', so 'Bar' will end up overriding 5559 // 'Foo' even though the cursor location was at 'Foo'. 5560 if (Data->VisitedObjCPropertyImplDecl) 5561 return CXChildVisit_Break; 5562 Data->VisitedObjCPropertyImplDecl = true; 5563 } 5564 } 5565 5566 if (clang_isExpression(cursor.kind) && 5567 clang_isDeclaration(BestCursor->kind)) { 5568 if (const Decl *D = getCursorDecl(*BestCursor)) { 5569 // Avoid having the cursor of an expression replace the declaration cursor 5570 // when the expression source range overlaps the declaration range. 5571 // This can happen for C++ constructor expressions whose range generally 5572 // include the variable declaration, e.g.: 5573 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. 5574 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 5575 D->getLocation() == Data->TokenBeginLoc) 5576 return CXChildVisit_Break; 5577 } 5578 } 5579 5580 // If our current best cursor is the construction of a temporary object, 5581 // don't replace that cursor with a type reference, because we want 5582 // clang_getCursor() to point at the constructor. 5583 if (clang_isExpression(BestCursor->kind) && 5584 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 5585 cursor.kind == CXCursor_TypeRef) { 5586 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 5587 // as having the actual point on the type reference. 5588 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 5589 return CXChildVisit_Recurse; 5590 } 5591 5592 // If we already have an Objective-C superclass reference, don't 5593 // update it further. 5594 if (BestCursor->kind == CXCursor_ObjCSuperClassRef) 5595 return CXChildVisit_Break; 5596 5597 *BestCursor = cursor; 5598 return CXChildVisit_Recurse; 5599 } 5600 5601 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 5602 if (isNotUsableTU(TU)) { 5603 LOG_BAD_TU(TU); 5604 return clang_getNullCursor(); 5605 } 5606 5607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5608 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5609 5610 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 5611 CXCursor Result = cxcursor::getCursor(TU, SLoc); 5612 5613 LOG_FUNC_SECTION { 5614 CXFile SearchFile; 5615 unsigned SearchLine, SearchColumn; 5616 CXFile ResultFile; 5617 unsigned ResultLine, ResultColumn; 5618 CXString SearchFileName, ResultFileName, KindSpelling, USR; 5619 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 5620 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 5621 5622 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 5623 nullptr); 5624 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, 5625 &ResultColumn, nullptr); 5626 SearchFileName = clang_getFileName(SearchFile); 5627 ResultFileName = clang_getFileName(ResultFile); 5628 KindSpelling = clang_getCursorKindSpelling(Result.kind); 5629 USR = clang_getCursorUSR(Result); 5630 *Log << llvm::format("(%s:%d:%d) = %s", 5631 clang_getCString(SearchFileName), SearchLine, SearchColumn, 5632 clang_getCString(KindSpelling)) 5633 << llvm::format("(%s:%d:%d):%s%s", 5634 clang_getCString(ResultFileName), ResultLine, ResultColumn, 5635 clang_getCString(USR), IsDef); 5636 clang_disposeString(SearchFileName); 5637 clang_disposeString(ResultFileName); 5638 clang_disposeString(KindSpelling); 5639 clang_disposeString(USR); 5640 5641 CXCursor Definition = clang_getCursorDefinition(Result); 5642 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 5643 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 5644 CXString DefinitionKindSpelling 5645 = clang_getCursorKindSpelling(Definition.kind); 5646 CXFile DefinitionFile; 5647 unsigned DefinitionLine, DefinitionColumn; 5648 clang_getFileLocation(DefinitionLoc, &DefinitionFile, 5649 &DefinitionLine, &DefinitionColumn, nullptr); 5650 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 5651 *Log << llvm::format(" -> %s(%s:%d:%d)", 5652 clang_getCString(DefinitionKindSpelling), 5653 clang_getCString(DefinitionFileName), 5654 DefinitionLine, DefinitionColumn); 5655 clang_disposeString(DefinitionFileName); 5656 clang_disposeString(DefinitionKindSpelling); 5657 } 5658 } 5659 5660 return Result; 5661 } 5662 5663 CXCursor clang_getNullCursor(void) { 5664 return MakeCXCursorInvalid(CXCursor_InvalidFile); 5665 } 5666 5667 unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 5668 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we 5669 // can't set consistently. For example, when visiting a DeclStmt we will set 5670 // it but we don't set it on the result of clang_getCursorDefinition for 5671 // a reference of the same declaration. 5672 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works 5673 // when visiting a DeclStmt currently, the AST should be enhanced to be able 5674 // to provide that kind of info. 5675 if (clang_isDeclaration(X.kind)) 5676 X.data[1] = nullptr; 5677 if (clang_isDeclaration(Y.kind)) 5678 Y.data[1] = nullptr; 5679 5680 return X == Y; 5681 } 5682 5683 unsigned clang_hashCursor(CXCursor C) { 5684 unsigned Index = 0; 5685 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 5686 Index = 1; 5687 5688 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue( 5689 std::make_pair(C.kind, C.data[Index])); 5690 } 5691 5692 unsigned clang_isInvalid(enum CXCursorKind K) { 5693 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 5694 } 5695 5696 unsigned clang_isDeclaration(enum CXCursorKind K) { 5697 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 5698 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 5699 } 5700 5701 unsigned clang_isInvalidDeclaration(CXCursor C) { 5702 if (clang_isDeclaration(C.kind)) { 5703 if (const Decl *D = getCursorDecl(C)) 5704 return D->isInvalidDecl(); 5705 } 5706 5707 return 0; 5708 } 5709 5710 unsigned clang_isReference(enum CXCursorKind K) { 5711 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 5712 } 5713 5714 unsigned clang_isExpression(enum CXCursorKind K) { 5715 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 5716 } 5717 5718 unsigned clang_isStatement(enum CXCursorKind K) { 5719 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 5720 } 5721 5722 unsigned clang_isAttribute(enum CXCursorKind K) { 5723 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 5724 } 5725 5726 unsigned clang_isTranslationUnit(enum CXCursorKind K) { 5727 return K == CXCursor_TranslationUnit; 5728 } 5729 5730 unsigned clang_isPreprocessing(enum CXCursorKind K) { 5731 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 5732 } 5733 5734 unsigned clang_isUnexposed(enum CXCursorKind K) { 5735 switch (K) { 5736 case CXCursor_UnexposedDecl: 5737 case CXCursor_UnexposedExpr: 5738 case CXCursor_UnexposedStmt: 5739 case CXCursor_UnexposedAttr: 5740 return true; 5741 default: 5742 return false; 5743 } 5744 } 5745 5746 CXCursorKind clang_getCursorKind(CXCursor C) { 5747 return C.kind; 5748 } 5749 5750 CXSourceLocation clang_getCursorLocation(CXCursor C) { 5751 if (clang_isReference(C.kind)) { 5752 switch (C.kind) { 5753 case CXCursor_ObjCSuperClassRef: { 5754 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 5755 = getCursorObjCSuperClassRef(C); 5756 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5757 } 5758 5759 case CXCursor_ObjCProtocolRef: { 5760 std::pair<const ObjCProtocolDecl *, SourceLocation> P 5761 = getCursorObjCProtocolRef(C); 5762 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5763 } 5764 5765 case CXCursor_ObjCClassRef: { 5766 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 5767 = getCursorObjCClassRef(C); 5768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5769 } 5770 5771 case CXCursor_TypeRef: { 5772 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 5773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5774 } 5775 5776 case CXCursor_TemplateRef: { 5777 std::pair<const TemplateDecl *, SourceLocation> P = 5778 getCursorTemplateRef(C); 5779 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5780 } 5781 5782 case CXCursor_NamespaceRef: { 5783 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 5784 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5785 } 5786 5787 case CXCursor_MemberRef: { 5788 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 5789 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5790 } 5791 5792 case CXCursor_VariableRef: { 5793 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); 5794 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5795 } 5796 5797 case CXCursor_CXXBaseSpecifier: { 5798 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 5799 if (!BaseSpec) 5800 return clang_getNullLocation(); 5801 5802 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 5803 return cxloc::translateSourceLocation(getCursorContext(C), 5804 TSInfo->getTypeLoc().getBeginLoc()); 5805 5806 return cxloc::translateSourceLocation(getCursorContext(C), 5807 BaseSpec->getBeginLoc()); 5808 } 5809 5810 case CXCursor_LabelRef: { 5811 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 5812 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 5813 } 5814 5815 case CXCursor_OverloadedDeclRef: 5816 return cxloc::translateSourceLocation(getCursorContext(C), 5817 getCursorOverloadedDeclRef(C).second); 5818 5819 default: 5820 // FIXME: Need a way to enumerate all non-reference cases. 5821 llvm_unreachable("Missed a reference kind"); 5822 } 5823 } 5824 5825 if (clang_isExpression(C.kind)) 5826 return cxloc::translateSourceLocation(getCursorContext(C), 5827 getLocationFromExpr(getCursorExpr(C))); 5828 5829 if (clang_isStatement(C.kind)) 5830 return cxloc::translateSourceLocation(getCursorContext(C), 5831 getCursorStmt(C)->getBeginLoc()); 5832 5833 if (C.kind == CXCursor_PreprocessingDirective) { 5834 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 5835 return cxloc::translateSourceLocation(getCursorContext(C), L); 5836 } 5837 5838 if (C.kind == CXCursor_MacroExpansion) { 5839 SourceLocation L 5840 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); 5841 return cxloc::translateSourceLocation(getCursorContext(C), L); 5842 } 5843 5844 if (C.kind == CXCursor_MacroDefinition) { 5845 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 5846 return cxloc::translateSourceLocation(getCursorContext(C), L); 5847 } 5848 5849 if (C.kind == CXCursor_InclusionDirective) { 5850 SourceLocation L 5851 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 5852 return cxloc::translateSourceLocation(getCursorContext(C), L); 5853 } 5854 5855 if (clang_isAttribute(C.kind)) { 5856 SourceLocation L 5857 = cxcursor::getCursorAttr(C)->getLocation(); 5858 return cxloc::translateSourceLocation(getCursorContext(C), L); 5859 } 5860 5861 if (!clang_isDeclaration(C.kind)) 5862 return clang_getNullLocation(); 5863 5864 const Decl *D = getCursorDecl(C); 5865 if (!D) 5866 return clang_getNullLocation(); 5867 5868 SourceLocation Loc = D->getLocation(); 5869 // FIXME: Multiple variables declared in a single declaration 5870 // currently lack the information needed to correctly determine their 5871 // ranges when accounting for the type-specifier. We use context 5872 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 5873 // and if so, whether it is the first decl. 5874 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5875 if (!cxcursor::isFirstInDeclGroup(C)) 5876 Loc = VD->getLocation(); 5877 } 5878 5879 // For ObjC methods, give the start location of the method name. 5880 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 5881 Loc = MD->getSelectorStartLoc(); 5882 5883 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 5884 } 5885 5886 } // end extern "C" 5887 5888 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 5889 assert(TU); 5890 5891 // Guard against an invalid SourceLocation, or we may assert in one 5892 // of the following calls. 5893 if (SLoc.isInvalid()) 5894 return clang_getNullCursor(); 5895 5896 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5897 5898 // Translate the given source location to make it point at the beginning of 5899 // the token under the cursor. 5900 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 5901 CXXUnit->getASTContext().getLangOpts()); 5902 5903 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 5904 if (SLoc.isValid()) { 5905 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 5906 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 5907 /*VisitPreprocessorLast=*/true, 5908 /*VisitIncludedEntities=*/false, 5909 SourceLocation(SLoc)); 5910 CursorVis.visitFileRegion(); 5911 } 5912 5913 return Result; 5914 } 5915 5916 static SourceRange getRawCursorExtent(CXCursor C) { 5917 if (clang_isReference(C.kind)) { 5918 switch (C.kind) { 5919 case CXCursor_ObjCSuperClassRef: 5920 return getCursorObjCSuperClassRef(C).second; 5921 5922 case CXCursor_ObjCProtocolRef: 5923 return getCursorObjCProtocolRef(C).second; 5924 5925 case CXCursor_ObjCClassRef: 5926 return getCursorObjCClassRef(C).second; 5927 5928 case CXCursor_TypeRef: 5929 return getCursorTypeRef(C).second; 5930 5931 case CXCursor_TemplateRef: 5932 return getCursorTemplateRef(C).second; 5933 5934 case CXCursor_NamespaceRef: 5935 return getCursorNamespaceRef(C).second; 5936 5937 case CXCursor_MemberRef: 5938 return getCursorMemberRef(C).second; 5939 5940 case CXCursor_CXXBaseSpecifier: 5941 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 5942 5943 case CXCursor_LabelRef: 5944 return getCursorLabelRef(C).second; 5945 5946 case CXCursor_OverloadedDeclRef: 5947 return getCursorOverloadedDeclRef(C).second; 5948 5949 case CXCursor_VariableRef: 5950 return getCursorVariableRef(C).second; 5951 5952 default: 5953 // FIXME: Need a way to enumerate all non-reference cases. 5954 llvm_unreachable("Missed a reference kind"); 5955 } 5956 } 5957 5958 if (clang_isExpression(C.kind)) 5959 return getCursorExpr(C)->getSourceRange(); 5960 5961 if (clang_isStatement(C.kind)) 5962 return getCursorStmt(C)->getSourceRange(); 5963 5964 if (clang_isAttribute(C.kind)) 5965 return getCursorAttr(C)->getRange(); 5966 5967 if (C.kind == CXCursor_PreprocessingDirective) 5968 return cxcursor::getCursorPreprocessingDirective(C); 5969 5970 if (C.kind == CXCursor_MacroExpansion) { 5971 ASTUnit *TU = getCursorASTUnit(C); 5972 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); 5973 return TU->mapRangeFromPreamble(Range); 5974 } 5975 5976 if (C.kind == CXCursor_MacroDefinition) { 5977 ASTUnit *TU = getCursorASTUnit(C); 5978 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 5979 return TU->mapRangeFromPreamble(Range); 5980 } 5981 5982 if (C.kind == CXCursor_InclusionDirective) { 5983 ASTUnit *TU = getCursorASTUnit(C); 5984 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 5985 return TU->mapRangeFromPreamble(Range); 5986 } 5987 5988 if (C.kind == CXCursor_TranslationUnit) { 5989 ASTUnit *TU = getCursorASTUnit(C); 5990 FileID MainID = TU->getSourceManager().getMainFileID(); 5991 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 5992 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 5993 return SourceRange(Start, End); 5994 } 5995 5996 if (clang_isDeclaration(C.kind)) { 5997 const Decl *D = cxcursor::getCursorDecl(C); 5998 if (!D) 5999 return SourceRange(); 6000 6001 SourceRange R = D->getSourceRange(); 6002 // FIXME: Multiple variables declared in a single declaration 6003 // currently lack the information needed to correctly determine their 6004 // ranges when accounting for the type-specifier. We use context 6005 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6006 // and if so, whether it is the first decl. 6007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6008 if (!cxcursor::isFirstInDeclGroup(C)) 6009 R.setBegin(VD->getLocation()); 6010 } 6011 return R; 6012 } 6013 return SourceRange(); 6014 } 6015 6016 /// Retrieves the "raw" cursor extent, which is then extended to include 6017 /// the decl-specifier-seq for declarations. 6018 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 6019 if (clang_isDeclaration(C.kind)) { 6020 const Decl *D = cxcursor::getCursorDecl(C); 6021 if (!D) 6022 return SourceRange(); 6023 6024 SourceRange R = D->getSourceRange(); 6025 6026 // Adjust the start of the location for declarations preceded by 6027 // declaration specifiers. 6028 SourceLocation StartLoc; 6029 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6030 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 6031 StartLoc = TI->getTypeLoc().getBeginLoc(); 6032 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 6033 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 6034 StartLoc = TI->getTypeLoc().getBeginLoc(); 6035 } 6036 6037 if (StartLoc.isValid() && R.getBegin().isValid() && 6038 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 6039 R.setBegin(StartLoc); 6040 6041 // FIXME: Multiple variables declared in a single declaration 6042 // currently lack the information needed to correctly determine their 6043 // ranges when accounting for the type-specifier. We use context 6044 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6045 // and if so, whether it is the first decl. 6046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6047 if (!cxcursor::isFirstInDeclGroup(C)) 6048 R.setBegin(VD->getLocation()); 6049 } 6050 6051 return R; 6052 } 6053 6054 return getRawCursorExtent(C); 6055 } 6056 6057 CXSourceRange clang_getCursorExtent(CXCursor C) { 6058 SourceRange R = getRawCursorExtent(C); 6059 if (R.isInvalid()) 6060 return clang_getNullRange(); 6061 6062 return cxloc::translateSourceRange(getCursorContext(C), R); 6063 } 6064 6065 CXCursor clang_getCursorReferenced(CXCursor C) { 6066 if (clang_isInvalid(C.kind)) 6067 return clang_getNullCursor(); 6068 6069 CXTranslationUnit tu = getCursorTU(C); 6070 if (clang_isDeclaration(C.kind)) { 6071 const Decl *D = getCursorDecl(C); 6072 if (!D) 6073 return clang_getNullCursor(); 6074 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6075 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 6076 if (const ObjCPropertyImplDecl *PropImpl = 6077 dyn_cast<ObjCPropertyImplDecl>(D)) 6078 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 6079 return MakeCXCursor(Property, tu); 6080 6081 return C; 6082 } 6083 6084 if (clang_isExpression(C.kind)) { 6085 const Expr *E = getCursorExpr(C); 6086 const Decl *D = getDeclFromExpr(E); 6087 if (D) { 6088 CXCursor declCursor = MakeCXCursor(D, tu); 6089 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 6090 declCursor); 6091 return declCursor; 6092 } 6093 6094 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 6095 return MakeCursorOverloadedDeclRef(Ovl, tu); 6096 6097 return clang_getNullCursor(); 6098 } 6099 6100 if (clang_isStatement(C.kind)) { 6101 const Stmt *S = getCursorStmt(C); 6102 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 6103 if (LabelDecl *label = Goto->getLabel()) 6104 if (LabelStmt *labelS = label->getStmt()) 6105 return MakeCXCursor(labelS, getCursorDecl(C), tu); 6106 6107 return clang_getNullCursor(); 6108 } 6109 6110 if (C.kind == CXCursor_MacroExpansion) { 6111 if (const MacroDefinitionRecord *Def = 6112 getCursorMacroExpansion(C).getDefinition()) 6113 return MakeMacroDefinitionCursor(Def, tu); 6114 } 6115 6116 if (!clang_isReference(C.kind)) 6117 return clang_getNullCursor(); 6118 6119 switch (C.kind) { 6120 case CXCursor_ObjCSuperClassRef: 6121 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 6122 6123 case CXCursor_ObjCProtocolRef: { 6124 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 6125 if (const ObjCProtocolDecl *Def = Prot->getDefinition()) 6126 return MakeCXCursor(Def, tu); 6127 6128 return MakeCXCursor(Prot, tu); 6129 } 6130 6131 case CXCursor_ObjCClassRef: { 6132 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 6133 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6134 return MakeCXCursor(Def, tu); 6135 6136 return MakeCXCursor(Class, tu); 6137 } 6138 6139 case CXCursor_TypeRef: 6140 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 6141 6142 case CXCursor_TemplateRef: 6143 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 6144 6145 case CXCursor_NamespaceRef: 6146 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 6147 6148 case CXCursor_MemberRef: 6149 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 6150 6151 case CXCursor_CXXBaseSpecifier: { 6152 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 6153 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 6154 tu )); 6155 } 6156 6157 case CXCursor_LabelRef: 6158 // FIXME: We end up faking the "parent" declaration here because we 6159 // don't want to make CXCursor larger. 6160 return MakeCXCursor(getCursorLabelRef(C).first, 6161 cxtu::getASTUnit(tu)->getASTContext() 6162 .getTranslationUnitDecl(), 6163 tu); 6164 6165 case CXCursor_OverloadedDeclRef: 6166 return C; 6167 6168 case CXCursor_VariableRef: 6169 return MakeCXCursor(getCursorVariableRef(C).first, tu); 6170 6171 default: 6172 // We would prefer to enumerate all non-reference cursor kinds here. 6173 llvm_unreachable("Unhandled reference cursor kind"); 6174 } 6175 } 6176 6177 CXCursor clang_getCursorDefinition(CXCursor C) { 6178 if (clang_isInvalid(C.kind)) 6179 return clang_getNullCursor(); 6180 6181 CXTranslationUnit TU = getCursorTU(C); 6182 6183 bool WasReference = false; 6184 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 6185 C = clang_getCursorReferenced(C); 6186 WasReference = true; 6187 } 6188 6189 if (C.kind == CXCursor_MacroExpansion) 6190 return clang_getCursorReferenced(C); 6191 6192 if (!clang_isDeclaration(C.kind)) 6193 return clang_getNullCursor(); 6194 6195 const Decl *D = getCursorDecl(C); 6196 if (!D) 6197 return clang_getNullCursor(); 6198 6199 switch (D->getKind()) { 6200 // Declaration kinds that don't really separate the notions of 6201 // declaration and definition. 6202 case Decl::Namespace: 6203 case Decl::Typedef: 6204 case Decl::TypeAlias: 6205 case Decl::TypeAliasTemplate: 6206 case Decl::TemplateTypeParm: 6207 case Decl::EnumConstant: 6208 case Decl::Field: 6209 case Decl::Binding: 6210 case Decl::MSProperty: 6211 case Decl::IndirectField: 6212 case Decl::ObjCIvar: 6213 case Decl::ObjCAtDefsField: 6214 case Decl::ImplicitParam: 6215 case Decl::ParmVar: 6216 case Decl::NonTypeTemplateParm: 6217 case Decl::TemplateTemplateParm: 6218 case Decl::ObjCCategoryImpl: 6219 case Decl::ObjCImplementation: 6220 case Decl::AccessSpec: 6221 case Decl::LinkageSpec: 6222 case Decl::Export: 6223 case Decl::ObjCPropertyImpl: 6224 case Decl::FileScopeAsm: 6225 case Decl::StaticAssert: 6226 case Decl::Block: 6227 case Decl::Captured: 6228 case Decl::OMPCapturedExpr: 6229 case Decl::Label: // FIXME: Is this right?? 6230 case Decl::ClassScopeFunctionSpecialization: 6231 case Decl::CXXDeductionGuide: 6232 case Decl::Import: 6233 case Decl::OMPThreadPrivate: 6234 case Decl::OMPDeclareReduction: 6235 case Decl::OMPRequires: 6236 case Decl::ObjCTypeParam: 6237 case Decl::BuiltinTemplate: 6238 case Decl::PragmaComment: 6239 case Decl::PragmaDetectMismatch: 6240 case Decl::UsingPack: 6241 return C; 6242 6243 // Declaration kinds that don't make any sense here, but are 6244 // nonetheless harmless. 6245 case Decl::Empty: 6246 case Decl::TranslationUnit: 6247 case Decl::ExternCContext: 6248 break; 6249 6250 // Declaration kinds for which the definition is not resolvable. 6251 case Decl::UnresolvedUsingTypename: 6252 case Decl::UnresolvedUsingValue: 6253 break; 6254 6255 case Decl::UsingDirective: 6256 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 6257 TU); 6258 6259 case Decl::NamespaceAlias: 6260 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 6261 6262 case Decl::Enum: 6263 case Decl::Record: 6264 case Decl::CXXRecord: 6265 case Decl::ClassTemplateSpecialization: 6266 case Decl::ClassTemplatePartialSpecialization: 6267 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 6268 return MakeCXCursor(Def, TU); 6269 return clang_getNullCursor(); 6270 6271 case Decl::Function: 6272 case Decl::CXXMethod: 6273 case Decl::CXXConstructor: 6274 case Decl::CXXDestructor: 6275 case Decl::CXXConversion: { 6276 const FunctionDecl *Def = nullptr; 6277 if (cast<FunctionDecl>(D)->getBody(Def)) 6278 return MakeCXCursor(Def, TU); 6279 return clang_getNullCursor(); 6280 } 6281 6282 case Decl::Var: 6283 case Decl::VarTemplateSpecialization: 6284 case Decl::VarTemplatePartialSpecialization: 6285 case Decl::Decomposition: { 6286 // Ask the variable if it has a definition. 6287 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 6288 return MakeCXCursor(Def, TU); 6289 return clang_getNullCursor(); 6290 } 6291 6292 case Decl::FunctionTemplate: { 6293 const FunctionDecl *Def = nullptr; 6294 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 6295 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 6296 return clang_getNullCursor(); 6297 } 6298 6299 case Decl::ClassTemplate: { 6300 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 6301 ->getDefinition()) 6302 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 6303 TU); 6304 return clang_getNullCursor(); 6305 } 6306 6307 case Decl::VarTemplate: { 6308 if (VarDecl *Def = 6309 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 6310 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU); 6311 return clang_getNullCursor(); 6312 } 6313 6314 case Decl::Using: 6315 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 6316 D->getLocation(), TU); 6317 6318 case Decl::UsingShadow: 6319 case Decl::ConstructorUsingShadow: 6320 return clang_getCursorDefinition( 6321 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 6322 TU)); 6323 6324 case Decl::ObjCMethod: { 6325 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 6326 if (Method->isThisDeclarationADefinition()) 6327 return C; 6328 6329 // Dig out the method definition in the associated 6330 // @implementation, if we have it. 6331 // FIXME: The ASTs should make finding the definition easier. 6332 if (const ObjCInterfaceDecl *Class 6333 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 6334 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 6335 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 6336 Method->isInstanceMethod())) 6337 if (Def->isThisDeclarationADefinition()) 6338 return MakeCXCursor(Def, TU); 6339 6340 return clang_getNullCursor(); 6341 } 6342 6343 case Decl::ObjCCategory: 6344 if (ObjCCategoryImplDecl *Impl 6345 = cast<ObjCCategoryDecl>(D)->getImplementation()) 6346 return MakeCXCursor(Impl, TU); 6347 return clang_getNullCursor(); 6348 6349 case Decl::ObjCProtocol: 6350 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition()) 6351 return MakeCXCursor(Def, TU); 6352 return clang_getNullCursor(); 6353 6354 case Decl::ObjCInterface: { 6355 // There are two notions of a "definition" for an Objective-C 6356 // class: the interface and its implementation. When we resolved a 6357 // reference to an Objective-C class, produce the @interface as 6358 // the definition; when we were provided with the interface, 6359 // produce the @implementation as the definition. 6360 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 6361 if (WasReference) { 6362 if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) 6363 return MakeCXCursor(Def, TU); 6364 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6365 return MakeCXCursor(Impl, TU); 6366 return clang_getNullCursor(); 6367 } 6368 6369 case Decl::ObjCProperty: 6370 // FIXME: We don't really know where to find the 6371 // ObjCPropertyImplDecls that implement this property. 6372 return clang_getNullCursor(); 6373 6374 case Decl::ObjCCompatibleAlias: 6375 if (const ObjCInterfaceDecl *Class 6376 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 6377 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6378 return MakeCXCursor(Def, TU); 6379 6380 return clang_getNullCursor(); 6381 6382 case Decl::Friend: 6383 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 6384 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6385 return clang_getNullCursor(); 6386 6387 case Decl::FriendTemplate: 6388 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 6389 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6390 return clang_getNullCursor(); 6391 } 6392 6393 return clang_getNullCursor(); 6394 } 6395 6396 unsigned clang_isCursorDefinition(CXCursor C) { 6397 if (!clang_isDeclaration(C.kind)) 6398 return 0; 6399 6400 return clang_getCursorDefinition(C) == C; 6401 } 6402 6403 CXCursor clang_getCanonicalCursor(CXCursor C) { 6404 if (!clang_isDeclaration(C.kind)) 6405 return C; 6406 6407 if (const Decl *D = getCursorDecl(C)) { 6408 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) 6409 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 6410 return MakeCXCursor(CatD, getCursorTU(C)); 6411 6412 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 6413 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 6414 return MakeCXCursor(IFD, getCursorTU(C)); 6415 6416 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 6417 } 6418 6419 return C; 6420 } 6421 6422 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 6423 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 6424 } 6425 6426 unsigned clang_getNumOverloadedDecls(CXCursor C) { 6427 if (C.kind != CXCursor_OverloadedDeclRef) 6428 return 0; 6429 6430 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 6431 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6432 return E->getNumDecls(); 6433 6434 if (OverloadedTemplateStorage *S 6435 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 6436 return S->size(); 6437 6438 const Decl *D = Storage.get<const Decl *>(); 6439 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6440 return Using->shadow_size(); 6441 6442 return 0; 6443 } 6444 6445 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 6446 if (cursor.kind != CXCursor_OverloadedDeclRef) 6447 return clang_getNullCursor(); 6448 6449 if (index >= clang_getNumOverloadedDecls(cursor)) 6450 return clang_getNullCursor(); 6451 6452 CXTranslationUnit TU = getCursorTU(cursor); 6453 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 6454 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6455 return MakeCXCursor(E->decls_begin()[index], TU); 6456 6457 if (OverloadedTemplateStorage *S 6458 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 6459 return MakeCXCursor(S->begin()[index], TU); 6460 6461 const Decl *D = Storage.get<const Decl *>(); 6462 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 6463 // FIXME: This is, unfortunately, linear time. 6464 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 6465 std::advance(Pos, index); 6466 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 6467 } 6468 6469 return clang_getNullCursor(); 6470 } 6471 6472 void clang_getDefinitionSpellingAndExtent(CXCursor C, 6473 const char **startBuf, 6474 const char **endBuf, 6475 unsigned *startLine, 6476 unsigned *startColumn, 6477 unsigned *endLine, 6478 unsigned *endColumn) { 6479 assert(getCursorDecl(C) && "CXCursor has null decl"); 6480 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C)); 6481 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 6482 6483 SourceManager &SM = FD->getASTContext().getSourceManager(); 6484 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 6485 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 6486 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 6487 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 6488 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 6489 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 6490 } 6491 6492 6493 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 6494 unsigned PieceIndex) { 6495 RefNamePieces Pieces; 6496 6497 switch (C.kind) { 6498 case CXCursor_MemberRefExpr: 6499 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 6500 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 6501 E->getQualifierLoc().getSourceRange()); 6502 break; 6503 6504 case CXCursor_DeclRefExpr: 6505 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) { 6506 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc()); 6507 Pieces = 6508 buildPieces(NameFlags, false, E->getNameInfo(), 6509 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc); 6510 } 6511 break; 6512 6513 case CXCursor_CallExpr: 6514 if (const CXXOperatorCallExpr *OCE = 6515 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 6516 const Expr *Callee = OCE->getCallee(); 6517 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 6518 Callee = ICE->getSubExpr(); 6519 6520 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 6521 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 6522 DRE->getQualifierLoc().getSourceRange()); 6523 } 6524 break; 6525 6526 default: 6527 break; 6528 } 6529 6530 if (Pieces.empty()) { 6531 if (PieceIndex == 0) 6532 return clang_getCursorExtent(C); 6533 } else if (PieceIndex < Pieces.size()) { 6534 SourceRange R = Pieces[PieceIndex]; 6535 if (R.isValid()) 6536 return cxloc::translateSourceRange(getCursorContext(C), R); 6537 } 6538 6539 return clang_getNullRange(); 6540 } 6541 6542 void clang_enableStackTraces(void) { 6543 // FIXME: Provide an argv0 here so we can find llvm-symbolizer. 6544 llvm::sys::PrintStackTraceOnErrorSignal(StringRef()); 6545 } 6546 6547 void clang_executeOnThread(void (*fn)(void*), void *user_data, 6548 unsigned stack_size) { 6549 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 6550 } 6551 6552 //===----------------------------------------------------------------------===// 6553 // Token-based Operations. 6554 //===----------------------------------------------------------------------===// 6555 6556 /* CXToken layout: 6557 * int_data[0]: a CXTokenKind 6558 * int_data[1]: starting token location 6559 * int_data[2]: token length 6560 * int_data[3]: reserved 6561 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 6562 * otherwise unused. 6563 */ 6564 CXTokenKind clang_getTokenKind(CXToken CXTok) { 6565 return static_cast<CXTokenKind>(CXTok.int_data[0]); 6566 } 6567 6568 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 6569 switch (clang_getTokenKind(CXTok)) { 6570 case CXToken_Identifier: 6571 case CXToken_Keyword: 6572 // We know we have an IdentifierInfo*, so use that. 6573 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data) 6574 ->getNameStart()); 6575 6576 case CXToken_Literal: { 6577 // We have stashed the starting pointer in the ptr_data field. Use it. 6578 const char *Text = static_cast<const char *>(CXTok.ptr_data); 6579 return cxstring::createDup(StringRef(Text, CXTok.int_data[2])); 6580 } 6581 6582 case CXToken_Punctuation: 6583 case CXToken_Comment: 6584 break; 6585 } 6586 6587 if (isNotUsableTU(TU)) { 6588 LOG_BAD_TU(TU); 6589 return cxstring::createEmpty(); 6590 } 6591 6592 // We have to find the starting buffer pointer the hard way, by 6593 // deconstructing the source location. 6594 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6595 if (!CXXUnit) 6596 return cxstring::createEmpty(); 6597 6598 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 6599 std::pair<FileID, unsigned> LocInfo 6600 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 6601 bool Invalid = false; 6602 StringRef Buffer 6603 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 6604 if (Invalid) 6605 return cxstring::createEmpty(); 6606 6607 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 6608 } 6609 6610 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 6611 if (isNotUsableTU(TU)) { 6612 LOG_BAD_TU(TU); 6613 return clang_getNullLocation(); 6614 } 6615 6616 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6617 if (!CXXUnit) 6618 return clang_getNullLocation(); 6619 6620 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 6621 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6622 } 6623 6624 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 6625 if (isNotUsableTU(TU)) { 6626 LOG_BAD_TU(TU); 6627 return clang_getNullRange(); 6628 } 6629 6630 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6631 if (!CXXUnit) 6632 return clang_getNullRange(); 6633 6634 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 6635 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6636 } 6637 6638 static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 6639 SmallVectorImpl<CXToken> &CXTokens) { 6640 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 6641 std::pair<FileID, unsigned> BeginLocInfo 6642 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin()); 6643 std::pair<FileID, unsigned> EndLocInfo 6644 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd()); 6645 6646 // Cannot tokenize across files. 6647 if (BeginLocInfo.first != EndLocInfo.first) 6648 return; 6649 6650 // Create a lexer 6651 bool Invalid = false; 6652 StringRef Buffer 6653 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 6654 if (Invalid) 6655 return; 6656 6657 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 6658 CXXUnit->getASTContext().getLangOpts(), 6659 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 6660 Lex.SetCommentRetentionState(true); 6661 6662 // Lex tokens until we hit the end of the range. 6663 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 6664 Token Tok; 6665 bool previousWasAt = false; 6666 do { 6667 // Lex the next token 6668 Lex.LexFromRawLexer(Tok); 6669 if (Tok.is(tok::eof)) 6670 break; 6671 6672 // Initialize the CXToken. 6673 CXToken CXTok; 6674 6675 // - Common fields 6676 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 6677 CXTok.int_data[2] = Tok.getLength(); 6678 CXTok.int_data[3] = 0; 6679 6680 // - Kind-specific fields 6681 if (Tok.isLiteral()) { 6682 CXTok.int_data[0] = CXToken_Literal; 6683 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData()); 6684 } else if (Tok.is(tok::raw_identifier)) { 6685 // Lookup the identifier to determine whether we have a keyword. 6686 IdentifierInfo *II 6687 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 6688 6689 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 6690 CXTok.int_data[0] = CXToken_Keyword; 6691 } 6692 else { 6693 CXTok.int_data[0] = Tok.is(tok::identifier) 6694 ? CXToken_Identifier 6695 : CXToken_Keyword; 6696 } 6697 CXTok.ptr_data = II; 6698 } else if (Tok.is(tok::comment)) { 6699 CXTok.int_data[0] = CXToken_Comment; 6700 CXTok.ptr_data = nullptr; 6701 } else { 6702 CXTok.int_data[0] = CXToken_Punctuation; 6703 CXTok.ptr_data = nullptr; 6704 } 6705 CXTokens.push_back(CXTok); 6706 previousWasAt = Tok.is(tok::at); 6707 } while (Lex.getBufferLocation() < EffectiveBufferEnd); 6708 } 6709 6710 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) { 6711 LOG_FUNC_SECTION { 6712 *Log << TU << ' ' << Location; 6713 } 6714 6715 if (isNotUsableTU(TU)) { 6716 LOG_BAD_TU(TU); 6717 return NULL; 6718 } 6719 6720 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6721 if (!CXXUnit) 6722 return NULL; 6723 6724 SourceLocation Begin = cxloc::translateSourceLocation(Location); 6725 if (Begin.isInvalid()) 6726 return NULL; 6727 SourceManager &SM = CXXUnit->getSourceManager(); 6728 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin); 6729 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts()); 6730 6731 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second); 6732 6733 SmallVector<CXToken, 32> CXTokens; 6734 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens); 6735 6736 if (CXTokens.empty()) 6737 return NULL; 6738 6739 CXTokens.resize(1); 6740 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken))); 6741 6742 memmove(Token, CXTokens.data(), sizeof(CXToken)); 6743 return Token; 6744 } 6745 6746 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 6747 CXToken **Tokens, unsigned *NumTokens) { 6748 LOG_FUNC_SECTION { 6749 *Log << TU << ' ' << Range; 6750 } 6751 6752 if (Tokens) 6753 *Tokens = nullptr; 6754 if (NumTokens) 6755 *NumTokens = 0; 6756 6757 if (isNotUsableTU(TU)) { 6758 LOG_BAD_TU(TU); 6759 return; 6760 } 6761 6762 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6763 if (!CXXUnit || !Tokens || !NumTokens) 6764 return; 6765 6766 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 6767 6768 SourceRange R = cxloc::translateCXSourceRange(Range); 6769 if (R.isInvalid()) 6770 return; 6771 6772 SmallVector<CXToken, 32> CXTokens; 6773 getTokens(CXXUnit, R, CXTokens); 6774 6775 if (CXTokens.empty()) 6776 return; 6777 6778 *Tokens = static_cast<CXToken *>( 6779 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size())); 6780 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 6781 *NumTokens = CXTokens.size(); 6782 } 6783 6784 void clang_disposeTokens(CXTranslationUnit TU, 6785 CXToken *Tokens, unsigned NumTokens) { 6786 free(Tokens); 6787 } 6788 6789 //===----------------------------------------------------------------------===// 6790 // Token annotation APIs. 6791 //===----------------------------------------------------------------------===// 6792 6793 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 6794 CXCursor parent, 6795 CXClientData client_data); 6796 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 6797 CXClientData client_data); 6798 6799 namespace { 6800 class AnnotateTokensWorker { 6801 CXToken *Tokens; 6802 CXCursor *Cursors; 6803 unsigned NumTokens; 6804 unsigned TokIdx; 6805 unsigned PreprocessingTokIdx; 6806 CursorVisitor AnnotateVis; 6807 SourceManager &SrcMgr; 6808 bool HasContextSensitiveKeywords; 6809 6810 struct PostChildrenAction { 6811 CXCursor cursor; 6812 enum Action { Invalid, Ignore, Postpone } action; 6813 }; 6814 using PostChildrenActions = SmallVector<PostChildrenAction, 0>; 6815 6816 struct PostChildrenInfo { 6817 CXCursor Cursor; 6818 SourceRange CursorRange; 6819 unsigned BeforeReachingCursorIdx; 6820 unsigned BeforeChildrenTokenIdx; 6821 PostChildrenActions ChildActions; 6822 }; 6823 SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 6824 6825 CXToken &getTok(unsigned Idx) { 6826 assert(Idx < NumTokens); 6827 return Tokens[Idx]; 6828 } 6829 const CXToken &getTok(unsigned Idx) const { 6830 assert(Idx < NumTokens); 6831 return Tokens[Idx]; 6832 } 6833 bool MoreTokens() const { return TokIdx < NumTokens; } 6834 unsigned NextToken() const { return TokIdx; } 6835 void AdvanceToken() { ++TokIdx; } 6836 SourceLocation GetTokenLoc(unsigned tokI) { 6837 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 6838 } 6839 bool isFunctionMacroToken(unsigned tokI) const { 6840 return getTok(tokI).int_data[3] != 0; 6841 } 6842 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 6843 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]); 6844 } 6845 6846 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 6847 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 6848 SourceRange); 6849 6850 public: 6851 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, 6852 CXTranslationUnit TU, SourceRange RegionOfInterest) 6853 : Tokens(tokens), Cursors(cursors), 6854 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 6855 AnnotateVis(TU, 6856 AnnotateTokensVisitor, this, 6857 /*VisitPreprocessorLast=*/true, 6858 /*VisitIncludedEntities=*/false, 6859 RegionOfInterest, 6860 /*VisitDeclsOnly=*/false, 6861 AnnotateTokensPostChildrenVisitor), 6862 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()), 6863 HasContextSensitiveKeywords(false) { } 6864 6865 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 6866 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 6867 bool IsIgnoredChildCursor(CXCursor cursor) const; 6868 PostChildrenActions DetermineChildActions(CXCursor Cursor) const; 6869 6870 bool postVisitChildren(CXCursor cursor); 6871 void HandlePostPonedChildCursors(const PostChildrenInfo &Info); 6872 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex); 6873 6874 void AnnotateTokens(); 6875 6876 /// Determine whether the annotator saw any cursors that have 6877 /// context-sensitive keywords. 6878 bool hasContextSensitiveKeywords() const { 6879 return HasContextSensitiveKeywords; 6880 } 6881 6882 ~AnnotateTokensWorker() { 6883 assert(PostChildrenInfos.empty()); 6884 } 6885 }; 6886 } 6887 6888 void AnnotateTokensWorker::AnnotateTokens() { 6889 // Walk the AST within the region of interest, annotating tokens 6890 // along the way. 6891 AnnotateVis.visitFileRegion(); 6892 } 6893 6894 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const { 6895 if (PostChildrenInfos.empty()) 6896 return false; 6897 6898 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) { 6899 if (ChildAction.cursor == cursor && 6900 ChildAction.action == PostChildrenAction::Ignore) { 6901 return true; 6902 } 6903 } 6904 6905 return false; 6906 } 6907 6908 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) { 6909 if (!clang_isExpression(Cursor.kind)) 6910 return nullptr; 6911 6912 const Expr *E = getCursorExpr(Cursor); 6913 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 6914 const OverloadedOperatorKind Kind = OCE->getOperator(); 6915 if (Kind == OO_Call || Kind == OO_Subscript) 6916 return OCE; 6917 } 6918 6919 return nullptr; 6920 } 6921 6922 AnnotateTokensWorker::PostChildrenActions 6923 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const { 6924 PostChildrenActions actions; 6925 6926 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is 6927 // visited before the arguments to the operator call. For the Call and 6928 // Subscript operator the range of this DeclRefExpr includes the whole call 6929 // expression, so that all tokens in that range would be mapped to the 6930 // operator function, including the tokens of the arguments. To avoid that, 6931 // ensure to visit this DeclRefExpr as last node. 6932 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) { 6933 const Expr *Callee = OCE->getCallee(); 6934 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) { 6935 const Expr *SubExpr = ICE->getSubExpr(); 6936 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) { 6937 const Decl *parentDecl = getCursorParentDecl(Cursor); 6938 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor); 6939 6940 // Visit the DeclRefExpr as last. 6941 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU); 6942 actions.push_back({cxChild, PostChildrenAction::Postpone}); 6943 6944 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally 6945 // wide range as the DeclRefExpr. We can skip visiting this entirely. 6946 cxChild = MakeCXCursor(ICE, parentDecl, TU); 6947 actions.push_back({cxChild, PostChildrenAction::Ignore}); 6948 } 6949 } 6950 } 6951 6952 return actions; 6953 } 6954 6955 static inline void updateCursorAnnotation(CXCursor &Cursor, 6956 const CXCursor &updateC) { 6957 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind)) 6958 return; 6959 Cursor = updateC; 6960 } 6961 6962 /// It annotates and advances tokens with a cursor until the comparison 6963 //// between the cursor location and the source range is the same as 6964 /// \arg compResult. 6965 /// 6966 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 6967 /// Pass RangeOverlap to annotate tokens inside a range. 6968 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC, 6969 RangeComparisonResult compResult, 6970 SourceRange range) { 6971 while (MoreTokens()) { 6972 const unsigned I = NextToken(); 6973 if (isFunctionMacroToken(I)) 6974 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range)) 6975 return; 6976 6977 SourceLocation TokLoc = GetTokenLoc(I); 6978 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 6979 updateCursorAnnotation(Cursors[I], updateC); 6980 AdvanceToken(); 6981 continue; 6982 } 6983 break; 6984 } 6985 } 6986 6987 /// Special annotation handling for macro argument tokens. 6988 /// \returns true if it advanced beyond all macro tokens, false otherwise. 6989 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 6990 CXCursor updateC, 6991 RangeComparisonResult compResult, 6992 SourceRange range) { 6993 assert(MoreTokens()); 6994 assert(isFunctionMacroToken(NextToken()) && 6995 "Should be called only for macro arg tokens"); 6996 6997 // This works differently than annotateAndAdvanceTokens; because expanded 6998 // macro arguments can have arbitrary translation-unit source order, we do not 6999 // advance the token index one by one until a token fails the range test. 7000 // We only advance once past all of the macro arg tokens if all of them 7001 // pass the range test. If one of them fails we keep the token index pointing 7002 // at the start of the macro arg tokens so that the failing token will be 7003 // annotated by a subsequent annotation try. 7004 7005 bool atLeastOneCompFail = false; 7006 7007 unsigned I = NextToken(); 7008 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 7009 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 7010 if (TokLoc.isFileID()) 7011 continue; // not macro arg token, it's parens or comma. 7012 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 7013 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7014 Cursors[I] = updateC; 7015 } else 7016 atLeastOneCompFail = true; 7017 } 7018 7019 if (atLeastOneCompFail) 7020 return false; 7021 7022 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 7023 return true; 7024 } 7025 7026 enum CXChildVisitResult 7027 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 7028 SourceRange cursorRange = getRawCursorExtent(cursor); 7029 if (cursorRange.isInvalid()) 7030 return CXChildVisit_Recurse; 7031 7032 if (IsIgnoredChildCursor(cursor)) 7033 return CXChildVisit_Continue; 7034 7035 if (!HasContextSensitiveKeywords) { 7036 // Objective-C properties can have context-sensitive keywords. 7037 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 7038 if (const ObjCPropertyDecl *Property 7039 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 7040 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; 7041 } 7042 // Objective-C methods can have context-sensitive keywords. 7043 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 7044 cursor.kind == CXCursor_ObjCClassMethodDecl) { 7045 if (const ObjCMethodDecl *Method 7046 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 7047 if (Method->getObjCDeclQualifier()) 7048 HasContextSensitiveKeywords = true; 7049 else { 7050 for (const auto *P : Method->parameters()) { 7051 if (P->getObjCDeclQualifier()) { 7052 HasContextSensitiveKeywords = true; 7053 break; 7054 } 7055 } 7056 } 7057 } 7058 } 7059 // C++ methods can have context-sensitive keywords. 7060 else if (cursor.kind == CXCursor_CXXMethod) { 7061 if (const CXXMethodDecl *Method 7062 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 7063 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 7064 HasContextSensitiveKeywords = true; 7065 } 7066 } 7067 // C++ classes can have context-sensitive keywords. 7068 else if (cursor.kind == CXCursor_StructDecl || 7069 cursor.kind == CXCursor_ClassDecl || 7070 cursor.kind == CXCursor_ClassTemplate || 7071 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 7072 if (const Decl *D = getCursorDecl(cursor)) 7073 if (D->hasAttr<FinalAttr>()) 7074 HasContextSensitiveKeywords = true; 7075 } 7076 } 7077 7078 // Don't override a property annotation with its getter/setter method. 7079 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl && 7080 parent.kind == CXCursor_ObjCPropertyDecl) 7081 return CXChildVisit_Continue; 7082 7083 if (clang_isPreprocessing(cursor.kind)) { 7084 // Items in the preprocessing record are kept separate from items in 7085 // declarations, so we keep a separate token index. 7086 unsigned SavedTokIdx = TokIdx; 7087 TokIdx = PreprocessingTokIdx; 7088 7089 // Skip tokens up until we catch up to the beginning of the preprocessing 7090 // entry. 7091 while (MoreTokens()) { 7092 const unsigned I = NextToken(); 7093 SourceLocation TokLoc = GetTokenLoc(I); 7094 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7095 case RangeBefore: 7096 AdvanceToken(); 7097 continue; 7098 case RangeAfter: 7099 case RangeOverlap: 7100 break; 7101 } 7102 break; 7103 } 7104 7105 // Look at all of the tokens within this range. 7106 while (MoreTokens()) { 7107 const unsigned I = NextToken(); 7108 SourceLocation TokLoc = GetTokenLoc(I); 7109 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7110 case RangeBefore: 7111 llvm_unreachable("Infeasible"); 7112 case RangeAfter: 7113 break; 7114 case RangeOverlap: 7115 // For macro expansions, just note where the beginning of the macro 7116 // expansion occurs. 7117 if (cursor.kind == CXCursor_MacroExpansion) { 7118 if (TokLoc == cursorRange.getBegin()) 7119 Cursors[I] = cursor; 7120 AdvanceToken(); 7121 break; 7122 } 7123 // We may have already annotated macro names inside macro definitions. 7124 if (Cursors[I].kind != CXCursor_MacroExpansion) 7125 Cursors[I] = cursor; 7126 AdvanceToken(); 7127 continue; 7128 } 7129 break; 7130 } 7131 7132 // Save the preprocessing token index; restore the non-preprocessing 7133 // token index. 7134 PreprocessingTokIdx = TokIdx; 7135 TokIdx = SavedTokIdx; 7136 return CXChildVisit_Recurse; 7137 } 7138 7139 if (cursorRange.isInvalid()) 7140 return CXChildVisit_Continue; 7141 7142 unsigned BeforeReachingCursorIdx = NextToken(); 7143 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 7144 const enum CXCursorKind K = clang_getCursorKind(parent); 7145 const CXCursor updateC = 7146 (clang_isInvalid(K) || K == CXCursor_TranslationUnit || 7147 // Attributes are annotated out-of-order, skip tokens until we reach it. 7148 clang_isAttribute(cursor.kind)) 7149 ? clang_getNullCursor() : parent; 7150 7151 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 7152 7153 // Avoid having the cursor of an expression "overwrite" the annotation of the 7154 // variable declaration that it belongs to. 7155 // This can happen for C++ constructor expressions whose range generally 7156 // include the variable declaration, e.g.: 7157 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 7158 if (clang_isExpression(cursorK) && MoreTokens()) { 7159 const Expr *E = getCursorExpr(cursor); 7160 if (const Decl *D = getCursorParentDecl(cursor)) { 7161 const unsigned I = NextToken(); 7162 if (E->getBeginLoc().isValid() && D->getLocation().isValid() && 7163 E->getBeginLoc() == D->getLocation() && 7164 E->getBeginLoc() == GetTokenLoc(I)) { 7165 updateCursorAnnotation(Cursors[I], updateC); 7166 AdvanceToken(); 7167 } 7168 } 7169 } 7170 7171 // Before recursing into the children keep some state that we are going 7172 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 7173 // extra work after the child nodes are visited. 7174 // Note that we don't call VisitChildren here to avoid traversing statements 7175 // code-recursively which can blow the stack. 7176 7177 PostChildrenInfo Info; 7178 Info.Cursor = cursor; 7179 Info.CursorRange = cursorRange; 7180 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx; 7181 Info.BeforeChildrenTokenIdx = NextToken(); 7182 Info.ChildActions = DetermineChildActions(cursor); 7183 PostChildrenInfos.push_back(Info); 7184 7185 return CXChildVisit_Recurse; 7186 } 7187 7188 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 7189 if (PostChildrenInfos.empty()) 7190 return false; 7191 const PostChildrenInfo &Info = PostChildrenInfos.back(); 7192 if (!clang_equalCursors(Info.Cursor, cursor)) 7193 return false; 7194 7195 HandlePostPonedChildCursors(Info); 7196 7197 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 7198 const unsigned AfterChildren = NextToken(); 7199 SourceRange cursorRange = Info.CursorRange; 7200 7201 // Scan the tokens that are at the end of the cursor, but are not captured 7202 // but the child cursors. 7203 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 7204 7205 // Scan the tokens that are at the beginning of the cursor, but are not 7206 // capture by the child cursors. 7207 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 7208 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7209 break; 7210 7211 Cursors[I] = cursor; 7212 } 7213 7214 // Attributes are annotated out-of-order, rewind TokIdx to when we first 7215 // encountered the attribute cursor. 7216 if (clang_isAttribute(cursor.kind)) 7217 TokIdx = Info.BeforeReachingCursorIdx; 7218 7219 PostChildrenInfos.pop_back(); 7220 return false; 7221 } 7222 7223 void AnnotateTokensWorker::HandlePostPonedChildCursors( 7224 const PostChildrenInfo &Info) { 7225 for (const auto &ChildAction : Info.ChildActions) { 7226 if (ChildAction.action == PostChildrenAction::Postpone) { 7227 HandlePostPonedChildCursor(ChildAction.cursor, 7228 Info.BeforeChildrenTokenIdx); 7229 } 7230 } 7231 } 7232 7233 void AnnotateTokensWorker::HandlePostPonedChildCursor( 7234 CXCursor Cursor, unsigned StartTokenIndex) { 7235 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier; 7236 unsigned I = StartTokenIndex; 7237 7238 // The bracket tokens of a Call or Subscript operator are mapped to 7239 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding 7240 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors. 7241 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) { 7242 const CXSourceRange CXRefNameRange = 7243 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr); 7244 if (clang_Range_isNull(CXRefNameRange)) 7245 break; // All ranges handled. 7246 7247 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange); 7248 while (I < NumTokens) { 7249 const SourceLocation TokenLocation = GetTokenLoc(I); 7250 if (!TokenLocation.isValid()) 7251 break; 7252 7253 // Adapt the end range, because LocationCompare() reports 7254 // RangeOverlap even for the not-inclusive end location. 7255 const SourceLocation fixedEnd = 7256 RefNameRange.getEnd().getLocWithOffset(-1); 7257 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd); 7258 7259 const RangeComparisonResult ComparisonResult = 7260 LocationCompare(SrcMgr, TokenLocation, RefNameRange); 7261 7262 if (ComparisonResult == RangeOverlap) { 7263 Cursors[I++] = Cursor; 7264 } else if (ComparisonResult == RangeBefore) { 7265 ++I; // Not relevant token, check next one. 7266 } else if (ComparisonResult == RangeAfter) { 7267 break; // All tokens updated for current range, check next. 7268 } 7269 } 7270 } 7271 } 7272 7273 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 7274 CXCursor parent, 7275 CXClientData client_data) { 7276 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 7277 } 7278 7279 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 7280 CXClientData client_data) { 7281 return static_cast<AnnotateTokensWorker*>(client_data)-> 7282 postVisitChildren(cursor); 7283 } 7284 7285 namespace { 7286 7287 /// Uses the macro expansions in the preprocessing record to find 7288 /// and mark tokens that are macro arguments. This info is used by the 7289 /// AnnotateTokensWorker. 7290 class MarkMacroArgTokensVisitor { 7291 SourceManager &SM; 7292 CXToken *Tokens; 7293 unsigned NumTokens; 7294 unsigned CurIdx; 7295 7296 public: 7297 MarkMacroArgTokensVisitor(SourceManager &SM, 7298 CXToken *tokens, unsigned numTokens) 7299 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { } 7300 7301 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 7302 if (cursor.kind != CXCursor_MacroExpansion) 7303 return CXChildVisit_Continue; 7304 7305 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); 7306 if (macroRange.getBegin() == macroRange.getEnd()) 7307 return CXChildVisit_Continue; // it's not a function macro. 7308 7309 for (; CurIdx < NumTokens; ++CurIdx) { 7310 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 7311 macroRange.getBegin())) 7312 break; 7313 } 7314 7315 if (CurIdx == NumTokens) 7316 return CXChildVisit_Break; 7317 7318 for (; CurIdx < NumTokens; ++CurIdx) { 7319 SourceLocation tokLoc = getTokenLoc(CurIdx); 7320 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 7321 break; 7322 7323 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 7324 } 7325 7326 if (CurIdx == NumTokens) 7327 return CXChildVisit_Break; 7328 7329 return CXChildVisit_Continue; 7330 } 7331 7332 private: 7333 CXToken &getTok(unsigned Idx) { 7334 assert(Idx < NumTokens); 7335 return Tokens[Idx]; 7336 } 7337 const CXToken &getTok(unsigned Idx) const { 7338 assert(Idx < NumTokens); 7339 return Tokens[Idx]; 7340 } 7341 7342 SourceLocation getTokenLoc(unsigned tokI) { 7343 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 7344 } 7345 7346 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 7347 // The third field is reserved and currently not used. Use it here 7348 // to mark macro arg expanded tokens with their expanded locations. 7349 getTok(tokI).int_data[3] = loc.getRawEncoding(); 7350 } 7351 }; 7352 7353 } // end anonymous namespace 7354 7355 static CXChildVisitResult 7356 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 7357 CXClientData client_data) { 7358 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor, 7359 parent); 7360 } 7361 7362 /// Used by \c annotatePreprocessorTokens. 7363 /// \returns true if lexing was finished, false otherwise. 7364 static bool lexNext(Lexer &Lex, Token &Tok, 7365 unsigned &NextIdx, unsigned NumTokens) { 7366 if (NextIdx >= NumTokens) 7367 return true; 7368 7369 ++NextIdx; 7370 Lex.LexFromRawLexer(Tok); 7371 return Tok.is(tok::eof); 7372 } 7373 7374 static void annotatePreprocessorTokens(CXTranslationUnit TU, 7375 SourceRange RegionOfInterest, 7376 CXCursor *Cursors, 7377 CXToken *Tokens, 7378 unsigned NumTokens) { 7379 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7380 7381 Preprocessor &PP = CXXUnit->getPreprocessor(); 7382 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 7383 std::pair<FileID, unsigned> BeginLocInfo 7384 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin()); 7385 std::pair<FileID, unsigned> EndLocInfo 7386 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd()); 7387 7388 if (BeginLocInfo.first != EndLocInfo.first) 7389 return; 7390 7391 StringRef Buffer; 7392 bool Invalid = false; 7393 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 7394 if (Buffer.empty() || Invalid) 7395 return; 7396 7397 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 7398 CXXUnit->getASTContext().getLangOpts(), 7399 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 7400 Buffer.end()); 7401 Lex.SetCommentRetentionState(true); 7402 7403 unsigned NextIdx = 0; 7404 // Lex tokens in raw mode until we hit the end of the range, to avoid 7405 // entering #includes or expanding macros. 7406 while (true) { 7407 Token Tok; 7408 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7409 break; 7410 unsigned TokIdx = NextIdx-1; 7411 assert(Tok.getLocation() == 7412 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); 7413 7414 reprocess: 7415 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 7416 // We have found a preprocessing directive. Annotate the tokens 7417 // appropriately. 7418 // 7419 // FIXME: Some simple tests here could identify macro definitions and 7420 // #undefs, to provide specific cursor kinds for those. 7421 7422 SourceLocation BeginLoc = Tok.getLocation(); 7423 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7424 break; 7425 7426 MacroInfo *MI = nullptr; 7427 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") { 7428 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7429 break; 7430 7431 if (Tok.is(tok::raw_identifier)) { 7432 IdentifierInfo &II = 7433 PP.getIdentifierTable().get(Tok.getRawIdentifier()); 7434 SourceLocation MappedTokLoc = 7435 CXXUnit->mapLocationToPreamble(Tok.getLocation()); 7436 MI = getMacroInfo(II, MappedTokLoc, TU); 7437 } 7438 } 7439 7440 bool finished = false; 7441 do { 7442 if (lexNext(Lex, Tok, NextIdx, NumTokens)) { 7443 finished = true; 7444 break; 7445 } 7446 // If we are in a macro definition, check if the token was ever a 7447 // macro name and annotate it if that's the case. 7448 if (MI) { 7449 SourceLocation SaveLoc = Tok.getLocation(); 7450 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); 7451 MacroDefinitionRecord *MacroDef = 7452 checkForMacroInMacroDefinition(MI, Tok, TU); 7453 Tok.setLocation(SaveLoc); 7454 if (MacroDef) 7455 Cursors[NextIdx - 1] = 7456 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU); 7457 } 7458 } while (!Tok.isAtStartOfLine()); 7459 7460 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2; 7461 assert(TokIdx <= LastIdx); 7462 SourceLocation EndLoc = 7463 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); 7464 CXCursor Cursor = 7465 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); 7466 7467 for (; TokIdx <= LastIdx; ++TokIdx) 7468 updateCursorAnnotation(Cursors[TokIdx], Cursor); 7469 7470 if (finished) 7471 break; 7472 goto reprocess; 7473 } 7474 } 7475 } 7476 7477 // This gets run a separate thread to avoid stack blowout. 7478 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit, 7479 CXToken *Tokens, unsigned NumTokens, 7480 CXCursor *Cursors) { 7481 CIndexer *CXXIdx = TU->CIdx; 7482 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 7483 setThreadBackgroundPriority(); 7484 7485 // Determine the region of interest, which contains all of the tokens. 7486 SourceRange RegionOfInterest; 7487 RegionOfInterest.setBegin( 7488 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 7489 RegionOfInterest.setEnd( 7490 cxloc::translateSourceLocation(clang_getTokenLocation(TU, 7491 Tokens[NumTokens-1]))); 7492 7493 // Relex the tokens within the source range to look for preprocessing 7494 // directives. 7495 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); 7496 7497 // If begin location points inside a macro argument, set it to the expansion 7498 // location so we can have the full context when annotating semantically. 7499 { 7500 SourceManager &SM = CXXUnit->getSourceManager(); 7501 SourceLocation Loc = 7502 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin()); 7503 if (Loc.isMacroID()) 7504 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc)); 7505 } 7506 7507 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 7508 // Search and mark tokens that are macro argument expansions. 7509 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), 7510 Tokens, NumTokens); 7511 CursorVisitor MacroArgMarker(TU, 7512 MarkMacroArgTokensVisitorDelegate, &Visitor, 7513 /*VisitPreprocessorLast=*/true, 7514 /*VisitIncludedEntities=*/false, 7515 RegionOfInterest); 7516 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 7517 } 7518 7519 // Annotate all of the source locations in the region of interest that map to 7520 // a specific cursor. 7521 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); 7522 7523 // FIXME: We use a ridiculous stack size here because the data-recursion 7524 // algorithm uses a large stack frame than the non-data recursive version, 7525 // and AnnotationTokensWorker currently transforms the data-recursion 7526 // algorithm back into a traditional recursion by explicitly calling 7527 // VisitChildren(). We will need to remove this explicit recursive call. 7528 W.AnnotateTokens(); 7529 7530 // If we ran into any entities that involve context-sensitive keywords, 7531 // take another pass through the tokens to mark them as such. 7532 if (W.hasContextSensitiveKeywords()) { 7533 for (unsigned I = 0; I != NumTokens; ++I) { 7534 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 7535 continue; 7536 7537 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 7538 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7539 if (const ObjCPropertyDecl *Property 7540 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 7541 if (Property->getPropertyAttributesAsWritten() != 0 && 7542 llvm::StringSwitch<bool>(II->getName()) 7543 .Case("readonly", true) 7544 .Case("assign", true) 7545 .Case("unsafe_unretained", true) 7546 .Case("readwrite", true) 7547 .Case("retain", true) 7548 .Case("copy", true) 7549 .Case("nonatomic", true) 7550 .Case("atomic", true) 7551 .Case("getter", true) 7552 .Case("setter", true) 7553 .Case("strong", true) 7554 .Case("weak", true) 7555 .Case("class", true) 7556 .Default(false)) 7557 Tokens[I].int_data[0] = CXToken_Keyword; 7558 } 7559 continue; 7560 } 7561 7562 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 7563 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 7564 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7565 if (llvm::StringSwitch<bool>(II->getName()) 7566 .Case("in", true) 7567 .Case("out", true) 7568 .Case("inout", true) 7569 .Case("oneway", true) 7570 .Case("bycopy", true) 7571 .Case("byref", true) 7572 .Default(false)) 7573 Tokens[I].int_data[0] = CXToken_Keyword; 7574 continue; 7575 } 7576 7577 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 7578 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 7579 Tokens[I].int_data[0] = CXToken_Keyword; 7580 continue; 7581 } 7582 } 7583 } 7584 } 7585 7586 void clang_annotateTokens(CXTranslationUnit TU, 7587 CXToken *Tokens, unsigned NumTokens, 7588 CXCursor *Cursors) { 7589 if (isNotUsableTU(TU)) { 7590 LOG_BAD_TU(TU); 7591 return; 7592 } 7593 if (NumTokens == 0 || !Tokens || !Cursors) { 7594 LOG_FUNC_SECTION { *Log << "<null input>"; } 7595 return; 7596 } 7597 7598 LOG_FUNC_SECTION { 7599 *Log << TU << ' '; 7600 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); 7601 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]); 7602 *Log << clang_getRange(bloc, eloc); 7603 } 7604 7605 // Any token we don't specifically annotate will have a NULL cursor. 7606 CXCursor C = clang_getNullCursor(); 7607 for (unsigned I = 0; I != NumTokens; ++I) 7608 Cursors[I] = C; 7609 7610 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7611 if (!CXXUnit) 7612 return; 7613 7614 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7615 7616 auto AnnotateTokensImpl = [=]() { 7617 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors); 7618 }; 7619 llvm::CrashRecoveryContext CRC; 7620 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) { 7621 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 7622 } 7623 } 7624 7625 //===----------------------------------------------------------------------===// 7626 // Operations for querying linkage of a cursor. 7627 //===----------------------------------------------------------------------===// 7628 7629 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 7630 if (!clang_isDeclaration(cursor.kind)) 7631 return CXLinkage_Invalid; 7632 7633 const Decl *D = cxcursor::getCursorDecl(cursor); 7634 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7635 switch (ND->getLinkageInternal()) { 7636 case NoLinkage: 7637 case VisibleNoLinkage: return CXLinkage_NoLinkage; 7638 case ModuleInternalLinkage: 7639 case InternalLinkage: return CXLinkage_Internal; 7640 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 7641 case ModuleLinkage: 7642 case ExternalLinkage: return CXLinkage_External; 7643 }; 7644 7645 return CXLinkage_Invalid; 7646 } 7647 7648 //===----------------------------------------------------------------------===// 7649 // Operations for querying visibility of a cursor. 7650 //===----------------------------------------------------------------------===// 7651 7652 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) { 7653 if (!clang_isDeclaration(cursor.kind)) 7654 return CXVisibility_Invalid; 7655 7656 const Decl *D = cxcursor::getCursorDecl(cursor); 7657 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7658 switch (ND->getVisibility()) { 7659 case HiddenVisibility: return CXVisibility_Hidden; 7660 case ProtectedVisibility: return CXVisibility_Protected; 7661 case DefaultVisibility: return CXVisibility_Default; 7662 }; 7663 7664 return CXVisibility_Invalid; 7665 } 7666 7667 //===----------------------------------------------------------------------===// 7668 // Operations for querying language of a cursor. 7669 //===----------------------------------------------------------------------===// 7670 7671 static CXLanguageKind getDeclLanguage(const Decl *D) { 7672 if (!D) 7673 return CXLanguage_C; 7674 7675 switch (D->getKind()) { 7676 default: 7677 break; 7678 case Decl::ImplicitParam: 7679 case Decl::ObjCAtDefsField: 7680 case Decl::ObjCCategory: 7681 case Decl::ObjCCategoryImpl: 7682 case Decl::ObjCCompatibleAlias: 7683 case Decl::ObjCImplementation: 7684 case Decl::ObjCInterface: 7685 case Decl::ObjCIvar: 7686 case Decl::ObjCMethod: 7687 case Decl::ObjCProperty: 7688 case Decl::ObjCPropertyImpl: 7689 case Decl::ObjCProtocol: 7690 case Decl::ObjCTypeParam: 7691 return CXLanguage_ObjC; 7692 case Decl::CXXConstructor: 7693 case Decl::CXXConversion: 7694 case Decl::CXXDestructor: 7695 case Decl::CXXMethod: 7696 case Decl::CXXRecord: 7697 case Decl::ClassTemplate: 7698 case Decl::ClassTemplatePartialSpecialization: 7699 case Decl::ClassTemplateSpecialization: 7700 case Decl::Friend: 7701 case Decl::FriendTemplate: 7702 case Decl::FunctionTemplate: 7703 case Decl::LinkageSpec: 7704 case Decl::Namespace: 7705 case Decl::NamespaceAlias: 7706 case Decl::NonTypeTemplateParm: 7707 case Decl::StaticAssert: 7708 case Decl::TemplateTemplateParm: 7709 case Decl::TemplateTypeParm: 7710 case Decl::UnresolvedUsingTypename: 7711 case Decl::UnresolvedUsingValue: 7712 case Decl::Using: 7713 case Decl::UsingDirective: 7714 case Decl::UsingShadow: 7715 return CXLanguage_CPlusPlus; 7716 } 7717 7718 return CXLanguage_C; 7719 } 7720 7721 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) { 7722 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 7723 return CXAvailability_NotAvailable; 7724 7725 switch (D->getAvailability()) { 7726 case AR_Available: 7727 case AR_NotYetIntroduced: 7728 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 7729 return getCursorAvailabilityForDecl( 7730 cast<Decl>(EnumConst->getDeclContext())); 7731 return CXAvailability_Available; 7732 7733 case AR_Deprecated: 7734 return CXAvailability_Deprecated; 7735 7736 case AR_Unavailable: 7737 return CXAvailability_NotAvailable; 7738 } 7739 7740 llvm_unreachable("Unknown availability kind!"); 7741 } 7742 7743 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 7744 if (clang_isDeclaration(cursor.kind)) 7745 if (const Decl *D = cxcursor::getCursorDecl(cursor)) 7746 return getCursorAvailabilityForDecl(D); 7747 7748 return CXAvailability_Available; 7749 } 7750 7751 static CXVersion convertVersion(VersionTuple In) { 7752 CXVersion Out = { -1, -1, -1 }; 7753 if (In.empty()) 7754 return Out; 7755 7756 Out.Major = In.getMajor(); 7757 7758 Optional<unsigned> Minor = In.getMinor(); 7759 if (Minor.hasValue()) 7760 Out.Minor = *Minor; 7761 else 7762 return Out; 7763 7764 Optional<unsigned> Subminor = In.getSubminor(); 7765 if (Subminor.hasValue()) 7766 Out.Subminor = *Subminor; 7767 7768 return Out; 7769 } 7770 7771 static void getCursorPlatformAvailabilityForDecl( 7772 const Decl *D, int *always_deprecated, CXString *deprecated_message, 7773 int *always_unavailable, CXString *unavailable_message, 7774 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) { 7775 bool HadAvailAttr = false; 7776 for (auto A : D->attrs()) { 7777 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 7778 HadAvailAttr = true; 7779 if (always_deprecated) 7780 *always_deprecated = 1; 7781 if (deprecated_message) { 7782 clang_disposeString(*deprecated_message); 7783 *deprecated_message = cxstring::createDup(Deprecated->getMessage()); 7784 } 7785 continue; 7786 } 7787 7788 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) { 7789 HadAvailAttr = true; 7790 if (always_unavailable) 7791 *always_unavailable = 1; 7792 if (unavailable_message) { 7793 clang_disposeString(*unavailable_message); 7794 *unavailable_message = cxstring::createDup(Unavailable->getMessage()); 7795 } 7796 continue; 7797 } 7798 7799 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) { 7800 AvailabilityAttrs.push_back(Avail); 7801 HadAvailAttr = true; 7802 } 7803 } 7804 7805 if (!HadAvailAttr) 7806 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 7807 return getCursorPlatformAvailabilityForDecl( 7808 cast<Decl>(EnumConst->getDeclContext()), always_deprecated, 7809 deprecated_message, always_unavailable, unavailable_message, 7810 AvailabilityAttrs); 7811 7812 if (AvailabilityAttrs.empty()) 7813 return; 7814 7815 llvm::sort(AvailabilityAttrs, 7816 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 7817 return LHS->getPlatform()->getName() < 7818 RHS->getPlatform()->getName(); 7819 }); 7820 ASTContext &Ctx = D->getASTContext(); 7821 auto It = std::unique( 7822 AvailabilityAttrs.begin(), AvailabilityAttrs.end(), 7823 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 7824 if (LHS->getPlatform() != RHS->getPlatform()) 7825 return false; 7826 7827 if (LHS->getIntroduced() == RHS->getIntroduced() && 7828 LHS->getDeprecated() == RHS->getDeprecated() && 7829 LHS->getObsoleted() == RHS->getObsoleted() && 7830 LHS->getMessage() == RHS->getMessage() && 7831 LHS->getReplacement() == RHS->getReplacement()) 7832 return true; 7833 7834 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) || 7835 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) || 7836 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty())) 7837 return false; 7838 7839 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) 7840 LHS->setIntroduced(Ctx, RHS->getIntroduced()); 7841 7842 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) { 7843 LHS->setDeprecated(Ctx, RHS->getDeprecated()); 7844 if (LHS->getMessage().empty()) 7845 LHS->setMessage(Ctx, RHS->getMessage()); 7846 if (LHS->getReplacement().empty()) 7847 LHS->setReplacement(Ctx, RHS->getReplacement()); 7848 } 7849 7850 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) { 7851 LHS->setObsoleted(Ctx, RHS->getObsoleted()); 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 return true; 7859 }); 7860 AvailabilityAttrs.erase(It, AvailabilityAttrs.end()); 7861 } 7862 7863 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, 7864 CXString *deprecated_message, 7865 int *always_unavailable, 7866 CXString *unavailable_message, 7867 CXPlatformAvailability *availability, 7868 int availability_size) { 7869 if (always_deprecated) 7870 *always_deprecated = 0; 7871 if (deprecated_message) 7872 *deprecated_message = cxstring::createEmpty(); 7873 if (always_unavailable) 7874 *always_unavailable = 0; 7875 if (unavailable_message) 7876 *unavailable_message = cxstring::createEmpty(); 7877 7878 if (!clang_isDeclaration(cursor.kind)) 7879 return 0; 7880 7881 const Decl *D = cxcursor::getCursorDecl(cursor); 7882 if (!D) 7883 return 0; 7884 7885 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs; 7886 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message, 7887 always_unavailable, unavailable_message, 7888 AvailabilityAttrs); 7889 for (const auto &Avail : 7890 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs) 7891 .take_front(availability_size))) { 7892 availability[Avail.index()].Platform = 7893 cxstring::createDup(Avail.value()->getPlatform()->getName()); 7894 availability[Avail.index()].Introduced = 7895 convertVersion(Avail.value()->getIntroduced()); 7896 availability[Avail.index()].Deprecated = 7897 convertVersion(Avail.value()->getDeprecated()); 7898 availability[Avail.index()].Obsoleted = 7899 convertVersion(Avail.value()->getObsoleted()); 7900 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable(); 7901 availability[Avail.index()].Message = 7902 cxstring::createDup(Avail.value()->getMessage()); 7903 } 7904 7905 return AvailabilityAttrs.size(); 7906 } 7907 7908 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 7909 clang_disposeString(availability->Platform); 7910 clang_disposeString(availability->Message); 7911 } 7912 7913 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 7914 if (clang_isDeclaration(cursor.kind)) 7915 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 7916 7917 return CXLanguage_Invalid; 7918 } 7919 7920 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) { 7921 const Decl *D = cxcursor::getCursorDecl(cursor); 7922 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7923 switch (VD->getTLSKind()) { 7924 case VarDecl::TLS_None: 7925 return CXTLS_None; 7926 case VarDecl::TLS_Dynamic: 7927 return CXTLS_Dynamic; 7928 case VarDecl::TLS_Static: 7929 return CXTLS_Static; 7930 } 7931 } 7932 7933 return CXTLS_None; 7934 } 7935 7936 /// If the given cursor is the "templated" declaration 7937 /// describing a class or function template, return the class or 7938 /// function template. 7939 static const Decl *maybeGetTemplateCursor(const Decl *D) { 7940 if (!D) 7941 return nullptr; 7942 7943 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 7944 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 7945 return FunTmpl; 7946 7947 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 7948 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 7949 return ClassTmpl; 7950 7951 return D; 7952 } 7953 7954 7955 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) { 7956 StorageClass sc = SC_None; 7957 const Decl *D = getCursorDecl(C); 7958 if (D) { 7959 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7960 sc = FD->getStorageClass(); 7961 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7962 sc = VD->getStorageClass(); 7963 } else { 7964 return CX_SC_Invalid; 7965 } 7966 } else { 7967 return CX_SC_Invalid; 7968 } 7969 switch (sc) { 7970 case SC_None: 7971 return CX_SC_None; 7972 case SC_Extern: 7973 return CX_SC_Extern; 7974 case SC_Static: 7975 return CX_SC_Static; 7976 case SC_PrivateExtern: 7977 return CX_SC_PrivateExtern; 7978 case SC_Auto: 7979 return CX_SC_Auto; 7980 case SC_Register: 7981 return CX_SC_Register; 7982 } 7983 llvm_unreachable("Unhandled storage class!"); 7984 } 7985 7986 CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 7987 if (clang_isDeclaration(cursor.kind)) { 7988 if (const Decl *D = getCursorDecl(cursor)) { 7989 const DeclContext *DC = D->getDeclContext(); 7990 if (!DC) 7991 return clang_getNullCursor(); 7992 7993 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 7994 getCursorTU(cursor)); 7995 } 7996 } 7997 7998 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 7999 if (const Decl *D = getCursorDecl(cursor)) 8000 return MakeCXCursor(D, getCursorTU(cursor)); 8001 } 8002 8003 return clang_getNullCursor(); 8004 } 8005 8006 CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 8007 if (clang_isDeclaration(cursor.kind)) { 8008 if (const Decl *D = getCursorDecl(cursor)) { 8009 const DeclContext *DC = D->getLexicalDeclContext(); 8010 if (!DC) 8011 return clang_getNullCursor(); 8012 8013 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 8014 getCursorTU(cursor)); 8015 } 8016 } 8017 8018 // FIXME: Note that we can't easily compute the lexical context of a 8019 // statement or expression, so we return nothing. 8020 return clang_getNullCursor(); 8021 } 8022 8023 CXFile clang_getIncludedFile(CXCursor cursor) { 8024 if (cursor.kind != CXCursor_InclusionDirective) 8025 return nullptr; 8026 8027 const InclusionDirective *ID = getCursorInclusionDirective(cursor); 8028 return const_cast<FileEntry *>(ID->getFile()); 8029 } 8030 8031 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) { 8032 if (C.kind != CXCursor_ObjCPropertyDecl) 8033 return CXObjCPropertyAttr_noattr; 8034 8035 unsigned Result = CXObjCPropertyAttr_noattr; 8036 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8037 ObjCPropertyDecl::PropertyAttributeKind Attr = 8038 PD->getPropertyAttributesAsWritten(); 8039 8040 #define SET_CXOBJCPROP_ATTR(A) \ 8041 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \ 8042 Result |= CXObjCPropertyAttr_##A 8043 SET_CXOBJCPROP_ATTR(readonly); 8044 SET_CXOBJCPROP_ATTR(getter); 8045 SET_CXOBJCPROP_ATTR(assign); 8046 SET_CXOBJCPROP_ATTR(readwrite); 8047 SET_CXOBJCPROP_ATTR(retain); 8048 SET_CXOBJCPROP_ATTR(copy); 8049 SET_CXOBJCPROP_ATTR(nonatomic); 8050 SET_CXOBJCPROP_ATTR(setter); 8051 SET_CXOBJCPROP_ATTR(atomic); 8052 SET_CXOBJCPROP_ATTR(weak); 8053 SET_CXOBJCPROP_ATTR(strong); 8054 SET_CXOBJCPROP_ATTR(unsafe_unretained); 8055 SET_CXOBJCPROP_ATTR(class); 8056 #undef SET_CXOBJCPROP_ATTR 8057 8058 return Result; 8059 } 8060 8061 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) { 8062 if (C.kind != CXCursor_ObjCPropertyDecl) 8063 return cxstring::createNull(); 8064 8065 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8066 Selector sel = PD->getGetterName(); 8067 if (sel.isNull()) 8068 return cxstring::createNull(); 8069 8070 return cxstring::createDup(sel.getAsString()); 8071 } 8072 8073 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) { 8074 if (C.kind != CXCursor_ObjCPropertyDecl) 8075 return cxstring::createNull(); 8076 8077 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8078 Selector sel = PD->getSetterName(); 8079 if (sel.isNull()) 8080 return cxstring::createNull(); 8081 8082 return cxstring::createDup(sel.getAsString()); 8083 } 8084 8085 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) { 8086 if (!clang_isDeclaration(C.kind)) 8087 return CXObjCDeclQualifier_None; 8088 8089 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None; 8090 const Decl *D = getCursorDecl(C); 8091 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8092 QT = MD->getObjCDeclQualifier(); 8093 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) 8094 QT = PD->getObjCDeclQualifier(); 8095 if (QT == Decl::OBJC_TQ_None) 8096 return CXObjCDeclQualifier_None; 8097 8098 unsigned Result = CXObjCDeclQualifier_None; 8099 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In; 8100 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout; 8101 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out; 8102 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy; 8103 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref; 8104 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway; 8105 8106 return Result; 8107 } 8108 8109 unsigned clang_Cursor_isObjCOptional(CXCursor C) { 8110 if (!clang_isDeclaration(C.kind)) 8111 return 0; 8112 8113 const Decl *D = getCursorDecl(C); 8114 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 8115 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional; 8116 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8117 return MD->getImplementationControl() == ObjCMethodDecl::Optional; 8118 8119 return 0; 8120 } 8121 8122 unsigned clang_Cursor_isVariadic(CXCursor C) { 8123 if (!clang_isDeclaration(C.kind)) 8124 return 0; 8125 8126 const Decl *D = getCursorDecl(C); 8127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 8128 return FD->isVariadic(); 8129 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8130 return MD->isVariadic(); 8131 8132 return 0; 8133 } 8134 8135 unsigned clang_Cursor_isExternalSymbol(CXCursor C, 8136 CXString *language, CXString *definedIn, 8137 unsigned *isGenerated) { 8138 if (!clang_isDeclaration(C.kind)) 8139 return 0; 8140 8141 const Decl *D = getCursorDecl(C); 8142 8143 if (auto *attr = D->getExternalSourceSymbolAttr()) { 8144 if (language) 8145 *language = cxstring::createDup(attr->getLanguage()); 8146 if (definedIn) 8147 *definedIn = cxstring::createDup(attr->getDefinedIn()); 8148 if (isGenerated) 8149 *isGenerated = attr->getGeneratedDeclaration(); 8150 return 1; 8151 } 8152 return 0; 8153 } 8154 8155 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 8156 if (!clang_isDeclaration(C.kind)) 8157 return clang_getNullRange(); 8158 8159 const Decl *D = getCursorDecl(C); 8160 ASTContext &Context = getCursorContext(C); 8161 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8162 if (!RC) 8163 return clang_getNullRange(); 8164 8165 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 8166 } 8167 8168 CXString clang_Cursor_getRawCommentText(CXCursor C) { 8169 if (!clang_isDeclaration(C.kind)) 8170 return cxstring::createNull(); 8171 8172 const Decl *D = getCursorDecl(C); 8173 ASTContext &Context = getCursorContext(C); 8174 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8175 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) : 8176 StringRef(); 8177 8178 // Don't duplicate the string because RawText points directly into source 8179 // code. 8180 return cxstring::createRef(RawText); 8181 } 8182 8183 CXString clang_Cursor_getBriefCommentText(CXCursor C) { 8184 if (!clang_isDeclaration(C.kind)) 8185 return cxstring::createNull(); 8186 8187 const Decl *D = getCursorDecl(C); 8188 const ASTContext &Context = getCursorContext(C); 8189 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8190 8191 if (RC) { 8192 StringRef BriefText = RC->getBriefText(Context); 8193 8194 // Don't duplicate the string because RawComment ensures that this memory 8195 // will not go away. 8196 return cxstring::createRef(BriefText); 8197 } 8198 8199 return cxstring::createNull(); 8200 } 8201 8202 CXModule clang_Cursor_getModule(CXCursor C) { 8203 if (C.kind == CXCursor_ModuleImportDecl) { 8204 if (const ImportDecl *ImportD = 8205 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 8206 return ImportD->getImportedModule(); 8207 } 8208 8209 return nullptr; 8210 } 8211 8212 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) { 8213 if (isNotUsableTU(TU)) { 8214 LOG_BAD_TU(TU); 8215 return nullptr; 8216 } 8217 if (!File) 8218 return nullptr; 8219 FileEntry *FE = static_cast<FileEntry *>(File); 8220 8221 ASTUnit &Unit = *cxtu::getASTUnit(TU); 8222 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo(); 8223 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE); 8224 8225 return Header.getModule(); 8226 } 8227 8228 CXFile clang_Module_getASTFile(CXModule CXMod) { 8229 if (!CXMod) 8230 return nullptr; 8231 Module *Mod = static_cast<Module*>(CXMod); 8232 return const_cast<FileEntry *>(Mod->getASTFile()); 8233 } 8234 8235 CXModule clang_Module_getParent(CXModule CXMod) { 8236 if (!CXMod) 8237 return nullptr; 8238 Module *Mod = static_cast<Module*>(CXMod); 8239 return Mod->Parent; 8240 } 8241 8242 CXString clang_Module_getName(CXModule CXMod) { 8243 if (!CXMod) 8244 return cxstring::createEmpty(); 8245 Module *Mod = static_cast<Module*>(CXMod); 8246 return cxstring::createDup(Mod->Name); 8247 } 8248 8249 CXString clang_Module_getFullName(CXModule CXMod) { 8250 if (!CXMod) 8251 return cxstring::createEmpty(); 8252 Module *Mod = static_cast<Module*>(CXMod); 8253 return cxstring::createDup(Mod->getFullModuleName()); 8254 } 8255 8256 int clang_Module_isSystem(CXModule CXMod) { 8257 if (!CXMod) 8258 return 0; 8259 Module *Mod = static_cast<Module*>(CXMod); 8260 return Mod->IsSystem; 8261 } 8262 8263 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU, 8264 CXModule CXMod) { 8265 if (isNotUsableTU(TU)) { 8266 LOG_BAD_TU(TU); 8267 return 0; 8268 } 8269 if (!CXMod) 8270 return 0; 8271 Module *Mod = static_cast<Module*>(CXMod); 8272 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8273 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8274 return TopHeaders.size(); 8275 } 8276 8277 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, 8278 CXModule CXMod, unsigned Index) { 8279 if (isNotUsableTU(TU)) { 8280 LOG_BAD_TU(TU); 8281 return nullptr; 8282 } 8283 if (!CXMod) 8284 return nullptr; 8285 Module *Mod = static_cast<Module*>(CXMod); 8286 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8287 8288 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8289 if (Index < TopHeaders.size()) 8290 return const_cast<FileEntry *>(TopHeaders[Index]); 8291 8292 return nullptr; 8293 } 8294 8295 //===----------------------------------------------------------------------===// 8296 // C++ AST instrospection. 8297 //===----------------------------------------------------------------------===// 8298 8299 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) { 8300 if (!clang_isDeclaration(C.kind)) 8301 return 0; 8302 8303 const Decl *D = cxcursor::getCursorDecl(C); 8304 const CXXConstructorDecl *Constructor = 8305 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8306 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0; 8307 } 8308 8309 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) { 8310 if (!clang_isDeclaration(C.kind)) 8311 return 0; 8312 8313 const Decl *D = cxcursor::getCursorDecl(C); 8314 const CXXConstructorDecl *Constructor = 8315 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8316 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0; 8317 } 8318 8319 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) { 8320 if (!clang_isDeclaration(C.kind)) 8321 return 0; 8322 8323 const Decl *D = cxcursor::getCursorDecl(C); 8324 const CXXConstructorDecl *Constructor = 8325 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8326 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0; 8327 } 8328 8329 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) { 8330 if (!clang_isDeclaration(C.kind)) 8331 return 0; 8332 8333 const Decl *D = cxcursor::getCursorDecl(C); 8334 const CXXConstructorDecl *Constructor = 8335 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8336 // Passing 'false' excludes constructors marked 'explicit'. 8337 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0; 8338 } 8339 8340 unsigned clang_CXXField_isMutable(CXCursor C) { 8341 if (!clang_isDeclaration(C.kind)) 8342 return 0; 8343 8344 if (const auto D = cxcursor::getCursorDecl(C)) 8345 if (const auto FD = dyn_cast_or_null<FieldDecl>(D)) 8346 return FD->isMutable() ? 1 : 0; 8347 return 0; 8348 } 8349 8350 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) { 8351 if (!clang_isDeclaration(C.kind)) 8352 return 0; 8353 8354 const Decl *D = cxcursor::getCursorDecl(C); 8355 const CXXMethodDecl *Method = 8356 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8357 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0; 8358 } 8359 8360 unsigned clang_CXXMethod_isConst(CXCursor C) { 8361 if (!clang_isDeclaration(C.kind)) 8362 return 0; 8363 8364 const Decl *D = cxcursor::getCursorDecl(C); 8365 const CXXMethodDecl *Method = 8366 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8367 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0; 8368 } 8369 8370 unsigned clang_CXXMethod_isDefaulted(CXCursor C) { 8371 if (!clang_isDeclaration(C.kind)) 8372 return 0; 8373 8374 const Decl *D = cxcursor::getCursorDecl(C); 8375 const CXXMethodDecl *Method = 8376 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8377 return (Method && Method->isDefaulted()) ? 1 : 0; 8378 } 8379 8380 unsigned clang_CXXMethod_isStatic(CXCursor C) { 8381 if (!clang_isDeclaration(C.kind)) 8382 return 0; 8383 8384 const Decl *D = cxcursor::getCursorDecl(C); 8385 const CXXMethodDecl *Method = 8386 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8387 return (Method && Method->isStatic()) ? 1 : 0; 8388 } 8389 8390 unsigned clang_CXXMethod_isVirtual(CXCursor C) { 8391 if (!clang_isDeclaration(C.kind)) 8392 return 0; 8393 8394 const Decl *D = cxcursor::getCursorDecl(C); 8395 const CXXMethodDecl *Method = 8396 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8397 return (Method && Method->isVirtual()) ? 1 : 0; 8398 } 8399 8400 unsigned clang_CXXRecord_isAbstract(CXCursor C) { 8401 if (!clang_isDeclaration(C.kind)) 8402 return 0; 8403 8404 const auto *D = cxcursor::getCursorDecl(C); 8405 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D); 8406 if (RD) 8407 RD = RD->getDefinition(); 8408 return (RD && RD->isAbstract()) ? 1 : 0; 8409 } 8410 8411 unsigned clang_EnumDecl_isScoped(CXCursor C) { 8412 if (!clang_isDeclaration(C.kind)) 8413 return 0; 8414 8415 const Decl *D = cxcursor::getCursorDecl(C); 8416 auto *Enum = dyn_cast_or_null<EnumDecl>(D); 8417 return (Enum && Enum->isScoped()) ? 1 : 0; 8418 } 8419 8420 //===----------------------------------------------------------------------===// 8421 // Attribute introspection. 8422 //===----------------------------------------------------------------------===// 8423 8424 CXType clang_getIBOutletCollectionType(CXCursor C) { 8425 if (C.kind != CXCursor_IBOutletCollectionAttr) 8426 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 8427 8428 const IBOutletCollectionAttr *A = 8429 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 8430 8431 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 8432 } 8433 8434 //===----------------------------------------------------------------------===// 8435 // Inspecting memory usage. 8436 //===----------------------------------------------------------------------===// 8437 8438 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 8439 8440 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 8441 enum CXTUResourceUsageKind k, 8442 unsigned long amount) { 8443 CXTUResourceUsageEntry entry = { k, amount }; 8444 entries.push_back(entry); 8445 } 8446 8447 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 8448 const char *str = ""; 8449 switch (kind) { 8450 case CXTUResourceUsage_AST: 8451 str = "ASTContext: expressions, declarations, and types"; 8452 break; 8453 case CXTUResourceUsage_Identifiers: 8454 str = "ASTContext: identifiers"; 8455 break; 8456 case CXTUResourceUsage_Selectors: 8457 str = "ASTContext: selectors"; 8458 break; 8459 case CXTUResourceUsage_GlobalCompletionResults: 8460 str = "Code completion: cached global results"; 8461 break; 8462 case CXTUResourceUsage_SourceManagerContentCache: 8463 str = "SourceManager: content cache allocator"; 8464 break; 8465 case CXTUResourceUsage_AST_SideTables: 8466 str = "ASTContext: side tables"; 8467 break; 8468 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 8469 str = "SourceManager: malloc'ed memory buffers"; 8470 break; 8471 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 8472 str = "SourceManager: mmap'ed memory buffers"; 8473 break; 8474 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 8475 str = "ExternalASTSource: malloc'ed memory buffers"; 8476 break; 8477 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 8478 str = "ExternalASTSource: mmap'ed memory buffers"; 8479 break; 8480 case CXTUResourceUsage_Preprocessor: 8481 str = "Preprocessor: malloc'ed memory"; 8482 break; 8483 case CXTUResourceUsage_PreprocessingRecord: 8484 str = "Preprocessor: PreprocessingRecord"; 8485 break; 8486 case CXTUResourceUsage_SourceManager_DataStructures: 8487 str = "SourceManager: data structures and tables"; 8488 break; 8489 case CXTUResourceUsage_Preprocessor_HeaderSearch: 8490 str = "Preprocessor: header search tables"; 8491 break; 8492 } 8493 return str; 8494 } 8495 8496 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 8497 if (isNotUsableTU(TU)) { 8498 LOG_BAD_TU(TU); 8499 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr }; 8500 return usage; 8501 } 8502 8503 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8504 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries()); 8505 ASTContext &astContext = astUnit->getASTContext(); 8506 8507 // How much memory is used by AST nodes and types? 8508 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, 8509 (unsigned long) astContext.getASTAllocatedMemory()); 8510 8511 // How much memory is used by identifiers? 8512 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, 8513 (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); 8514 8515 // How much memory is used for selectors? 8516 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, 8517 (unsigned long) astContext.Selectors.getTotalMemory()); 8518 8519 // How much memory is used by ASTContext's side tables? 8520 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables, 8521 (unsigned long) astContext.getSideTableAllocatedMemory()); 8522 8523 // How much memory is used for caching global code completion results? 8524 unsigned long completionBytes = 0; 8525 if (GlobalCodeCompletionAllocator *completionAllocator = 8526 astUnit->getCachedCompletionAllocator().get()) { 8527 completionBytes = completionAllocator->getTotalMemory(); 8528 } 8529 createCXTUResourceUsageEntry(*entries, 8530 CXTUResourceUsage_GlobalCompletionResults, 8531 completionBytes); 8532 8533 // How much memory is being used by SourceManager's content cache? 8534 createCXTUResourceUsageEntry(*entries, 8535 CXTUResourceUsage_SourceManagerContentCache, 8536 (unsigned long) astContext.getSourceManager().getContentCacheSize()); 8537 8538 // How much memory is being used by the MemoryBuffer's in SourceManager? 8539 const SourceManager::MemoryBufferSizes &srcBufs = 8540 astUnit->getSourceManager().getMemoryBufferSizes(); 8541 8542 createCXTUResourceUsageEntry(*entries, 8543 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 8544 (unsigned long) srcBufs.malloc_bytes); 8545 createCXTUResourceUsageEntry(*entries, 8546 CXTUResourceUsage_SourceManager_Membuffer_MMap, 8547 (unsigned long) srcBufs.mmap_bytes); 8548 createCXTUResourceUsageEntry(*entries, 8549 CXTUResourceUsage_SourceManager_DataStructures, 8550 (unsigned long) astContext.getSourceManager() 8551 .getDataStructureSizes()); 8552 8553 // How much memory is being used by the ExternalASTSource? 8554 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 8555 const ExternalASTSource::MemoryBufferSizes &sizes = 8556 esrc->getMemoryBufferSizes(); 8557 8558 createCXTUResourceUsageEntry(*entries, 8559 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 8560 (unsigned long) sizes.malloc_bytes); 8561 createCXTUResourceUsageEntry(*entries, 8562 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 8563 (unsigned long) sizes.mmap_bytes); 8564 } 8565 8566 // How much memory is being used by the Preprocessor? 8567 Preprocessor &pp = astUnit->getPreprocessor(); 8568 createCXTUResourceUsageEntry(*entries, 8569 CXTUResourceUsage_Preprocessor, 8570 pp.getTotalMemory()); 8571 8572 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 8573 createCXTUResourceUsageEntry(*entries, 8574 CXTUResourceUsage_PreprocessingRecord, 8575 pRec->getTotalMemory()); 8576 } 8577 8578 createCXTUResourceUsageEntry(*entries, 8579 CXTUResourceUsage_Preprocessor_HeaderSearch, 8580 pp.getHeaderSearchInfo().getTotalMemory()); 8581 8582 CXTUResourceUsage usage = { (void*) entries.get(), 8583 (unsigned) entries->size(), 8584 !entries->empty() ? &(*entries)[0] : nullptr }; 8585 (void)entries.release(); 8586 return usage; 8587 } 8588 8589 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 8590 if (usage.data) 8591 delete (MemUsageEntries*) usage.data; 8592 } 8593 8594 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) { 8595 CXSourceRangeList *skipped = new CXSourceRangeList; 8596 skipped->count = 0; 8597 skipped->ranges = nullptr; 8598 8599 if (isNotUsableTU(TU)) { 8600 LOG_BAD_TU(TU); 8601 return skipped; 8602 } 8603 8604 if (!file) 8605 return skipped; 8606 8607 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8608 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); 8609 if (!ppRec) 8610 return skipped; 8611 8612 ASTContext &Ctx = astUnit->getASTContext(); 8613 SourceManager &sm = Ctx.getSourceManager(); 8614 FileEntry *fileEntry = static_cast<FileEntry *>(file); 8615 FileID wantedFileID = sm.translateFile(fileEntry); 8616 bool isMainFile = wantedFileID == sm.getMainFileID(); 8617 8618 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8619 std::vector<SourceRange> wantedRanges; 8620 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end(); 8621 i != ei; ++i) { 8622 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID) 8623 wantedRanges.push_back(*i); 8624 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd()))) 8625 wantedRanges.push_back(*i); 8626 } 8627 8628 skipped->count = wantedRanges.size(); 8629 skipped->ranges = new CXSourceRange[skipped->count]; 8630 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8631 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]); 8632 8633 return skipped; 8634 } 8635 8636 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) { 8637 CXSourceRangeList *skipped = new CXSourceRangeList; 8638 skipped->count = 0; 8639 skipped->ranges = nullptr; 8640 8641 if (isNotUsableTU(TU)) { 8642 LOG_BAD_TU(TU); 8643 return skipped; 8644 } 8645 8646 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8647 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); 8648 if (!ppRec) 8649 return skipped; 8650 8651 ASTContext &Ctx = astUnit->getASTContext(); 8652 8653 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8654 8655 skipped->count = SkippedRanges.size(); 8656 skipped->ranges = new CXSourceRange[skipped->count]; 8657 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8658 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]); 8659 8660 return skipped; 8661 } 8662 8663 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) { 8664 if (ranges) { 8665 delete[] ranges->ranges; 8666 delete ranges; 8667 } 8668 } 8669 8670 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 8671 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 8672 for (unsigned I = 0; I != Usage.numEntries; ++I) 8673 fprintf(stderr, " %s: %lu\n", 8674 clang_getTUResourceUsageName(Usage.entries[I].kind), 8675 Usage.entries[I].amount); 8676 8677 clang_disposeCXTUResourceUsage(Usage); 8678 } 8679 8680 //===----------------------------------------------------------------------===// 8681 // Misc. utility functions. 8682 //===----------------------------------------------------------------------===// 8683 8684 /// Default to using our desired 8 MB stack size on "safety" threads. 8685 static unsigned SafetyStackThreadSize = DesiredStackSize; 8686 8687 namespace clang { 8688 8689 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn, 8690 unsigned Size) { 8691 if (!Size) 8692 Size = GetSafetyThreadStackSize(); 8693 if (Size && !getenv("LIBCLANG_NOTHREADS")) 8694 return CRC.RunSafelyOnThread(Fn, Size); 8695 return CRC.RunSafely(Fn); 8696 } 8697 8698 unsigned GetSafetyThreadStackSize() { 8699 return SafetyStackThreadSize; 8700 } 8701 8702 void SetSafetyThreadStackSize(unsigned Value) { 8703 SafetyStackThreadSize = Value; 8704 } 8705 8706 } 8707 8708 void clang::setThreadBackgroundPriority() { 8709 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 8710 return; 8711 8712 #ifdef USE_DARWIN_THREADS 8713 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); 8714 #endif 8715 } 8716 8717 void cxindex::printDiagsToStderr(ASTUnit *Unit) { 8718 if (!Unit) 8719 return; 8720 8721 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 8722 DEnd = Unit->stored_diag_end(); 8723 D != DEnd; ++D) { 8724 CXStoredDiagnostic Diag(*D, Unit->getLangOpts()); 8725 CXString Msg = clang_formatDiagnostic(&Diag, 8726 clang_defaultDiagnosticDisplayOptions()); 8727 fprintf(stderr, "%s\n", clang_getCString(Msg)); 8728 clang_disposeString(Msg); 8729 } 8730 #ifdef _WIN32 8731 // On Windows, force a flush, since there may be multiple copies of 8732 // stderr and stdout in the file system, all with different buffers 8733 // but writing to the same device. 8734 fflush(stderr); 8735 #endif 8736 } 8737 8738 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, 8739 SourceLocation MacroDefLoc, 8740 CXTranslationUnit TU){ 8741 if (MacroDefLoc.isInvalid() || !TU) 8742 return nullptr; 8743 if (!II.hadMacroDefinition()) 8744 return nullptr; 8745 8746 ASTUnit *Unit = cxtu::getASTUnit(TU); 8747 Preprocessor &PP = Unit->getPreprocessor(); 8748 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II); 8749 if (MD) { 8750 for (MacroDirective::DefInfo 8751 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) { 8752 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc()) 8753 return Def.getMacroInfo(); 8754 } 8755 } 8756 8757 return nullptr; 8758 } 8759 8760 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef, 8761 CXTranslationUnit TU) { 8762 if (!MacroDef || !TU) 8763 return nullptr; 8764 const IdentifierInfo *II = MacroDef->getName(); 8765 if (!II) 8766 return nullptr; 8767 8768 return getMacroInfo(*II, MacroDef->getLocation(), TU); 8769 } 8770 8771 MacroDefinitionRecord * 8772 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, 8773 CXTranslationUnit TU) { 8774 if (!MI || !TU) 8775 return nullptr; 8776 if (Tok.isNot(tok::raw_identifier)) 8777 return nullptr; 8778 8779 if (MI->getNumTokens() == 0) 8780 return nullptr; 8781 SourceRange DefRange(MI->getReplacementToken(0).getLocation(), 8782 MI->getDefinitionEndLoc()); 8783 ASTUnit *Unit = cxtu::getASTUnit(TU); 8784 8785 // Check that the token is inside the definition and not its argument list. 8786 SourceManager &SM = Unit->getSourceManager(); 8787 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) 8788 return nullptr; 8789 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) 8790 return nullptr; 8791 8792 Preprocessor &PP = Unit->getPreprocessor(); 8793 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 8794 if (!PPRec) 8795 return nullptr; 8796 8797 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); 8798 if (!II.hadMacroDefinition()) 8799 return nullptr; 8800 8801 // Check that the identifier is not one of the macro arguments. 8802 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end()) 8803 return nullptr; 8804 8805 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II); 8806 if (!InnerMD) 8807 return nullptr; 8808 8809 return PPRec->findMacroDefinition(InnerMD->getMacroInfo()); 8810 } 8811 8812 MacroDefinitionRecord * 8813 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, 8814 CXTranslationUnit TU) { 8815 if (Loc.isInvalid() || !MI || !TU) 8816 return nullptr; 8817 8818 if (MI->getNumTokens() == 0) 8819 return nullptr; 8820 ASTUnit *Unit = cxtu::getASTUnit(TU); 8821 Preprocessor &PP = Unit->getPreprocessor(); 8822 if (!PP.getPreprocessingRecord()) 8823 return nullptr; 8824 Loc = Unit->getSourceManager().getSpellingLoc(Loc); 8825 Token Tok; 8826 if (PP.getRawToken(Loc, Tok)) 8827 return nullptr; 8828 8829 return checkForMacroInMacroDefinition(MI, Tok, TU); 8830 } 8831 8832 CXString clang_getClangVersion() { 8833 return cxstring::createDup(getClangFullVersion()); 8834 } 8835 8836 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { 8837 if (TU) { 8838 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) { 8839 LogOS << '<' << Unit->getMainFileName() << '>'; 8840 if (Unit->isMainFileAST()) 8841 LogOS << " (" << Unit->getASTFileName() << ')'; 8842 return *this; 8843 } 8844 } else { 8845 LogOS << "<NULL TU>"; 8846 } 8847 return *this; 8848 } 8849 8850 Logger &cxindex::Logger::operator<<(const FileEntry *FE) { 8851 *this << FE->getName(); 8852 return *this; 8853 } 8854 8855 Logger &cxindex::Logger::operator<<(CXCursor cursor) { 8856 CXString cursorName = clang_getCursorDisplayName(cursor); 8857 *this << cursorName << "@" << clang_getCursorLocation(cursor); 8858 clang_disposeString(cursorName); 8859 return *this; 8860 } 8861 8862 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { 8863 CXFile File; 8864 unsigned Line, Column; 8865 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr); 8866 CXString FileName = clang_getFileName(File); 8867 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); 8868 clang_disposeString(FileName); 8869 return *this; 8870 } 8871 8872 Logger &cxindex::Logger::operator<<(CXSourceRange range) { 8873 CXSourceLocation BLoc = clang_getRangeStart(range); 8874 CXSourceLocation ELoc = clang_getRangeEnd(range); 8875 8876 CXFile BFile; 8877 unsigned BLine, BColumn; 8878 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr); 8879 8880 CXFile EFile; 8881 unsigned ELine, EColumn; 8882 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr); 8883 8884 CXString BFileName = clang_getFileName(BFile); 8885 if (BFile == EFile) { 8886 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), 8887 BLine, BColumn, ELine, EColumn); 8888 } else { 8889 CXString EFileName = clang_getFileName(EFile); 8890 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), 8891 BLine, BColumn) 8892 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), 8893 ELine, EColumn); 8894 clang_disposeString(EFileName); 8895 } 8896 clang_disposeString(BFileName); 8897 return *this; 8898 } 8899 8900 Logger &cxindex::Logger::operator<<(CXString Str) { 8901 *this << clang_getCString(Str); 8902 return *this; 8903 } 8904 8905 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { 8906 LogOS << Fmt; 8907 return *this; 8908 } 8909 8910 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex; 8911 8912 cxindex::Logger::~Logger() { 8913 llvm::sys::ScopedLock L(*LoggingMutex); 8914 8915 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); 8916 8917 raw_ostream &OS = llvm::errs(); 8918 OS << "[libclang:" << Name << ':'; 8919 8920 #ifdef USE_DARWIN_THREADS 8921 // TODO: Portability. 8922 mach_port_t tid = pthread_mach_thread_np(pthread_self()); 8923 OS << tid << ':'; 8924 #endif 8925 8926 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); 8927 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); 8928 OS << Msg << '\n'; 8929 8930 if (Trace) { 8931 llvm::sys::PrintStackTrace(OS); 8932 OS << "--------------------------------------------------\n"; 8933 } 8934 } 8935 8936 #ifdef CLANG_TOOL_EXTRA_BUILD 8937 // This anchor is used to force the linker to link the clang-tidy plugin. 8938 extern volatile int ClangTidyPluginAnchorSource; 8939 static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination = 8940 ClangTidyPluginAnchorSource; 8941 8942 // This anchor is used to force the linker to link the clang-include-fixer 8943 // plugin. 8944 extern volatile int ClangIncludeFixerPluginAnchorSource; 8945 static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination = 8946 ClangIncludeFixerPluginAnchorSource; 8947 #endif 8948