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