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