Indexing.cpp revision 95c579cae01118eadd311d445ff7f491d0011fb0
1//===- CIndexHigh.cpp - Higher level API functions ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "IndexingContext.h" 11#include "CXCursor.h" 12#include "CXSourceLocation.h" 13#include "CXTranslationUnit.h" 14#include "CXString.h" 15#include "CIndexDiagnostic.h" 16#include "CIndexer.h" 17 18#include "clang/Frontend/ASTUnit.h" 19#include "clang/Frontend/CompilerInvocation.h" 20#include "clang/Frontend/CompilerInstance.h" 21#include "clang/Frontend/FrontendAction.h" 22#include "clang/Frontend/Utils.h" 23#include "clang/Sema/SemaConsumer.h" 24#include "clang/AST/ASTConsumer.h" 25#include "clang/AST/DeclVisitor.h" 26#include "clang/Lex/Preprocessor.h" 27#include "clang/Lex/PPCallbacks.h" 28#include "llvm/Support/MemoryBuffer.h" 29#include "llvm/Support/CrashRecoveryContext.h" 30 31using namespace clang; 32using namespace cxstring; 33using namespace cxtu; 34using namespace cxindex; 35 36static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx); 37 38namespace { 39 40//===----------------------------------------------------------------------===// 41// IndexPPCallbacks 42//===----------------------------------------------------------------------===// 43 44class IndexPPCallbacks : public PPCallbacks { 45 Preprocessor &PP; 46 IndexingContext &IndexCtx; 47 bool IsMainFileEntered; 48 49public: 50 IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx) 51 : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { } 52 53 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 54 SrcMgr::CharacteristicKind FileType, FileID PrevFID) { 55 if (IsMainFileEntered) 56 return; 57 58 SourceManager &SM = PP.getSourceManager(); 59 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID()); 60 61 if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) { 62 IsMainFileEntered = true; 63 IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID())); 64 } 65 } 66 67 virtual void InclusionDirective(SourceLocation HashLoc, 68 const Token &IncludeTok, 69 StringRef FileName, 70 bool IsAngled, 71 CharSourceRange FilenameRange, 72 const FileEntry *File, 73 StringRef SearchPath, 74 StringRef RelativePath, 75 const Module *Imported) { 76 if (Imported) { 77 IndexCtx.importedModule(HashLoc, FileName, /*isIncludeDirective=*/true, 78 Imported); 79 return; 80 } 81 82 bool isImport = (IncludeTok.is(tok::identifier) && 83 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import); 84 IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled); 85 } 86 87 /// MacroDefined - This hook is called whenever a macro definition is seen. 88 virtual void MacroDefined(const Token &Id, const MacroInfo *MI) { 89 } 90 91 /// MacroUndefined - This hook is called whenever a macro #undef is seen. 92 /// MI is released immediately following this callback. 93 virtual void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI) { 94 } 95 96 /// MacroExpands - This is called by when a macro invocation is found. 97 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI, 98 SourceRange Range) { 99 } 100 101 /// SourceRangeSkipped - This hook is called when a source range is skipped. 102 /// \param Range The SourceRange that was skipped. The range begins at the 103 /// #if/#else directive and ends after the #endif/#else directive. 104 virtual void SourceRangeSkipped(SourceRange Range) { 105 } 106}; 107 108//===----------------------------------------------------------------------===// 109// IndexingConsumer 110//===----------------------------------------------------------------------===// 111 112class IndexingConsumer : public ASTConsumer { 113 IndexingContext &IndexCtx; 114 115public: 116 explicit IndexingConsumer(IndexingContext &indexCtx) 117 : IndexCtx(indexCtx) { } 118 119 // ASTConsumer Implementation 120 121 virtual void Initialize(ASTContext &Context) { 122 IndexCtx.setASTContext(Context); 123 IndexCtx.startedTranslationUnit(); 124 } 125 126 virtual void HandleTranslationUnit(ASTContext &Ctx) { 127 } 128 129 virtual bool HandleTopLevelDecl(DeclGroupRef DG) { 130 IndexCtx.indexDeclGroupRef(DG); 131 return !IndexCtx.shouldAbort(); 132 } 133 134 /// \brief Handle the specified top-level declaration that occurred inside 135 /// and ObjC container. 136 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) { 137 // They will be handled after the interface is seen first. 138 IndexCtx.addTUDeclInObjCContainer(D); 139 } 140 141 /// \brief This is called by the AST reader when deserializing things. 142 /// The default implementation forwards to HandleTopLevelDecl but we don't 143 /// care about them when indexing, so have an empty definition. 144 virtual void HandleInterestingDecl(DeclGroupRef D) {} 145 146 virtual void HandleTagDeclDefinition(TagDecl *D) { 147 if (!IndexCtx.shouldIndexImplicitTemplateInsts()) 148 return; 149 150 if (IndexCtx.isTemplateImplicitInstantiation(D)) 151 IndexCtx.indexDecl(D); 152 } 153 154 virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { 155 if (!IndexCtx.shouldIndexImplicitTemplateInsts()) 156 return; 157 158 IndexCtx.indexDecl(D); 159 } 160}; 161 162//===----------------------------------------------------------------------===// 163// CaptureDiagnosticConsumer 164//===----------------------------------------------------------------------===// 165 166class CaptureDiagnosticConsumer : public DiagnosticConsumer { 167 SmallVector<StoredDiagnostic, 4> Errors; 168public: 169 170 virtual void HandleDiagnostic(DiagnosticsEngine::Level level, 171 const Diagnostic &Info) { 172 if (level >= DiagnosticsEngine::Error) 173 Errors.push_back(StoredDiagnostic(level, Info)); 174 } 175 176 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 177 return new IgnoringDiagConsumer(); 178 } 179}; 180 181//===----------------------------------------------------------------------===// 182// IndexingFrontendAction 183//===----------------------------------------------------------------------===// 184 185class IndexingFrontendAction : public ASTFrontendAction { 186 IndexingContext IndexCtx; 187 CXTranslationUnit CXTU; 188 189public: 190 IndexingFrontendAction(CXClientData clientData, 191 IndexerCallbacks &indexCallbacks, 192 unsigned indexOptions, 193 CXTranslationUnit cxTU) 194 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU), 195 CXTU(cxTU), EnablePPDetailedRecordForModules(false) { } 196 197 bool EnablePPDetailedRecordForModules; 198 199 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 200 StringRef InFile) { 201 // We usually disable the preprocessing record for indexing even if the 202 // original preprocessing options had it enabled. Now that the indexing 203 // Preprocessor has been created (without a preprocessing record), re-enable 204 // the option in case modules are enabled, so that the detailed record 205 // option can be propagated when the module file is generated. 206 if (CI.getLangOpts().Modules && EnablePPDetailedRecordForModules) 207 CI.getPreprocessorOpts().DetailedRecord = true; 208 209 IndexCtx.setASTContext(CI.getASTContext()); 210 Preprocessor &PP = CI.getPreprocessor(); 211 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx)); 212 IndexCtx.setPreprocessor(PP); 213 return new IndexingConsumer(IndexCtx); 214 } 215 216 virtual void EndSourceFileAction() { 217 indexDiagnostics(CXTU, IndexCtx); 218 } 219 220 virtual TranslationUnitKind getTranslationUnitKind() { 221 if (IndexCtx.shouldIndexImplicitTemplateInsts()) 222 return TU_Complete; 223 else 224 return TU_Prefix; 225 } 226 virtual bool hasCodeCompletionSupport() const { return false; } 227}; 228 229//===----------------------------------------------------------------------===// 230// clang_indexSourceFileUnit Implementation 231//===----------------------------------------------------------------------===// 232 233struct IndexSourceFileInfo { 234 CXIndexAction idxAction; 235 CXClientData client_data; 236 IndexerCallbacks *index_callbacks; 237 unsigned index_callbacks_size; 238 unsigned index_options; 239 const char *source_filename; 240 const char *const *command_line_args; 241 int num_command_line_args; 242 struct CXUnsavedFile *unsaved_files; 243 unsigned num_unsaved_files; 244 CXTranslationUnit *out_TU; 245 unsigned TU_options; 246 int result; 247}; 248 249struct MemBufferOwner { 250 SmallVector<const llvm::MemoryBuffer *, 8> Buffers; 251 252 ~MemBufferOwner() { 253 for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator 254 I = Buffers.begin(), E = Buffers.end(); I != E; ++I) 255 delete *I; 256 } 257}; 258 259} // anonymous namespace 260 261static void clang_indexSourceFile_Impl(void *UserData) { 262 IndexSourceFileInfo *ITUI = 263 static_cast<IndexSourceFileInfo*>(UserData); 264 CXIndex CIdx = (CXIndex)ITUI->idxAction; 265 CXClientData client_data = ITUI->client_data; 266 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; 267 unsigned index_callbacks_size = ITUI->index_callbacks_size; 268 unsigned index_options = ITUI->index_options; 269 const char *source_filename = ITUI->source_filename; 270 const char * const *command_line_args = ITUI->command_line_args; 271 int num_command_line_args = ITUI->num_command_line_args; 272 struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files; 273 unsigned num_unsaved_files = ITUI->num_unsaved_files; 274 CXTranslationUnit *out_TU = ITUI->out_TU; 275 unsigned TU_options = ITUI->TU_options; 276 ITUI->result = 1; // init as error. 277 278 if (out_TU) 279 *out_TU = 0; 280 bool requestedToGetTU = (out_TU != 0); 281 282 if (!CIdx) 283 return; 284 if (!client_index_callbacks || index_callbacks_size == 0) 285 return; 286 287 IndexerCallbacks CB; 288 memset(&CB, 0, sizeof(CB)); 289 unsigned ClientCBSize = index_callbacks_size < sizeof(CB) 290 ? index_callbacks_size : sizeof(CB); 291 memcpy(&CB, client_index_callbacks, ClientCBSize); 292 293 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 294 295 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 296 setThreadBackgroundPriority(); 297 298 CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer(); 299 300 // Configure the diagnostics. 301 DiagnosticOptions DiagOpts; 302 IntrusiveRefCntPtr<DiagnosticsEngine> 303 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args, 304 command_line_args, 305 CaptureDiag, 306 /*ShouldOwnClient=*/true, 307 /*ShouldCloneClient=*/false)); 308 309 // Recover resources if we crash before exiting this function. 310 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 311 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 312 DiagCleanup(Diags.getPtr()); 313 314 OwningPtr<std::vector<const char *> > 315 Args(new std::vector<const char*>()); 316 317 // Recover resources if we crash before exiting this method. 318 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 319 ArgsCleanup(Args.get()); 320 321 Args->insert(Args->end(), command_line_args, 322 command_line_args + num_command_line_args); 323 324 // The 'source_filename' argument is optional. If the caller does not 325 // specify it then it is assumed that the source file is specified 326 // in the actual argument list. 327 // Put the source file after command_line_args otherwise if '-x' flag is 328 // present it will be unused. 329 if (source_filename) 330 Args->push_back(source_filename); 331 332 IntrusiveRefCntPtr<CompilerInvocation> 333 CInvok(createInvocationFromCommandLine(*Args, Diags)); 334 335 if (!CInvok) 336 return; 337 338 // Recover resources if we crash before exiting this function. 339 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation, 340 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> > 341 CInvokCleanup(CInvok.getPtr()); 342 343 if (CInvok->getFrontendOpts().Inputs.empty()) 344 return; 345 346 OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner()); 347 348 // Recover resources if we crash before exiting this method. 349 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> 350 BufOwnerCleanup(BufOwner.get()); 351 352 for (unsigned I = 0; I != num_unsaved_files; ++I) { 353 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 354 const llvm::MemoryBuffer *Buffer 355 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 356 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer); 357 BufOwner->Buffers.push_back(Buffer); 358 } 359 360 // Since libclang is primarily used by batch tools dealing with 361 // (often very broken) source code, where spell-checking can have a 362 // significant negative impact on performance (particularly when 363 // precompiled headers are involved), we disable it. 364 CInvok->getLangOpts()->SpellChecking = false; 365 366 if (index_options & CXIndexOpt_SuppressWarnings) 367 CInvok->getDiagnosticOpts().IgnoreWarnings = true; 368 369 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags, 370 /*CaptureDiagnostics=*/true, 371 /*UserFilesAreVolatile=*/true); 372 OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit))); 373 374 // Recover resources if we crash before exiting this method. 375 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner> 376 CXTUCleanup(CXTU.get()); 377 378 OwningPtr<IndexingFrontendAction> IndexAction; 379 IndexAction.reset(new IndexingFrontendAction(client_data, CB, 380 index_options, CXTU->getTU())); 381 382 // Recover resources if we crash before exiting this method. 383 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction> 384 IndexActionCleanup(IndexAction.get()); 385 386 bool Persistent = requestedToGetTU; 387 bool OnlyLocalDecls = false; 388 bool PrecompilePreamble = false; 389 bool CacheCodeCompletionResults = false; 390 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts(); 391 PPOpts.AllowPCHWithCompilerErrors = true; 392 393 if (requestedToGetTU) { 394 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls(); 395 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble; 396 // FIXME: Add a flag for modules. 397 CacheCodeCompletionResults 398 = TU_options & CXTranslationUnit_CacheCompletionResults; 399 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) { 400 PPOpts.DetailedRecord = true; 401 } 402 } 403 404 IndexAction->EnablePPDetailedRecordForModules 405 = PPOpts.DetailedRecord || 406 (TU_options & CXTranslationUnit_DetailedPreprocessingRecord); 407 408 if (!requestedToGetTU) 409 PPOpts.DetailedRecord = false; 410 411 DiagnosticErrorTrap DiagTrap(*Diags); 412 bool Success = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags, 413 IndexAction.get(), 414 Unit, 415 Persistent, 416 CXXIdx->getClangResourcesPath(), 417 OnlyLocalDecls, 418 /*CaptureDiagnostics=*/true, 419 PrecompilePreamble, 420 CacheCodeCompletionResults, 421 /*IncludeBriefCommentsInCodeCompletion=*/false, 422 /*UserFilesAreVolatile=*/true); 423 if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics()) 424 printDiagsToStderr(Unit); 425 426 if (!Success) 427 return; 428 429 if (out_TU) 430 *out_TU = CXTU->takeTU(); 431 432 ITUI->result = 0; // success. 433} 434 435//===----------------------------------------------------------------------===// 436// clang_indexTranslationUnit Implementation 437//===----------------------------------------------------------------------===// 438 439namespace { 440 441struct IndexTranslationUnitInfo { 442 CXIndexAction idxAction; 443 CXClientData client_data; 444 IndexerCallbacks *index_callbacks; 445 unsigned index_callbacks_size; 446 unsigned index_options; 447 CXTranslationUnit TU; 448 int result; 449}; 450 451} // anonymous namespace 452 453static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) { 454 Preprocessor &PP = Unit.getPreprocessor(); 455 if (!PP.getPreprocessingRecord()) 456 return; 457 458 // FIXME: Only deserialize inclusion directives. 459 460 PreprocessingRecord::iterator I, E; 461 llvm::tie(I, E) = Unit.getLocalPreprocessingEntities(); 462 463 for (; I != E; ++I) { 464 PreprocessedEntity *PPE = *I; 465 466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 467 if (!ID->importedModule()) 468 IdxCtx.ppIncludedFile(ID->getSourceRange().getBegin(),ID->getFileName(), 469 ID->getFile(), ID->getKind() == InclusionDirective::Import, 470 !ID->wasInQuotes()); 471 } 472 } 473} 474 475static bool topLevelDeclVisitor(void *context, const Decl *D) { 476 IndexingContext &IdxCtx = *static_cast<IndexingContext*>(context); 477 IdxCtx.indexTopLevelDecl(D); 478 if (IdxCtx.shouldAbort()) 479 return false; 480 return true; 481} 482 483static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) { 484 Unit.visitLocalTopLevelDecls(&IdxCtx, topLevelDeclVisitor); 485} 486 487static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) { 488 if (!IdxCtx.hasDiagnosticCallback()) 489 return; 490 491 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU); 492 IdxCtx.handleDiagnosticSet(DiagSet); 493} 494 495static void clang_indexTranslationUnit_Impl(void *UserData) { 496 IndexTranslationUnitInfo *ITUI = 497 static_cast<IndexTranslationUnitInfo*>(UserData); 498 CXTranslationUnit TU = ITUI->TU; 499 CXClientData client_data = ITUI->client_data; 500 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; 501 unsigned index_callbacks_size = ITUI->index_callbacks_size; 502 unsigned index_options = ITUI->index_options; 503 ITUI->result = 1; // init as error. 504 505 if (!TU) 506 return; 507 if (!client_index_callbacks || index_callbacks_size == 0) 508 return; 509 510 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 511 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 512 setThreadBackgroundPriority(); 513 514 IndexerCallbacks CB; 515 memset(&CB, 0, sizeof(CB)); 516 unsigned ClientCBSize = index_callbacks_size < sizeof(CB) 517 ? index_callbacks_size : sizeof(CB); 518 memcpy(&CB, client_index_callbacks, ClientCBSize); 519 520 OwningPtr<IndexingContext> IndexCtx; 521 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU)); 522 523 // Recover resources if we crash before exiting this method. 524 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext> 525 IndexCtxCleanup(IndexCtx.get()); 526 527 OwningPtr<IndexingConsumer> IndexConsumer; 528 IndexConsumer.reset(new IndexingConsumer(*IndexCtx)); 529 530 // Recover resources if we crash before exiting this method. 531 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer> 532 IndexConsumerCleanup(IndexConsumer.get()); 533 534 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 535 if (!Unit) 536 return; 537 538 ASTUnit::ConcurrencyCheck Check(*Unit); 539 540 FileManager &FileMgr = Unit->getFileManager(); 541 542 if (Unit->getOriginalSourceFileName().empty()) 543 IndexCtx->enteredMainFile(0); 544 else 545 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName())); 546 547 IndexConsumer->Initialize(Unit->getASTContext()); 548 549 indexPreprocessingRecord(*Unit, *IndexCtx); 550 indexTranslationUnit(*Unit, *IndexCtx); 551 indexDiagnostics(TU, *IndexCtx); 552 553 ITUI->result = 0; 554} 555 556//===----------------------------------------------------------------------===// 557// libclang public APIs. 558//===----------------------------------------------------------------------===// 559 560extern "C" { 561 562int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) { 563 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory; 564} 565 566const CXIdxObjCContainerDeclInfo * 567clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) { 568 if (!DInfo) 569 return 0; 570 571 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 572 if (const ObjCContainerDeclInfo * 573 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI)) 574 return &ContInfo->ObjCContDeclInfo; 575 576 return 0; 577} 578 579const CXIdxObjCInterfaceDeclInfo * 580clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) { 581 if (!DInfo) 582 return 0; 583 584 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 585 if (const ObjCInterfaceDeclInfo * 586 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 587 return &InterInfo->ObjCInterDeclInfo; 588 589 return 0; 590} 591 592const CXIdxObjCCategoryDeclInfo * 593clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){ 594 if (!DInfo) 595 return 0; 596 597 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 598 if (const ObjCCategoryDeclInfo * 599 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 600 return &CatInfo->ObjCCatDeclInfo; 601 602 return 0; 603} 604 605const CXIdxObjCProtocolRefListInfo * 606clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) { 607 if (!DInfo) 608 return 0; 609 610 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 611 612 if (const ObjCInterfaceDeclInfo * 613 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 614 return InterInfo->ObjCInterDeclInfo.protocols; 615 616 if (const ObjCProtocolDeclInfo * 617 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI)) 618 return &ProtInfo->ObjCProtoRefListInfo; 619 620 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 621 return CatInfo->ObjCCatDeclInfo.protocols; 622 623 return 0; 624} 625 626const CXIdxObjCPropertyDeclInfo * 627clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) { 628 if (!DInfo) 629 return 0; 630 631 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 632 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI)) 633 return &PropInfo->ObjCPropDeclInfo; 634 635 return 0; 636} 637 638const CXIdxIBOutletCollectionAttrInfo * 639clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) { 640 if (!AInfo) 641 return 0; 642 643 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo); 644 if (const IBOutletCollectionInfo * 645 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI)) 646 return &IBInfo->IBCollInfo; 647 648 return 0; 649} 650 651const CXIdxCXXClassDeclInfo * 652clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) { 653 if (!DInfo) 654 return 0; 655 656 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 657 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI)) 658 return &ClassInfo->CXXClassInfo; 659 660 return 0; 661} 662 663CXIdxClientContainer 664clang_index_getClientContainer(const CXIdxContainerInfo *info) { 665 if (!info) 666 return 0; 667 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 668 return Container->IndexCtx->getClientContainerForDC(Container->DC); 669} 670 671void clang_index_setClientContainer(const CXIdxContainerInfo *info, 672 CXIdxClientContainer client) { 673 if (!info) 674 return; 675 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 676 Container->IndexCtx->addContainerInMap(Container->DC, client); 677} 678 679CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) { 680 if (!info) 681 return 0; 682 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 683 return Entity->IndexCtx->getClientEntity(Entity->Dcl); 684} 685 686void clang_index_setClientEntity(const CXIdxEntityInfo *info, 687 CXIdxClientEntity client) { 688 if (!info) 689 return; 690 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 691 Entity->IndexCtx->setClientEntity(Entity->Dcl, client); 692} 693 694CXIndexAction clang_IndexAction_create(CXIndex CIdx) { 695 // For now, CXIndexAction is featureless. 696 return CIdx; 697} 698 699void clang_IndexAction_dispose(CXIndexAction idxAction) { 700 // For now, CXIndexAction is featureless. 701} 702 703int clang_indexSourceFile(CXIndexAction idxAction, 704 CXClientData client_data, 705 IndexerCallbacks *index_callbacks, 706 unsigned index_callbacks_size, 707 unsigned index_options, 708 const char *source_filename, 709 const char * const *command_line_args, 710 int num_command_line_args, 711 struct CXUnsavedFile *unsaved_files, 712 unsigned num_unsaved_files, 713 CXTranslationUnit *out_TU, 714 unsigned TU_options) { 715 716 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks, 717 index_callbacks_size, index_options, 718 source_filename, command_line_args, 719 num_command_line_args, unsaved_files, 720 num_unsaved_files, out_TU, TU_options, 0 }; 721 722 if (getenv("LIBCLANG_NOTHREADS")) { 723 clang_indexSourceFile_Impl(&ITUI); 724 return ITUI.result; 725 } 726 727 llvm::CrashRecoveryContext CRC; 728 729 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) { 730 fprintf(stderr, "libclang: crash detected during indexing source file: {\n"); 731 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 732 fprintf(stderr, " 'command_line_args' : ["); 733 for (int i = 0; i != num_command_line_args; ++i) { 734 if (i) 735 fprintf(stderr, ", "); 736 fprintf(stderr, "'%s'", command_line_args[i]); 737 } 738 fprintf(stderr, "],\n"); 739 fprintf(stderr, " 'unsaved_files' : ["); 740 for (unsigned i = 0; i != num_unsaved_files; ++i) { 741 if (i) 742 fprintf(stderr, ", "); 743 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 744 unsaved_files[i].Length); 745 } 746 fprintf(stderr, "],\n"); 747 fprintf(stderr, " 'options' : %d,\n", TU_options); 748 fprintf(stderr, "}\n"); 749 750 return 1; 751 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 752 if (out_TU) 753 PrintLibclangResourceUsage(*out_TU); 754 } 755 756 return ITUI.result; 757} 758 759int clang_indexTranslationUnit(CXIndexAction idxAction, 760 CXClientData client_data, 761 IndexerCallbacks *index_callbacks, 762 unsigned index_callbacks_size, 763 unsigned index_options, 764 CXTranslationUnit TU) { 765 766 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks, 767 index_callbacks_size, index_options, TU, 768 0 }; 769 770 if (getenv("LIBCLANG_NOTHREADS")) { 771 clang_indexTranslationUnit_Impl(&ITUI); 772 return ITUI.result; 773 } 774 775 llvm::CrashRecoveryContext CRC; 776 777 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) { 778 fprintf(stderr, "libclang: crash detected during indexing TU\n"); 779 780 return 1; 781 } 782 783 return ITUI.result; 784} 785 786void clang_indexLoc_getFileLocation(CXIdxLoc location, 787 CXIdxClientFile *indexFile, 788 CXFile *file, 789 unsigned *line, 790 unsigned *column, 791 unsigned *offset) { 792 if (indexFile) *indexFile = 0; 793 if (file) *file = 0; 794 if (line) *line = 0; 795 if (column) *column = 0; 796 if (offset) *offset = 0; 797 798 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 799 if (!location.ptr_data[0] || Loc.isInvalid()) 800 return; 801 802 IndexingContext &IndexCtx = 803 *static_cast<IndexingContext*>(location.ptr_data[0]); 804 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset); 805} 806 807CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) { 808 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 809 if (!location.ptr_data[0] || Loc.isInvalid()) 810 return clang_getNullLocation(); 811 812 IndexingContext &IndexCtx = 813 *static_cast<IndexingContext*>(location.ptr_data[0]); 814 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc); 815} 816 817} // end: extern "C" 818 819