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