blob: a70a3415431758d5004017c6f3bd86b153a1d732 [file] [log] [blame]
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001//===- 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"
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +000015#include "CIndexDiagnostic.h"
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000016#include "CIndexer.h"
17
18#include "clang/Frontend/ASTUnit.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor1f6b2b52012-01-20 16:28:04 +000021#include "clang/Frontend/FrontendAction.h"
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000022#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
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +000036static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx);
37
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000038namespace {
39
40//===----------------------------------------------------------------------===//
41// IndexPPCallbacks
42//===----------------------------------------------------------------------===//
43
44class IndexPPCallbacks : public PPCallbacks {
45 Preprocessor &PP;
46 IndexingContext &IndexCtx;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +000047 bool IsMainFileEntered;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000048
49public:
50 IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx)
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +000051 : 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 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000066
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.
81 virtual void MacroDefined(const Token &Id, const MacroInfo *MI) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000082 }
83
84 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
85 /// MI is released immediately following this callback.
86 virtual void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000087 }
88
89 /// MacroExpands - This is called by when a macro invocation is found.
90 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI,
91 SourceRange Range) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000092 }
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.
97 virtual void SourceRangeSkipped(SourceRange Range) {
98 }
99};
100
101//===----------------------------------------------------------------------===//
102// IndexingConsumer
103//===----------------------------------------------------------------------===//
104
105class IndexingConsumer : public ASTConsumer {
106 IndexingContext &IndexCtx;
107
108public:
109 explicit IndexingConsumer(IndexingContext &indexCtx)
110 : IndexCtx(indexCtx) { }
111
112 // ASTConsumer Implementation
113
114 virtual void Initialize(ASTContext &Context) {
115 IndexCtx.setASTContext(Context);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000116 IndexCtx.startedTranslationUnit();
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000117 }
118
119 virtual void HandleTranslationUnit(ASTContext &Ctx) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000120 }
121
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000122 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000123 IndexCtx.indexDeclGroupRef(DG);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000124 return !IndexCtx.shouldAbort();
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000125 }
126
127 /// \brief Handle the specified top-level declaration that occurred inside
128 /// and ObjC container.
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.
137 virtual void HandleInterestingDecl(DeclGroupRef D) {}
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +0000138
139 virtual void HandleTagDeclDefinition(TagDecl *D) {
140 if (IndexCtx.isTemplateImplicitInstantiation(D))
141 IndexCtx.indexDecl(D);
142 }
143
144 virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {
145 IndexCtx.indexDecl(D);
146 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000147};
148
149//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000150// CaptureDiagnosticConsumer
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000151//===----------------------------------------------------------------------===//
152
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000153class CaptureDiagnosticConsumer : public DiagnosticConsumer {
154 SmallVector<StoredDiagnostic, 4> Errors;
155public:
156
157 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
158 const Diagnostic &Info) {
159 if (level >= DiagnosticsEngine::Error)
160 Errors.push_back(StoredDiagnostic(level, Info));
161 }
162
163 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
164 return new IgnoringDiagConsumer();
165 }
166};
167
168//===----------------------------------------------------------------------===//
169// IndexingFrontendAction
170//===----------------------------------------------------------------------===//
171
172class IndexingFrontendAction : public ASTFrontendAction {
173 IndexingContext IndexCtx;
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000174 CXTranslationUnit CXTU;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000175
176public:
177 IndexingFrontendAction(CXClientData clientData,
178 IndexerCallbacks &indexCallbacks,
179 unsigned indexOptions,
180 CXTranslationUnit cxTU)
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000181 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU),
182 CXTU(cxTU) { }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000183
184 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
185 StringRef InFile) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000186 IndexCtx.setASTContext(CI.getASTContext());
187 Preprocessor &PP = CI.getPreprocessor();
188 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx));
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000189 IndexCtx.setPreprocessor(PP);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000190 return new IndexingConsumer(IndexCtx);
191 }
192
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000193 virtual void EndSourceFileAction() {
194 indexDiagnostics(CXTU, IndexCtx);
195 }
196
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +0000197 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Complete; }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000198 virtual bool hasCodeCompletionSupport() const { return false; }
199};
200
201//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000202// clang_indexSourceFileUnit Implementation
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000203//===----------------------------------------------------------------------===//
204
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000205struct IndexSourceFileInfo {
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000206 CXIndexAction idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000207 CXClientData client_data;
208 IndexerCallbacks *index_callbacks;
209 unsigned index_callbacks_size;
210 unsigned index_options;
211 const char *source_filename;
212 const char *const *command_line_args;
213 int num_command_line_args;
214 struct CXUnsavedFile *unsaved_files;
215 unsigned num_unsaved_files;
216 CXTranslationUnit *out_TU;
217 unsigned TU_options;
218 int result;
219};
220
221struct MemBufferOwner {
222 SmallVector<const llvm::MemoryBuffer *, 8> Buffers;
223
224 ~MemBufferOwner() {
225 for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator
226 I = Buffers.begin(), E = Buffers.end(); I != E; ++I)
227 delete *I;
228 }
229};
230
231} // anonymous namespace
232
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000233static void clang_indexSourceFile_Impl(void *UserData) {
234 IndexSourceFileInfo *ITUI =
235 static_cast<IndexSourceFileInfo*>(UserData);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000236 CXIndex CIdx = (CXIndex)ITUI->idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000237 CXClientData client_data = ITUI->client_data;
238 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
239 unsigned index_callbacks_size = ITUI->index_callbacks_size;
240 unsigned index_options = ITUI->index_options;
241 const char *source_filename = ITUI->source_filename;
242 const char * const *command_line_args = ITUI->command_line_args;
243 int num_command_line_args = ITUI->num_command_line_args;
244 struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files;
245 unsigned num_unsaved_files = ITUI->num_unsaved_files;
246 CXTranslationUnit *out_TU = ITUI->out_TU;
247 unsigned TU_options = ITUI->TU_options;
248 ITUI->result = 1; // init as error.
249
250 if (out_TU)
251 *out_TU = 0;
252 bool requestedToGetTU = (out_TU != 0);
253
254 if (!CIdx)
255 return;
256 if (!client_index_callbacks || index_callbacks_size == 0)
257 return;
258
259 IndexerCallbacks CB;
260 memset(&CB, 0, sizeof(CB));
261 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
262 ? index_callbacks_size : sizeof(CB);
263 memcpy(&CB, client_index_callbacks, ClientCBSize);
264
265 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
266
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000267 CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer();
268
269 // Configure the diagnostics.
270 DiagnosticOptions DiagOpts;
271 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
272 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
273 command_line_args,
274 CaptureDiag,
Argyrios Kyrtzidis73835502011-11-29 08:14:50 +0000275 /*ShouldOwnClient=*/true,
276 /*ShouldCloneClient=*/false));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000277
278 // Recover resources if we crash before exiting this function.
279 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
280 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
281 DiagCleanup(Diags.getPtr());
282
283 llvm::OwningPtr<std::vector<const char *> >
284 Args(new std::vector<const char*>());
285
286 // Recover resources if we crash before exiting this method.
287 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
288 ArgsCleanup(Args.get());
289
290 Args->insert(Args->end(), command_line_args,
291 command_line_args + num_command_line_args);
292
293 // The 'source_filename' argument is optional. If the caller does not
294 // specify it then it is assumed that the source file is specified
295 // in the actual argument list.
296 // Put the source file after command_line_args otherwise if '-x' flag is
297 // present it will be unused.
298 if (source_filename)
299 Args->push_back(source_filename);
300
301 llvm::IntrusiveRefCntPtr<CompilerInvocation>
302 CInvok(createInvocationFromCommandLine(*Args, Diags));
303
304 if (!CInvok)
305 return;
306
307 // Recover resources if we crash before exiting this function.
308 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
309 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
310 CInvokCleanup(CInvok.getPtr());
311
312 if (CInvok->getFrontendOpts().Inputs.empty())
313 return;
314
315 llvm::OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner());
316
317 // Recover resources if we crash before exiting this method.
318 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner>
319 BufOwnerCleanup(BufOwner.get());
320
321 for (unsigned I = 0; I != num_unsaved_files; ++I) {
322 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
323 const llvm::MemoryBuffer *Buffer
324 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
325 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer);
326 BufOwner->Buffers.push_back(Buffer);
327 }
328
329 // Since libclang is primarily used by batch tools dealing with
330 // (often very broken) source code, where spell-checking can have a
331 // significant negative impact on performance (particularly when
332 // precompiled headers are involved), we disable it.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000333 CInvok->getLangOpts()->SpellChecking = false;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000334
335 if (!requestedToGetTU)
336 CInvok->getPreprocessorOpts().DetailedRecord = false;
337
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +0000338 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags,
339 /*CaptureDiagnostics=*/true);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000340 llvm::OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(Unit)));
341
342 // Recover resources if we crash before exiting this method.
343 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
344 CXTUCleanup(CXTU.get());
345
346 llvm::OwningPtr<IndexingFrontendAction> IndexAction;
347 IndexAction.reset(new IndexingFrontendAction(client_data, CB,
348 index_options, CXTU->getTU()));
349
350 // Recover resources if we crash before exiting this method.
351 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction>
352 IndexActionCleanup(IndexAction.get());
353
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000354 bool Persistent = requestedToGetTU;
355 StringRef ResourceFilesPath = CXXIdx->getClangResourcesPath();
356 bool OnlyLocalDecls = false;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000357 bool PrecompilePreamble = false;
358 bool CacheCodeCompletionResults = false;
359 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
360 PPOpts.DetailedRecord = false;
361 PPOpts.DetailedRecordIncludesNestedMacroExpansions = false;
362
363 if (requestedToGetTU) {
364 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
365 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
366 // FIXME: Add a flag for modules.
367 CacheCodeCompletionResults
368 = TU_options & CXTranslationUnit_CacheCompletionResults;
369 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
370 PPOpts.DetailedRecord = true;
371 PPOpts.DetailedRecordIncludesNestedMacroExpansions
372 = (TU_options & CXTranslationUnit_NestedMacroExpansions);
373 }
374 }
375
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000376 Unit = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags,
377 IndexAction.get(),
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000378 Unit,
379 Persistent,
380 ResourceFilesPath,
381 OnlyLocalDecls,
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000382 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000383 PrecompilePreamble,
384 CacheCodeCompletionResults);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000385 if (!Unit)
386 return;
387
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000388 if (out_TU)
389 *out_TU = CXTU->takeTU();
390
391 ITUI->result = 0; // success.
392}
393
394//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000395// clang_indexTranslationUnit Implementation
396//===----------------------------------------------------------------------===//
397
398namespace {
399
400struct IndexTranslationUnitInfo {
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000401 CXIndexAction idxAction;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000402 CXClientData client_data;
403 IndexerCallbacks *index_callbacks;
404 unsigned index_callbacks_size;
405 unsigned index_options;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000406 CXTranslationUnit TU;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000407 int result;
408};
409
410} // anonymous namespace
411
412static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) {
413 Preprocessor &PP = Unit.getPreprocessor();
414 if (!PP.getPreprocessingRecord())
415 return;
416
417 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
418
419 // FIXME: Only deserialize inclusion directives.
420 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
421 // that it depends on.
422
423 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
424 PreprocessingRecord::iterator I, E;
425 if (OnlyLocal) {
426 I = PPRec.local_begin();
427 E = PPRec.local_end();
428 } else {
429 I = PPRec.begin();
430 E = PPRec.end();
431 }
432
433 for (; I != E; ++I) {
434 PreprocessedEntity *PPE = *I;
435
436 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
437 IdxCtx.ppIncludedFile(ID->getSourceRange().getBegin(), ID->getFileName(),
438 ID->getFile(), ID->getKind() == InclusionDirective::Import,
439 !ID->wasInQuotes());
440 }
441 }
442}
443
444static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) {
445 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
446 // that it depends on.
447
448 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
449
450 if (OnlyLocal) {
451 for (ASTUnit::top_level_iterator TL = Unit.top_level_begin(),
452 TLEnd = Unit.top_level_end();
453 TL != TLEnd; ++TL) {
454 IdxCtx.indexTopLevelDecl(*TL);
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000455 if (IdxCtx.shouldAbort())
456 return;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000457 }
458
459 } else {
460 TranslationUnitDecl *TUDecl = Unit.getASTContext().getTranslationUnitDecl();
461 for (TranslationUnitDecl::decl_iterator
462 I = TUDecl->decls_begin(), E = TUDecl->decls_end(); I != E; ++I) {
463 IdxCtx.indexTopLevelDecl(*I);
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000464 if (IdxCtx.shouldAbort())
465 return;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000466 }
467 }
468}
469
470static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) {
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000471 if (!IdxCtx.hasDiagnosticCallback())
472 return;
473
474 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU);
475 IdxCtx.handleDiagnosticSet(DiagSet);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000476}
477
478static void clang_indexTranslationUnit_Impl(void *UserData) {
479 IndexTranslationUnitInfo *ITUI =
480 static_cast<IndexTranslationUnitInfo*>(UserData);
481 CXTranslationUnit TU = ITUI->TU;
482 CXClientData client_data = ITUI->client_data;
483 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
484 unsigned index_callbacks_size = ITUI->index_callbacks_size;
485 unsigned index_options = ITUI->index_options;
486 ITUI->result = 1; // init as error.
487
488 if (!TU)
489 return;
490 if (!client_index_callbacks || index_callbacks_size == 0)
491 return;
492
493 IndexerCallbacks CB;
494 memset(&CB, 0, sizeof(CB));
495 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
496 ? index_callbacks_size : sizeof(CB);
497 memcpy(&CB, client_index_callbacks, ClientCBSize);
498
499 llvm::OwningPtr<IndexingContext> IndexCtx;
500 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU));
501
502 // Recover resources if we crash before exiting this method.
503 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext>
504 IndexCtxCleanup(IndexCtx.get());
505
506 llvm::OwningPtr<IndexingConsumer> IndexConsumer;
507 IndexConsumer.reset(new IndexingConsumer(*IndexCtx));
508
509 // Recover resources if we crash before exiting this method.
510 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer>
511 IndexConsumerCleanup(IndexConsumer.get());
512
513 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
514 if (!Unit)
515 return;
516
517 FileManager &FileMgr = Unit->getFileManager();
518
519 if (Unit->getOriginalSourceFileName().empty())
520 IndexCtx->enteredMainFile(0);
521 else
522 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
523
524 IndexConsumer->Initialize(Unit->getASTContext());
525
526 indexPreprocessingRecord(*Unit, *IndexCtx);
527 indexTranslationUnit(*Unit, *IndexCtx);
528 indexDiagnostics(TU, *IndexCtx);
529
530 ITUI->result = 0;
531}
532
533//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000534// libclang public APIs.
535//===----------------------------------------------------------------------===//
536
537extern "C" {
538
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000539int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
540 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
541}
542
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000543const CXIdxObjCContainerDeclInfo *
544clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
545 if (!DInfo)
546 return 0;
547
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000548 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
549 if (const ObjCContainerDeclInfo *
550 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
551 return &ContInfo->ObjCContDeclInfo;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000552
553 return 0;
554}
555
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000556const CXIdxObjCInterfaceDeclInfo *
557clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000558 if (!DInfo)
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000559 return 0;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000560
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000561 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
562 if (const ObjCInterfaceDeclInfo *
563 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
564 return &InterInfo->ObjCInterDeclInfo;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000565
566 return 0;
567}
568
569const CXIdxObjCCategoryDeclInfo *
570clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000571 if (!DInfo)
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000572 return 0;
573
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000574 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
575 if (const ObjCCategoryDeclInfo *
576 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
577 return &CatInfo->ObjCCatDeclInfo;
578
579 return 0;
580}
581
582const CXIdxObjCProtocolRefListInfo *
583clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
584 if (!DInfo)
585 return 0;
586
587 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
588
589 if (const ObjCInterfaceDeclInfo *
590 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
591 return InterInfo->ObjCInterDeclInfo.protocols;
592
593 if (const ObjCProtocolDeclInfo *
594 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
595 return &ProtInfo->ObjCProtoRefListInfo;
596
Argyrios Kyrtzidisc10a4c82011-12-13 18:47:45 +0000597 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
598 return CatInfo->ObjCCatDeclInfo.protocols;
599
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000600 return 0;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000601}
602
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000603const CXIdxIBOutletCollectionAttrInfo *
604clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
605 if (!AInfo)
606 return 0;
607
608 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
609 if (const IBOutletCollectionInfo *
610 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
611 return &IBInfo->IBCollInfo;
612
613 return 0;
614}
615
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000616const CXIdxCXXClassDeclInfo *
617clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
618 if (!DInfo)
619 return 0;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000620
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000621 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
622 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
623 return &ClassInfo->CXXClassInfo;
624
625 return 0;
626}
627
628CXIdxClientContainer
629clang_index_getClientContainer(const CXIdxContainerInfo *info) {
630 if (!info)
631 return 0;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000632 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000633 return Container->IndexCtx->getClientContainerForDC(Container->DC);
634}
635
636void clang_index_setClientContainer(const CXIdxContainerInfo *info,
637 CXIdxClientContainer client) {
638 if (!info)
639 return;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000640 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000641 Container->IndexCtx->addContainerInMap(Container->DC, client);
642}
643
644CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
645 if (!info)
646 return 0;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000647 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000648 return Entity->IndexCtx->getClientEntity(Entity->Dcl);
649}
650
651void clang_index_setClientEntity(const CXIdxEntityInfo *info,
652 CXIdxClientEntity client) {
653 if (!info)
654 return;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000655 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000656 Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
657}
658
659CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
660 // For now, CXIndexAction is featureless.
661 return CIdx;
662}
663
664void clang_IndexAction_dispose(CXIndexAction idxAction) {
665 // For now, CXIndexAction is featureless.
666}
667
668int clang_indexSourceFile(CXIndexAction idxAction,
669 CXClientData client_data,
670 IndexerCallbacks *index_callbacks,
671 unsigned index_callbacks_size,
672 unsigned index_options,
673 const char *source_filename,
674 const char * const *command_line_args,
675 int num_command_line_args,
676 struct CXUnsavedFile *unsaved_files,
677 unsigned num_unsaved_files,
678 CXTranslationUnit *out_TU,
679 unsigned TU_options) {
680
681 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks,
682 index_callbacks_size, index_options,
683 source_filename, command_line_args,
684 num_command_line_args, unsaved_files,
685 num_unsaved_files, out_TU, TU_options, 0 };
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000686
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +0000687 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000688 clang_indexSourceFile_Impl(&ITUI);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000689 return ITUI.result;
690 }
691
692 llvm::CrashRecoveryContext CRC;
693
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000694 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) {
695 fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000696 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
697 fprintf(stderr, " 'command_line_args' : [");
698 for (int i = 0; i != num_command_line_args; ++i) {
699 if (i)
700 fprintf(stderr, ", ");
701 fprintf(stderr, "'%s'", command_line_args[i]);
702 }
703 fprintf(stderr, "],\n");
704 fprintf(stderr, " 'unsaved_files' : [");
705 for (unsigned i = 0; i != num_unsaved_files; ++i) {
706 if (i)
707 fprintf(stderr, ", ");
708 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
709 unsaved_files[i].Length);
710 }
711 fprintf(stderr, "],\n");
712 fprintf(stderr, " 'options' : %d,\n", TU_options);
713 fprintf(stderr, "}\n");
714
715 return 1;
716 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
717 if (out_TU)
718 PrintLibclangResourceUsage(*out_TU);
719 }
720
721 return ITUI.result;
722}
723
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000724int clang_indexTranslationUnit(CXIndexAction idxAction,
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000725 CXClientData client_data,
726 IndexerCallbacks *index_callbacks,
727 unsigned index_callbacks_size,
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000728 unsigned index_options,
729 CXTranslationUnit TU) {
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000730
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000731 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks,
732 index_callbacks_size, index_options, TU,
733 0 };
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000734
735 if (getenv("LIBCLANG_NOTHREADS")) {
736 clang_indexTranslationUnit_Impl(&ITUI);
737 return ITUI.result;
738 }
739
740 llvm::CrashRecoveryContext CRC;
741
742 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) {
743 fprintf(stderr, "libclang: crash detected during indexing TU\n");
744
745 return 1;
746 }
747
748 return ITUI.result;
749}
750
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000751void clang_indexLoc_getFileLocation(CXIdxLoc location,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000752 CXIdxClientFile *indexFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000753 CXFile *file,
754 unsigned *line,
755 unsigned *column,
756 unsigned *offset) {
757 if (indexFile) *indexFile = 0;
758 if (file) *file = 0;
759 if (line) *line = 0;
760 if (column) *column = 0;
761 if (offset) *offset = 0;
762
763 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
764 if (!location.ptr_data[0] || Loc.isInvalid())
765 return;
766
767 IndexingContext &IndexCtx =
768 *static_cast<IndexingContext*>(location.ptr_data[0]);
769 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset);
770}
771
772CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
773 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
774 if (!location.ptr_data[0] || Loc.isInvalid())
775 return clang_getNullLocation();
776
777 IndexingContext &IndexCtx =
778 *static_cast<IndexingContext*>(location.ptr_data[0]);
779 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc);
780}
781
782} // end: extern "C"
783