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