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