blob: 8d905059711c80deeef942846b739690e9a24bff [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"
15#include "CIndexer.h"
16
17#include "clang/Frontend/ASTUnit.h"
18#include "clang/Frontend/CompilerInvocation.h"
19#include "clang/Frontend/CompilerInstance.h"
20#include "clang/Frontend/Utils.h"
21#include "clang/Sema/SemaConsumer.h"
22#include "clang/AST/ASTConsumer.h"
23#include "clang/AST/DeclVisitor.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Lex/PPCallbacks.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/CrashRecoveryContext.h"
28
29using namespace clang;
30using namespace cxstring;
31using namespace cxtu;
32using namespace cxindex;
33
34namespace {
35
36//===----------------------------------------------------------------------===//
37// IndexPPCallbacks
38//===----------------------------------------------------------------------===//
39
40class IndexPPCallbacks : public PPCallbacks {
41 Preprocessor &PP;
42 IndexingContext &IndexCtx;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +000043 bool IsMainFileEntered;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000044
45public:
46 IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx)
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +000047 : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { }
48
49 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
50 SrcMgr::CharacteristicKind FileType, FileID PrevFID) {
51 if (IsMainFileEntered)
52 return;
53
54 SourceManager &SM = PP.getSourceManager();
55 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
56
57 if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) {
58 IsMainFileEntered = true;
59 IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID()));
60 }
61 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000062
63 virtual void InclusionDirective(SourceLocation HashLoc,
64 const Token &IncludeTok,
65 StringRef FileName,
66 bool IsAngled,
67 const FileEntry *File,
68 SourceLocation EndLoc,
69 StringRef SearchPath,
70 StringRef RelativePath) {
71 bool isImport = (IncludeTok.is(tok::identifier) &&
72 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
73 IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled);
74 }
75
76 /// MacroDefined - This hook is called whenever a macro definition is seen.
77 virtual void MacroDefined(const Token &Id, const MacroInfo *MI) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000078 }
79
80 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
81 /// MI is released immediately following this callback.
82 virtual void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000083 }
84
85 /// MacroExpands - This is called by when a macro invocation is found.
86 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI,
87 SourceRange Range) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000088 }
89
90 /// SourceRangeSkipped - This hook is called when a source range is skipped.
91 /// \param Range The SourceRange that was skipped. The range begins at the
92 /// #if/#else directive and ends after the #endif/#else directive.
93 virtual void SourceRangeSkipped(SourceRange Range) {
94 }
95};
96
97//===----------------------------------------------------------------------===//
98// IndexingConsumer
99//===----------------------------------------------------------------------===//
100
101class IndexingConsumer : public ASTConsumer {
102 IndexingContext &IndexCtx;
103
104public:
105 explicit IndexingConsumer(IndexingContext &indexCtx)
106 : IndexCtx(indexCtx) { }
107
108 // ASTConsumer Implementation
109
110 virtual void Initialize(ASTContext &Context) {
111 IndexCtx.setASTContext(Context);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000112 IndexCtx.startedTranslationUnit();
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000113 }
114
115 virtual void HandleTranslationUnit(ASTContext &Ctx) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000116 }
117
118 virtual void HandleTopLevelDecl(DeclGroupRef DG) {
119 IndexCtx.indexDeclGroupRef(DG);
120 }
121
122 /// \brief Handle the specified top-level declaration that occurred inside
123 /// and ObjC container.
124 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
125 // They will be handled after the interface is seen first.
126 IndexCtx.addTUDeclInObjCContainer(D);
127 }
128
129 /// \brief This is called by the AST reader when deserializing things.
130 /// The default implementation forwards to HandleTopLevelDecl but we don't
131 /// care about them when indexing, so have an empty definition.
132 virtual void HandleInterestingDecl(DeclGroupRef D) {}
133};
134
135//===----------------------------------------------------------------------===//
136// IndexingDiagnosticConsumer
137//===----------------------------------------------------------------------===//
138
139class IndexingDiagnosticConsumer : public DiagnosticConsumer {
140 IndexingContext &IndexCtx;
141
142public:
143 explicit IndexingDiagnosticConsumer(IndexingContext &indexCtx)
144 : IndexCtx(indexCtx) {}
145
146 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
147 const Diagnostic &Info) {
148 // Default implementation (Warnings/errors count).
149 DiagnosticConsumer::HandleDiagnostic(Level, Info);
150
151 IndexCtx.handleDiagnostic(StoredDiagnostic(Level, Info));
152 }
153
154 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
155 return new IgnoringDiagConsumer();
156 }
157};
158
159class 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;
180
181public:
182 IndexingFrontendAction(CXClientData clientData,
183 IndexerCallbacks &indexCallbacks,
184 unsigned indexOptions,
185 CXTranslationUnit cxTU)
186 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU) { }
187
188 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
189 StringRef InFile) {
190 CI.getDiagnostics().setClient(new IndexingDiagnosticConsumer(IndexCtx),
191 /*own=*/true);
192 IndexCtx.setASTContext(CI.getASTContext());
193 Preprocessor &PP = CI.getPreprocessor();
194 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx));
195 return new IndexingConsumer(IndexCtx);
196 }
197
198 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
199 virtual bool hasCodeCompletionSupport() const { return false; }
200};
201
202//===----------------------------------------------------------------------===//
203// clang_indexTranslationUnit Implementation
204//===----------------------------------------------------------------------===//
205
206struct IndexTranslationUnitInfo {
207 CXIndex CIdx;
208 CXClientData client_data;
209 IndexerCallbacks *index_callbacks;
210 unsigned index_callbacks_size;
211 unsigned index_options;
212 const char *source_filename;
213 const char *const *command_line_args;
214 int num_command_line_args;
215 struct CXUnsavedFile *unsaved_files;
216 unsigned num_unsaved_files;
217 CXTranslationUnit *out_TU;
218 unsigned TU_options;
219 int result;
220};
221
222struct MemBufferOwner {
223 SmallVector<const llvm::MemoryBuffer *, 8> Buffers;
224
225 ~MemBufferOwner() {
226 for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator
227 I = Buffers.begin(), E = Buffers.end(); I != E; ++I)
228 delete *I;
229 }
230};
231
232} // anonymous namespace
233
234static void clang_indexTranslationUnit_Impl(void *UserData) {
235 IndexTranslationUnitInfo *ITUI =
236 static_cast<IndexTranslationUnitInfo*>(UserData);
237 CXIndex CIdx = ITUI->CIdx;
238 CXClientData client_data = ITUI->client_data;
239 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
240 unsigned index_callbacks_size = ITUI->index_callbacks_size;
241 unsigned index_options = ITUI->index_options;
242 const char *source_filename = ITUI->source_filename;
243 const char * const *command_line_args = ITUI->command_line_args;
244 int num_command_line_args = ITUI->num_command_line_args;
245 struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files;
246 unsigned num_unsaved_files = ITUI->num_unsaved_files;
247 CXTranslationUnit *out_TU = ITUI->out_TU;
248 unsigned TU_options = ITUI->TU_options;
249 ITUI->result = 1; // init as error.
250
251 if (out_TU)
252 *out_TU = 0;
253 bool requestedToGetTU = (out_TU != 0);
254
255 if (!CIdx)
256 return;
257 if (!client_index_callbacks || index_callbacks_size == 0)
258 return;
259
260 IndexerCallbacks CB;
261 memset(&CB, 0, sizeof(CB));
262 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
263 ? index_callbacks_size : sizeof(CB);
264 memcpy(&CB, client_index_callbacks, ClientCBSize);
265
266 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
267
268 (void)CXXIdx;
269 (void)TU_options;
270
271 CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer();
272
273 // Configure the diagnostics.
274 DiagnosticOptions DiagOpts;
275 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
276 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
277 command_line_args,
278 CaptureDiag,
279 /*ShouldOwnClient=*/true));
280
281 // Recover resources if we crash before exiting this function.
282 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
283 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
284 DiagCleanup(Diags.getPtr());
285
286 llvm::OwningPtr<std::vector<const char *> >
287 Args(new std::vector<const char*>());
288
289 // Recover resources if we crash before exiting this method.
290 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
291 ArgsCleanup(Args.get());
292
293 Args->insert(Args->end(), command_line_args,
294 command_line_args + num_command_line_args);
295
296 // The 'source_filename' argument is optional. If the caller does not
297 // specify it then it is assumed that the source file is specified
298 // in the actual argument list.
299 // Put the source file after command_line_args otherwise if '-x' flag is
300 // present it will be unused.
301 if (source_filename)
302 Args->push_back(source_filename);
303
304 llvm::IntrusiveRefCntPtr<CompilerInvocation>
305 CInvok(createInvocationFromCommandLine(*Args, Diags));
306
307 if (!CInvok)
308 return;
309
310 // Recover resources if we crash before exiting this function.
311 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
312 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
313 CInvokCleanup(CInvok.getPtr());
314
315 if (CInvok->getFrontendOpts().Inputs.empty())
316 return;
317
318 llvm::OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner());
319
320 // Recover resources if we crash before exiting this method.
321 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner>
322 BufOwnerCleanup(BufOwner.get());
323
324 for (unsigned I = 0; I != num_unsaved_files; ++I) {
325 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
326 const llvm::MemoryBuffer *Buffer
327 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
328 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer);
329 BufOwner->Buffers.push_back(Buffer);
330 }
331
332 // Since libclang is primarily used by batch tools dealing with
333 // (often very broken) source code, where spell-checking can have a
334 // significant negative impact on performance (particularly when
335 // precompiled headers are involved), we disable it.
336 CInvok->getLangOpts().SpellChecking = false;
337
338 if (!requestedToGetTU)
339 CInvok->getPreprocessorOpts().DetailedRecord = false;
340
341 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags);
342 llvm::OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(Unit)));
343
344 // Recover resources if we crash before exiting this method.
345 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
346 CXTUCleanup(CXTU.get());
347
348 llvm::OwningPtr<IndexingFrontendAction> IndexAction;
349 IndexAction.reset(new IndexingFrontendAction(client_data, CB,
350 index_options, CXTU->getTU()));
351
352 // Recover resources if we crash before exiting this method.
353 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction>
354 IndexActionCleanup(IndexAction.get());
355
356 Unit = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags,
357 IndexAction.get(),
358 Unit);
359 if (!Unit)
360 return;
361
362 // FIXME: Set state of the ASTUnit according to the TU_options.
363 if (out_TU)
364 *out_TU = CXTU->takeTU();
365
366 ITUI->result = 0; // success.
367}
368
369//===----------------------------------------------------------------------===//
370// libclang public APIs.
371//===----------------------------------------------------------------------===//
372
373extern "C" {
374
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000375int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
376 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
377}
378
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000379const CXIdxObjCContainerDeclInfo *
380clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
381 if (!DInfo)
382 return 0;
383
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000384 if (clang_index_isEntityObjCContainerKind(DInfo->entityInfo->kind))
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000385 return &static_cast<const ObjCContainerDeclInfo*>(DInfo)->ObjCContDeclInfo;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000386
387 return 0;
388}
389
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000390const CXIdxObjCInterfaceDeclInfo *
391clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
392 if (!DInfo || DInfo->entityInfo->kind != CXIdxEntity_ObjCClass)
393 return 0;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000394
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000395 if (const CXIdxObjCContainerDeclInfo *
396 ContInfo = clang_index_getObjCContainerDeclInfo(DInfo)) {
397 if (ContInfo->kind == CXIdxObjCContainer_Interface)
398 return &static_cast<const ObjCInterfaceDeclInfo*>(DInfo)->ObjCInterDeclInfo;
399 }
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000400
401 return 0;
402}
403
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +0000404const CXIdxObjCProtocolDeclInfo *
405clang_index_getObjCProtocolDeclInfo(const CXIdxDeclInfo *DInfo) {
406 if (!DInfo || DInfo->entityInfo->kind != CXIdxEntity_ObjCProtocol)
407 return 0;
408
409 if (const CXIdxObjCContainerDeclInfo *
410 ContInfo = clang_index_getObjCContainerDeclInfo(DInfo)) {
411 if (ContInfo->kind == CXIdxObjCContainer_Interface)
412 return &static_cast<const ObjCProtocolDeclInfo*>(DInfo)->ObjCProtoDeclInfo;
413 }
414
415 return 0;
416}
417
418const CXIdxObjCCategoryDeclInfo *
419clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
420 if (!DInfo || DInfo->entityInfo->kind != CXIdxEntity_ObjCCategory)
421 return 0;
422
423 return &static_cast<const ObjCCategoryDeclInfo*>(DInfo)->ObjCCatDeclInfo;
424}
425
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000426int clang_indexTranslationUnit(CXIndex CIdx,
427 CXClientData client_data,
428 IndexerCallbacks *index_callbacks,
429 unsigned index_callbacks_size,
430 unsigned index_options,
431 const char *source_filename,
432 const char * const *command_line_args,
433 int num_command_line_args,
434 struct CXUnsavedFile *unsaved_files,
435 unsigned num_unsaved_files,
436 CXTranslationUnit *out_TU,
437 unsigned TU_options) {
438 IndexTranslationUnitInfo ITUI = { CIdx, client_data, index_callbacks,
439 index_callbacks_size, index_options,
440 source_filename, command_line_args,
441 num_command_line_args, unsaved_files,
442 num_unsaved_files, out_TU, TU_options, 0 };
443
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +0000444 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000445 clang_indexTranslationUnit_Impl(&ITUI);
446 return ITUI.result;
447 }
448
449 llvm::CrashRecoveryContext CRC;
450
451 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) {
452 fprintf(stderr, "libclang: crash detected during parsing: {\n");
453 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
454 fprintf(stderr, " 'command_line_args' : [");
455 for (int i = 0; i != num_command_line_args; ++i) {
456 if (i)
457 fprintf(stderr, ", ");
458 fprintf(stderr, "'%s'", command_line_args[i]);
459 }
460 fprintf(stderr, "],\n");
461 fprintf(stderr, " 'unsaved_files' : [");
462 for (unsigned i = 0; i != num_unsaved_files; ++i) {
463 if (i)
464 fprintf(stderr, ", ");
465 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
466 unsaved_files[i].Length);
467 }
468 fprintf(stderr, "],\n");
469 fprintf(stderr, " 'options' : %d,\n", TU_options);
470 fprintf(stderr, "}\n");
471
472 return 1;
473 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
474 if (out_TU)
475 PrintLibclangResourceUsage(*out_TU);
476 }
477
478 return ITUI.result;
479}
480
481void clang_indexLoc_getFileLocation(CXIdxLoc location,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +0000482 CXIdxClientFile *indexFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +0000483 CXFile *file,
484 unsigned *line,
485 unsigned *column,
486 unsigned *offset) {
487 if (indexFile) *indexFile = 0;
488 if (file) *file = 0;
489 if (line) *line = 0;
490 if (column) *column = 0;
491 if (offset) *offset = 0;
492
493 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
494 if (!location.ptr_data[0] || Loc.isInvalid())
495 return;
496
497 IndexingContext &IndexCtx =
498 *static_cast<IndexingContext*>(location.ptr_data[0]);
499 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset);
500}
501
502CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
503 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
504 if (!location.ptr_data[0] || Loc.isInvalid())
505 return clang_getNullLocation();
506
507 IndexingContext &IndexCtx =
508 *static_cast<IndexingContext*>(location.ptr_data[0]);
509 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc);
510}
511
512} // end: extern "C"
513