blob: d1af38887b7b2994b7f6e31f82baa3bb2f845385 [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) {
Argyrios Kyrtzidis58d2dbe2012-02-14 22:23:11 +0000140 if (!IndexCtx.shouldIndexImplicitTemplateInsts())
141 return;
142
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +0000143 if (IndexCtx.isTemplateImplicitInstantiation(D))
144 IndexCtx.indexDecl(D);
145 }
146
147 virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {
Argyrios Kyrtzidis58d2dbe2012-02-14 22:23:11 +0000148 if (!IndexCtx.shouldIndexImplicitTemplateInsts())
149 return;
150
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +0000151 IndexCtx.indexDecl(D);
152 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000153};
154
155//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000156// CaptureDiagnosticConsumer
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000157//===----------------------------------------------------------------------===//
158
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000159class CaptureDiagnosticConsumer : public DiagnosticConsumer {
160 SmallVector<StoredDiagnostic, 4> Errors;
161public:
162
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
169 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
170 return new IgnoringDiagConsumer();
171 }
172};
173
174//===----------------------------------------------------------------------===//
175// IndexingFrontendAction
176//===----------------------------------------------------------------------===//
177
178class IndexingFrontendAction : public ASTFrontendAction {
179 IndexingContext IndexCtx;
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000180 CXTranslationUnit CXTU;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000181
182public:
183 IndexingFrontendAction(CXClientData clientData,
184 IndexerCallbacks &indexCallbacks,
185 unsigned indexOptions,
186 CXTranslationUnit cxTU)
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000187 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU),
188 CXTU(cxTU) { }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000189
190 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
191 StringRef InFile) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000192 IndexCtx.setASTContext(CI.getASTContext());
193 Preprocessor &PP = CI.getPreprocessor();
194 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx));
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000195 IndexCtx.setPreprocessor(PP);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000196 return new IndexingConsumer(IndexCtx);
197 }
198
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000199 virtual void EndSourceFileAction() {
200 indexDiagnostics(CXTU, IndexCtx);
201 }
202
Argyrios Kyrtzidis58d2dbe2012-02-14 22:23:11 +0000203 virtual TranslationUnitKind getTranslationUnitKind() {
204 if (IndexCtx.shouldIndexImplicitTemplateInsts())
205 return TU_Complete;
206 else
207 return TU_Prefix;
208 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000209 virtual bool hasCodeCompletionSupport() const { return false; }
210};
211
212//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000213// clang_indexSourceFileUnit Implementation
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000214//===----------------------------------------------------------------------===//
215
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000216struct IndexSourceFileInfo {
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000217 CXIndexAction idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000218 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
232struct MemBufferOwner {
233 SmallVector<const llvm::MemoryBuffer *, 8> Buffers;
234
235 ~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
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000244static void clang_indexSourceFile_Impl(void *UserData) {
245 IndexSourceFileInfo *ITUI =
246 static_cast<IndexSourceFileInfo*>(UserData);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000247 CXIndex CIdx = (CXIndex)ITUI->idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000248 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
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000278 CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer();
279
280 // Configure the diagnostics.
281 DiagnosticOptions DiagOpts;
282 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
283 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
284 command_line_args,
285 CaptureDiag,
Argyrios Kyrtzidis73835502011-11-29 08:14:50 +0000286 /*ShouldOwnClient=*/true,
287 /*ShouldCloneClient=*/false));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000288
289 // Recover resources if we crash before exiting this function.
290 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
291 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
292 DiagCleanup(Diags.getPtr());
293
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000294 OwningPtr<std::vector<const char *> >
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000295 Args(new std::vector<const char*>());
296
297 // Recover resources if we crash before exiting this method.
298 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
299 ArgsCleanup(Args.get());
300
301 Args->insert(Args->end(), command_line_args,
302 command_line_args + num_command_line_args);
303
304 // The 'source_filename' argument is optional. If the caller does not
305 // specify it then it is assumed that the source file is specified
306 // in the actual argument list.
307 // Put the source file after command_line_args otherwise if '-x' flag is
308 // present it will be unused.
309 if (source_filename)
310 Args->push_back(source_filename);
311
312 llvm::IntrusiveRefCntPtr<CompilerInvocation>
313 CInvok(createInvocationFromCommandLine(*Args, Diags));
314
315 if (!CInvok)
316 return;
317
318 // Recover resources if we crash before exiting this function.
319 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
320 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
321 CInvokCleanup(CInvok.getPtr());
322
323 if (CInvok->getFrontendOpts().Inputs.empty())
324 return;
325
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000326 OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner());
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000327
328 // Recover resources if we crash before exiting this method.
329 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner>
330 BufOwnerCleanup(BufOwner.get());
331
332 for (unsigned I = 0; I != num_unsaved_files; ++I) {
333 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
334 const llvm::MemoryBuffer *Buffer
335 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
336 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer);
337 BufOwner->Buffers.push_back(Buffer);
338 }
339
340 // Since libclang is primarily used by batch tools dealing with
341 // (often very broken) source code, where spell-checking can have a
342 // significant negative impact on performance (particularly when
343 // precompiled headers are involved), we disable it.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000344 CInvok->getLangOpts()->SpellChecking = false;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000345
346 if (!requestedToGetTU)
347 CInvok->getPreprocessorOpts().DetailedRecord = false;
348
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +0000349 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags,
350 /*CaptureDiagnostics=*/true);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000351 OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(Unit)));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000352
353 // Recover resources if we crash before exiting this method.
354 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
355 CXTUCleanup(CXTU.get());
356
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000357 OwningPtr<IndexingFrontendAction> IndexAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000358 IndexAction.reset(new IndexingFrontendAction(client_data, CB,
359 index_options, CXTU->getTU()));
360
361 // Recover resources if we crash before exiting this method.
362 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction>
363 IndexActionCleanup(IndexAction.get());
364
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000365 bool Persistent = requestedToGetTU;
366 StringRef ResourceFilesPath = CXXIdx->getClangResourcesPath();
367 bool OnlyLocalDecls = false;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000368 bool PrecompilePreamble = false;
369 bool CacheCodeCompletionResults = false;
370 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
371 PPOpts.DetailedRecord = false;
372 PPOpts.DetailedRecordIncludesNestedMacroExpansions = false;
373
374 if (requestedToGetTU) {
375 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
376 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
377 // FIXME: Add a flag for modules.
378 CacheCodeCompletionResults
379 = TU_options & CXTranslationUnit_CacheCompletionResults;
380 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
381 PPOpts.DetailedRecord = true;
382 PPOpts.DetailedRecordIncludesNestedMacroExpansions
383 = (TU_options & CXTranslationUnit_NestedMacroExpansions);
384 }
385 }
386
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000387 Unit = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags,
388 IndexAction.get(),
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000389 Unit,
390 Persistent,
391 ResourceFilesPath,
392 OnlyLocalDecls,
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000393 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +0000394 PrecompilePreamble,
395 CacheCodeCompletionResults);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000396 if (!Unit)
397 return;
398
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000399 if (out_TU)
400 *out_TU = CXTU->takeTU();
401
402 ITUI->result = 0; // success.
403}
404
405//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000406// clang_indexTranslationUnit Implementation
407//===----------------------------------------------------------------------===//
408
409namespace {
410
411struct IndexTranslationUnitInfo {
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000412 CXIndexAction idxAction;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000413 CXClientData client_data;
414 IndexerCallbacks *index_callbacks;
415 unsigned index_callbacks_size;
416 unsigned index_options;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000417 CXTranslationUnit TU;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000418 int result;
419};
420
421} // anonymous namespace
422
423static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) {
424 Preprocessor &PP = Unit.getPreprocessor();
425 if (!PP.getPreprocessingRecord())
426 return;
427
428 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
429
430 // FIXME: Only deserialize inclusion directives.
431 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
432 // that it depends on.
433
434 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
435 PreprocessingRecord::iterator I, E;
436 if (OnlyLocal) {
437 I = PPRec.local_begin();
438 E = PPRec.local_end();
439 } else {
440 I = PPRec.begin();
441 E = PPRec.end();
442 }
443
444 for (; I != E; ++I) {
445 PreprocessedEntity *PPE = *I;
446
447 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
448 IdxCtx.ppIncludedFile(ID->getSourceRange().getBegin(), ID->getFileName(),
449 ID->getFile(), ID->getKind() == InclusionDirective::Import,
450 !ID->wasInQuotes());
451 }
452 }
453}
454
455static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) {
456 // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
457 // that it depends on.
458
459 bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
460
461 if (OnlyLocal) {
462 for (ASTUnit::top_level_iterator TL = Unit.top_level_begin(),
463 TLEnd = Unit.top_level_end();
464 TL != TLEnd; ++TL) {
465 IdxCtx.indexTopLevelDecl(*TL);
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000466 if (IdxCtx.shouldAbort())
467 return;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000468 }
469
470 } else {
471 TranslationUnitDecl *TUDecl = Unit.getASTContext().getTranslationUnitDecl();
472 for (TranslationUnitDecl::decl_iterator
473 I = TUDecl->decls_begin(), E = TUDecl->decls_end(); I != E; ++I) {
474 IdxCtx.indexTopLevelDecl(*I);
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000475 if (IdxCtx.shouldAbort())
476 return;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000477 }
478 }
479}
480
481static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) {
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +0000482 if (!IdxCtx.hasDiagnosticCallback())
483 return;
484
485 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU);
486 IdxCtx.handleDiagnosticSet(DiagSet);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000487}
488
489static void clang_indexTranslationUnit_Impl(void *UserData) {
490 IndexTranslationUnitInfo *ITUI =
491 static_cast<IndexTranslationUnitInfo*>(UserData);
492 CXTranslationUnit TU = ITUI->TU;
493 CXClientData client_data = ITUI->client_data;
494 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
495 unsigned index_callbacks_size = ITUI->index_callbacks_size;
496 unsigned index_options = ITUI->index_options;
497 ITUI->result = 1; // init as error.
498
499 if (!TU)
500 return;
501 if (!client_index_callbacks || index_callbacks_size == 0)
502 return;
503
504 IndexerCallbacks CB;
505 memset(&CB, 0, sizeof(CB));
506 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
507 ? index_callbacks_size : sizeof(CB);
508 memcpy(&CB, client_index_callbacks, ClientCBSize);
509
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000510 OwningPtr<IndexingContext> IndexCtx;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000511 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU));
512
513 // Recover resources if we crash before exiting this method.
514 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext>
515 IndexCtxCleanup(IndexCtx.get());
516
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000517 OwningPtr<IndexingConsumer> IndexConsumer;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000518 IndexConsumer.reset(new IndexingConsumer(*IndexCtx));
519
520 // Recover resources if we crash before exiting this method.
521 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer>
522 IndexConsumerCleanup(IndexConsumer.get());
523
524 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
525 if (!Unit)
526 return;
527
528 FileManager &FileMgr = Unit->getFileManager();
529
530 if (Unit->getOriginalSourceFileName().empty())
531 IndexCtx->enteredMainFile(0);
532 else
533 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
534
535 IndexConsumer->Initialize(Unit->getASTContext());
536
537 indexPreprocessingRecord(*Unit, *IndexCtx);
538 indexTranslationUnit(*Unit, *IndexCtx);
539 indexDiagnostics(TU, *IndexCtx);
540
541 ITUI->result = 0;
542}
543
544//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000545// libclang public APIs.
546//===----------------------------------------------------------------------===//
547
548extern "C" {
549
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000550int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
551 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
552}
553
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000554const CXIdxObjCContainerDeclInfo *
555clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
556 if (!DInfo)
557 return 0;
558
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000559 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
560 if (const ObjCContainerDeclInfo *
561 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
562 return &ContInfo->ObjCContDeclInfo;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000563
564 return 0;
565}
566
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000567const CXIdxObjCInterfaceDeclInfo *
568clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000569 if (!DInfo)
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000570 return 0;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000571
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000572 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
573 if (const ObjCInterfaceDeclInfo *
574 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
575 return &InterInfo->ObjCInterDeclInfo;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000576
577 return 0;
578}
579
580const CXIdxObjCCategoryDeclInfo *
581clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000582 if (!DInfo)
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000583 return 0;
584
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000585 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
586 if (const ObjCCategoryDeclInfo *
587 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
588 return &CatInfo->ObjCCatDeclInfo;
589
590 return 0;
591}
592
593const CXIdxObjCProtocolRefListInfo *
594clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
595 if (!DInfo)
596 return 0;
597
598 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
599
600 if (const ObjCInterfaceDeclInfo *
601 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
602 return InterInfo->ObjCInterDeclInfo.protocols;
603
604 if (const ObjCProtocolDeclInfo *
605 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
606 return &ProtInfo->ObjCProtoRefListInfo;
607
Argyrios Kyrtzidisc10a4c82011-12-13 18:47:45 +0000608 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
609 return CatInfo->ObjCCatDeclInfo.protocols;
610
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +0000611 return 0;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000612}
613
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +0000614const CXIdxIBOutletCollectionAttrInfo *
615clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
616 if (!AInfo)
617 return 0;
618
619 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
620 if (const IBOutletCollectionInfo *
621 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
622 return &IBInfo->IBCollInfo;
623
624 return 0;
625}
626
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000627const CXIdxCXXClassDeclInfo *
628clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
629 if (!DInfo)
630 return 0;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000631
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000632 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
633 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
634 return &ClassInfo->CXXClassInfo;
635
636 return 0;
637}
638
639CXIdxClientContainer
640clang_index_getClientContainer(const CXIdxContainerInfo *info) {
641 if (!info)
642 return 0;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000643 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000644 return Container->IndexCtx->getClientContainerForDC(Container->DC);
645}
646
647void clang_index_setClientContainer(const CXIdxContainerInfo *info,
648 CXIdxClientContainer client) {
649 if (!info)
650 return;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000651 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000652 Container->IndexCtx->addContainerInMap(Container->DC, client);
653}
654
655CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
656 if (!info)
657 return 0;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000658 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000659 return Entity->IndexCtx->getClientEntity(Entity->Dcl);
660}
661
662void clang_index_setClientEntity(const CXIdxEntityInfo *info,
663 CXIdxClientEntity client) {
664 if (!info)
665 return;
Benjamin Kramer3267e112011-11-29 12:31:20 +0000666 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000667 Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
668}
669
670CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
671 // For now, CXIndexAction is featureless.
672 return CIdx;
673}
674
675void clang_IndexAction_dispose(CXIndexAction idxAction) {
676 // For now, CXIndexAction is featureless.
677}
678
679int clang_indexSourceFile(CXIndexAction idxAction,
680 CXClientData client_data,
681 IndexerCallbacks *index_callbacks,
682 unsigned index_callbacks_size,
683 unsigned index_options,
684 const char *source_filename,
685 const char * const *command_line_args,
686 int num_command_line_args,
687 struct CXUnsavedFile *unsaved_files,
688 unsigned num_unsaved_files,
689 CXTranslationUnit *out_TU,
690 unsigned TU_options) {
691
692 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks,
693 index_callbacks_size, index_options,
694 source_filename, command_line_args,
695 num_command_line_args, unsaved_files,
696 num_unsaved_files, out_TU, TU_options, 0 };
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000697
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +0000698 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000699 clang_indexSourceFile_Impl(&ITUI);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000700 return ITUI.result;
701 }
702
703 llvm::CrashRecoveryContext CRC;
704
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000705 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) {
706 fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000707 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
708 fprintf(stderr, " 'command_line_args' : [");
709 for (int i = 0; i != num_command_line_args; ++i) {
710 if (i)
711 fprintf(stderr, ", ");
712 fprintf(stderr, "'%s'", command_line_args[i]);
713 }
714 fprintf(stderr, "],\n");
715 fprintf(stderr, " 'unsaved_files' : [");
716 for (unsigned i = 0; i != num_unsaved_files; ++i) {
717 if (i)
718 fprintf(stderr, ", ");
719 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
720 unsaved_files[i].Length);
721 }
722 fprintf(stderr, "],\n");
723 fprintf(stderr, " 'options' : %d,\n", TU_options);
724 fprintf(stderr, "}\n");
725
726 return 1;
727 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
728 if (out_TU)
729 PrintLibclangResourceUsage(*out_TU);
730 }
731
732 return ITUI.result;
733}
734
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000735int clang_indexTranslationUnit(CXIndexAction idxAction,
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000736 CXClientData client_data,
737 IndexerCallbacks *index_callbacks,
738 unsigned index_callbacks_size,
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000739 unsigned index_options,
740 CXTranslationUnit TU) {
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000741
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +0000742 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks,
743 index_callbacks_size, index_options, TU,
744 0 };
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +0000745
746 if (getenv("LIBCLANG_NOTHREADS")) {
747 clang_indexTranslationUnit_Impl(&ITUI);
748 return ITUI.result;
749 }
750
751 llvm::CrashRecoveryContext CRC;
752
753 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) {
754 fprintf(stderr, "libclang: crash detected during indexing TU\n");
755
756 return 1;
757 }
758
759 return ITUI.result;
760}
761
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000762void clang_indexLoc_getFileLocation(CXIdxLoc location,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000763 CXIdxClientFile *indexFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000764 CXFile *file,
765 unsigned *line,
766 unsigned *column,
767 unsigned *offset) {
768 if (indexFile) *indexFile = 0;
769 if (file) *file = 0;
770 if (line) *line = 0;
771 if (column) *column = 0;
772 if (offset) *offset = 0;
773
774 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
775 if (!location.ptr_data[0] || Loc.isInvalid())
776 return;
777
778 IndexingContext &IndexCtx =
779 *static_cast<IndexingContext*>(location.ptr_data[0]);
780 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset);
781}
782
783CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
784 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
785 if (!location.ptr_data[0] || Loc.isInvalid())
786 return clang_getNullLocation();
787
788 IndexingContext &IndexCtx =
789 *static_cast<IndexingContext*>(location.ptr_data[0]);
790 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc);
791}
792
793} // end: extern "C"
794