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