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