Indexing.cpp revision 3fe97781ad5f31dbfd9348c9488b93a7c01d7818
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 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 459 460 // FIXME: Only deserialize inclusion directives. 461 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module 462 // that it depends on. 463 464 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls(); 465 PreprocessingRecord::iterator I, E; 466 if (OnlyLocal) { 467 I = PPRec.local_begin(); 468 E = PPRec.local_end(); 469 } else { 470 I = PPRec.begin(); 471 E = PPRec.end(); 472 } 473 474 for (; I != E; ++I) { 475 PreprocessedEntity *PPE = *I; 476 477 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 478 IdxCtx.ppIncludedFile(ID->getSourceRange().getBegin(), ID->getFileName(), 479 ID->getFile(), ID->getKind() == InclusionDirective::Import, 480 !ID->wasInQuotes()); 481 } 482 } 483} 484 485static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) { 486 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module 487 // that it depends on. 488 489 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls(); 490 491 if (OnlyLocal) { 492 for (ASTUnit::top_level_iterator TL = Unit.top_level_begin(), 493 TLEnd = Unit.top_level_end(); 494 TL != TLEnd; ++TL) { 495 IdxCtx.indexTopLevelDecl(*TL); 496 if (IdxCtx.shouldAbort()) 497 return; 498 } 499 500 } else { 501 TranslationUnitDecl *TUDecl = Unit.getASTContext().getTranslationUnitDecl(); 502 for (TranslationUnitDecl::decl_iterator 503 I = TUDecl->decls_begin(), E = TUDecl->decls_end(); I != E; ++I) { 504 IdxCtx.indexTopLevelDecl(*I); 505 if (IdxCtx.shouldAbort()) 506 return; 507 } 508 } 509} 510 511static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) { 512 if (!IdxCtx.hasDiagnosticCallback()) 513 return; 514 515 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU); 516 IdxCtx.handleDiagnosticSet(DiagSet); 517} 518 519static void clang_indexTranslationUnit_Impl(void *UserData) { 520 IndexTranslationUnitInfo *ITUI = 521 static_cast<IndexTranslationUnitInfo*>(UserData); 522 CXTranslationUnit TU = ITUI->TU; 523 CXClientData client_data = ITUI->client_data; 524 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; 525 unsigned index_callbacks_size = ITUI->index_callbacks_size; 526 unsigned index_options = ITUI->index_options; 527 ITUI->result = 1; // init as error. 528 529 if (!TU) 530 return; 531 if (!client_index_callbacks || index_callbacks_size == 0) 532 return; 533 534 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 535 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 536 setThreadBackgroundPriority(); 537 538 IndexerCallbacks CB; 539 memset(&CB, 0, sizeof(CB)); 540 unsigned ClientCBSize = index_callbacks_size < sizeof(CB) 541 ? index_callbacks_size : sizeof(CB); 542 memcpy(&CB, client_index_callbacks, ClientCBSize); 543 544 OwningPtr<IndexingContext> IndexCtx; 545 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU)); 546 547 // Recover resources if we crash before exiting this method. 548 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext> 549 IndexCtxCleanup(IndexCtx.get()); 550 551 OwningPtr<IndexingConsumer> IndexConsumer; 552 IndexConsumer.reset(new IndexingConsumer(*IndexCtx)); 553 554 // Recover resources if we crash before exiting this method. 555 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer> 556 IndexConsumerCleanup(IndexConsumer.get()); 557 558 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 559 if (!Unit) 560 return; 561 562 ASTUnit::ConcurrencyCheck Check(*Unit); 563 564 FileManager &FileMgr = Unit->getFileManager(); 565 566 if (Unit->getOriginalSourceFileName().empty()) 567 IndexCtx->enteredMainFile(0); 568 else 569 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName())); 570 571 IndexConsumer->Initialize(Unit->getASTContext()); 572 573 indexPreprocessingRecord(*Unit, *IndexCtx); 574 indexTranslationUnit(*Unit, *IndexCtx); 575 indexDiagnostics(TU, *IndexCtx); 576 577 ITUI->result = 0; 578} 579 580//===----------------------------------------------------------------------===// 581// libclang public APIs. 582//===----------------------------------------------------------------------===// 583 584extern "C" { 585 586int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) { 587 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory; 588} 589 590const CXIdxObjCContainerDeclInfo * 591clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) { 592 if (!DInfo) 593 return 0; 594 595 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 596 if (const ObjCContainerDeclInfo * 597 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI)) 598 return &ContInfo->ObjCContDeclInfo; 599 600 return 0; 601} 602 603const CXIdxObjCInterfaceDeclInfo * 604clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) { 605 if (!DInfo) 606 return 0; 607 608 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 609 if (const ObjCInterfaceDeclInfo * 610 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 611 return &InterInfo->ObjCInterDeclInfo; 612 613 return 0; 614} 615 616const CXIdxObjCCategoryDeclInfo * 617clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){ 618 if (!DInfo) 619 return 0; 620 621 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 622 if (const ObjCCategoryDeclInfo * 623 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 624 return &CatInfo->ObjCCatDeclInfo; 625 626 return 0; 627} 628 629const CXIdxObjCProtocolRefListInfo * 630clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) { 631 if (!DInfo) 632 return 0; 633 634 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 635 636 if (const ObjCInterfaceDeclInfo * 637 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 638 return InterInfo->ObjCInterDeclInfo.protocols; 639 640 if (const ObjCProtocolDeclInfo * 641 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI)) 642 return &ProtInfo->ObjCProtoRefListInfo; 643 644 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 645 return CatInfo->ObjCCatDeclInfo.protocols; 646 647 return 0; 648} 649 650const CXIdxObjCPropertyDeclInfo * 651clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) { 652 if (!DInfo) 653 return 0; 654 655 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 656 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI)) 657 return &PropInfo->ObjCPropDeclInfo; 658 659 return 0; 660} 661 662const CXIdxIBOutletCollectionAttrInfo * 663clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) { 664 if (!AInfo) 665 return 0; 666 667 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo); 668 if (const IBOutletCollectionInfo * 669 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI)) 670 return &IBInfo->IBCollInfo; 671 672 return 0; 673} 674 675const CXIdxCXXClassDeclInfo * 676clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) { 677 if (!DInfo) 678 return 0; 679 680 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 681 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI)) 682 return &ClassInfo->CXXClassInfo; 683 684 return 0; 685} 686 687CXIdxClientContainer 688clang_index_getClientContainer(const CXIdxContainerInfo *info) { 689 if (!info) 690 return 0; 691 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 692 return Container->IndexCtx->getClientContainerForDC(Container->DC); 693} 694 695void clang_index_setClientContainer(const CXIdxContainerInfo *info, 696 CXIdxClientContainer client) { 697 if (!info) 698 return; 699 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 700 Container->IndexCtx->addContainerInMap(Container->DC, client); 701} 702 703CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) { 704 if (!info) 705 return 0; 706 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 707 return Entity->IndexCtx->getClientEntity(Entity->Dcl); 708} 709 710void clang_index_setClientEntity(const CXIdxEntityInfo *info, 711 CXIdxClientEntity client) { 712 if (!info) 713 return; 714 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 715 Entity->IndexCtx->setClientEntity(Entity->Dcl, client); 716} 717 718CXIndexAction clang_IndexAction_create(CXIndex CIdx) { 719 // For now, CXIndexAction is featureless. 720 return CIdx; 721} 722 723void clang_IndexAction_dispose(CXIndexAction idxAction) { 724 // For now, CXIndexAction is featureless. 725} 726 727int clang_indexSourceFile(CXIndexAction idxAction, 728 CXClientData client_data, 729 IndexerCallbacks *index_callbacks, 730 unsigned index_callbacks_size, 731 unsigned index_options, 732 const char *source_filename, 733 const char * const *command_line_args, 734 int num_command_line_args, 735 struct CXUnsavedFile *unsaved_files, 736 unsigned num_unsaved_files, 737 CXTranslationUnit *out_TU, 738 unsigned TU_options) { 739 740 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks, 741 index_callbacks_size, index_options, 742 source_filename, command_line_args, 743 num_command_line_args, unsaved_files, 744 num_unsaved_files, out_TU, TU_options, 0 }; 745 746 if (getenv("LIBCLANG_NOTHREADS")) { 747 clang_indexSourceFile_Impl(&ITUI); 748 return ITUI.result; 749 } 750 751 llvm::CrashRecoveryContext CRC; 752 753 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) { 754 fprintf(stderr, "libclang: crash detected during indexing source file: {\n"); 755 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 756 fprintf(stderr, " 'command_line_args' : ["); 757 for (int i = 0; i != num_command_line_args; ++i) { 758 if (i) 759 fprintf(stderr, ", "); 760 fprintf(stderr, "'%s'", command_line_args[i]); 761 } 762 fprintf(stderr, "],\n"); 763 fprintf(stderr, " 'unsaved_files' : ["); 764 for (unsigned i = 0; i != num_unsaved_files; ++i) { 765 if (i) 766 fprintf(stderr, ", "); 767 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 768 unsaved_files[i].Length); 769 } 770 fprintf(stderr, "],\n"); 771 fprintf(stderr, " 'options' : %d,\n", TU_options); 772 fprintf(stderr, "}\n"); 773 774 return 1; 775 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 776 if (out_TU) 777 PrintLibclangResourceUsage(*out_TU); 778 } 779 780 return ITUI.result; 781} 782 783int clang_indexTranslationUnit(CXIndexAction idxAction, 784 CXClientData client_data, 785 IndexerCallbacks *index_callbacks, 786 unsigned index_callbacks_size, 787 unsigned index_options, 788 CXTranslationUnit TU) { 789 790 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks, 791 index_callbacks_size, index_options, TU, 792 0 }; 793 794 if (getenv("LIBCLANG_NOTHREADS")) { 795 clang_indexTranslationUnit_Impl(&ITUI); 796 return ITUI.result; 797 } 798 799 llvm::CrashRecoveryContext CRC; 800 801 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) { 802 fprintf(stderr, "libclang: crash detected during indexing TU\n"); 803 804 return 1; 805 } 806 807 return ITUI.result; 808} 809 810void clang_indexLoc_getFileLocation(CXIdxLoc location, 811 CXIdxClientFile *indexFile, 812 CXFile *file, 813 unsigned *line, 814 unsigned *column, 815 unsigned *offset) { 816 if (indexFile) *indexFile = 0; 817 if (file) *file = 0; 818 if (line) *line = 0; 819 if (column) *column = 0; 820 if (offset) *offset = 0; 821 822 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 823 if (!location.ptr_data[0] || Loc.isInvalid()) 824 return; 825 826 IndexingContext &IndexCtx = 827 *static_cast<IndexingContext*>(location.ptr_data[0]); 828 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset); 829} 830 831CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) { 832 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 833 if (!location.ptr_data[0] || Loc.isInvalid()) 834 return clang_getNullLocation(); 835 836 IndexingContext &IndexCtx = 837 *static_cast<IndexingContext*>(location.ptr_data[0]); 838 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc); 839} 840 841} // end: extern "C" 842 843