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