blob: bc80532b5b968529331d396f4a38dfd78a32bcb9 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
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 "ClangdUnit.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000011
Ilya Biryukov38d79772017-05-16 09:38:59 +000012#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000014#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000015#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000016#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000017#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Lex/Lexer.h"
19#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000021#include "clang/Lex/PreprocessorOptions.h"
22#include "clang/Sema/Sema.h"
23#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000024#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000025#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000028#include "llvm/Support/Format.h"
Ilya Biryukove5128f72017-09-20 07:24:15 +000029#include "Logger.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000030
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000031#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000032#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000033
Ilya Biryukov38d79772017-05-16 09:38:59 +000034using namespace clang::clangd;
35using namespace clang;
36
Ilya Biryukov04db3682017-07-21 13:29:29 +000037namespace {
38
39class DeclTrackingASTConsumer : public ASTConsumer {
40public:
41 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
42 : TopLevelDecls(TopLevelDecls) {}
43
44 bool HandleTopLevelDecl(DeclGroupRef DG) override {
45 for (const Decl *D : DG) {
46 // ObjCMethodDecl are not actually top-level decls.
47 if (isa<ObjCMethodDecl>(D))
48 continue;
49
50 TopLevelDecls.push_back(D);
51 }
52 return true;
53 }
54
55private:
56 std::vector<const Decl *> &TopLevelDecls;
57};
58
59class ClangdFrontendAction : public SyntaxOnlyAction {
60public:
61 std::vector<const Decl *> takeTopLevelDecls() {
62 return std::move(TopLevelDecls);
63 }
64
65protected:
66 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
67 StringRef InFile) override {
68 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
69 }
70
71private:
72 std::vector<const Decl *> TopLevelDecls;
73};
74
Ilya Biryukov02d58702017-08-01 15:51:38 +000075class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000076public:
77 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
78 return std::move(TopLevelDeclIDs);
79 }
80
81 void AfterPCHEmitted(ASTWriter &Writer) override {
82 TopLevelDeclIDs.reserve(TopLevelDecls.size());
83 for (Decl *D : TopLevelDecls) {
84 // Invalid top-level decls may not have been serialized.
85 if (D->isInvalidDecl())
86 continue;
87 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
88 }
89 }
90
91 void HandleTopLevelDecl(DeclGroupRef DG) override {
92 for (Decl *D : DG) {
93 if (isa<ObjCMethodDecl>(D))
94 continue;
95 TopLevelDecls.push_back(D);
96 }
97 }
98
99private:
100 std::vector<Decl *> TopLevelDecls;
101 std::vector<serialization::DeclID> TopLevelDeclIDs;
102};
103
104/// Convert from clang diagnostic level to LSP severity.
105static int getSeverity(DiagnosticsEngine::Level L) {
106 switch (L) {
107 case DiagnosticsEngine::Remark:
108 return 4;
109 case DiagnosticsEngine::Note:
110 return 3;
111 case DiagnosticsEngine::Warning:
112 return 2;
113 case DiagnosticsEngine::Fatal:
114 case DiagnosticsEngine::Error:
115 return 1;
116 case DiagnosticsEngine::Ignored:
117 return 0;
118 }
119 llvm_unreachable("Unknown diagnostic level!");
120}
121
122llvm::Optional<DiagWithFixIts> toClangdDiag(StoredDiagnostic D) {
123 auto Location = D.getLocation();
124 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
125 return llvm::None;
126
127 Position P;
128 P.line = Location.getSpellingLineNumber() - 1;
129 P.character = Location.getSpellingColumnNumber();
130 Range R = {P, P};
131 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
132
133 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
134 for (const FixItHint &Fix : D.getFixIts()) {
135 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
136 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
137 }
138 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
139}
140
141class StoreDiagsConsumer : public DiagnosticConsumer {
142public:
143 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
144
145 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
146 const clang::Diagnostic &Info) override {
147 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
148
149 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
150 Output.push_back(std::move(*convertedDiag));
151 }
152
153private:
154 std::vector<DiagWithFixIts> &Output;
155};
156
157class EmptyDiagsConsumer : public DiagnosticConsumer {
158public:
159 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
160 const clang::Diagnostic &Info) override {}
161};
162
163std::unique_ptr<CompilerInvocation>
164createCompilerInvocation(ArrayRef<const char *> ArgList,
165 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
166 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
167 auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags),
168 std::move(VFS));
169 // We rely on CompilerInstance to manage the resource (i.e. free them on
170 // EndSourceFile), but that won't happen if DisableFree is set to true.
171 // Since createInvocationFromCommandLine sets it to true, we have to override
172 // it.
173 CI->getFrontendOpts().DisableFree = false;
174 return CI;
175}
176
177/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
178/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
179/// null. Note that vfs::FileSystem inside returned instance may differ from \p
180/// VFS if additional file remapping were set in command-line arguments.
181/// On some errors, returns null. When non-null value is returned, it's expected
182/// to be consumed by the FrontendAction as it will have a pointer to the \p
183/// Buffer that will only be deleted if BeginSourceFile is called.
184std::unique_ptr<CompilerInstance>
185prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
186 const PrecompiledPreamble *Preamble,
187 std::unique_ptr<llvm::MemoryBuffer> Buffer,
188 std::shared_ptr<PCHContainerOperations> PCHs,
189 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
190 DiagnosticConsumer &DiagsClient) {
191 assert(VFS && "VFS is null");
192 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
193 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
194 "of ContentsBuffer");
195
196 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
197 // sure it will be released if no error is emitted.
198 if (Preamble) {
199 Preamble->AddImplicitPreamble(*CI, Buffer.get());
200 } else {
201 CI->getPreprocessorOpts().addRemappedFile(
202 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
203 }
204
205 auto Clang = llvm::make_unique<CompilerInstance>(PCHs);
206 Clang->setInvocation(std::move(CI));
207 Clang->createDiagnostics(&DiagsClient, false);
208
209 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
210 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
211 VFS = VFSWithRemapping;
212 Clang->setVirtualFileSystem(VFS);
213
214 Clang->setTarget(TargetInfo::CreateTargetInfo(
215 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
216 if (!Clang->hasTarget())
217 return nullptr;
218
219 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
220 // release it.
221 Buffer.release();
222 return Clang;
223}
224
Ilya Biryukov02d58702017-08-01 15:51:38 +0000225template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
226 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
227}
228
Ilya Biryukov04db3682017-07-21 13:29:29 +0000229} // namespace
230
Ilya Biryukov38d79772017-05-16 09:38:59 +0000231namespace {
232
233CompletionItemKind getKind(CXCursorKind K) {
234 switch (K) {
235 case CXCursor_MacroInstantiation:
236 case CXCursor_MacroDefinition:
237 return CompletionItemKind::Text;
238 case CXCursor_CXXMethod:
239 return CompletionItemKind::Method;
240 case CXCursor_FunctionDecl:
241 case CXCursor_FunctionTemplate:
242 return CompletionItemKind::Function;
243 case CXCursor_Constructor:
244 case CXCursor_Destructor:
245 return CompletionItemKind::Constructor;
246 case CXCursor_FieldDecl:
247 return CompletionItemKind::Field;
248 case CXCursor_VarDecl:
249 case CXCursor_ParmDecl:
250 return CompletionItemKind::Variable;
251 case CXCursor_ClassDecl:
252 case CXCursor_StructDecl:
253 case CXCursor_UnionDecl:
254 case CXCursor_ClassTemplate:
255 case CXCursor_ClassTemplatePartialSpecialization:
256 return CompletionItemKind::Class;
257 case CXCursor_Namespace:
258 case CXCursor_NamespaceAlias:
259 case CXCursor_NamespaceRef:
260 return CompletionItemKind::Module;
261 case CXCursor_EnumConstantDecl:
262 return CompletionItemKind::Value;
263 case CXCursor_EnumDecl:
264 return CompletionItemKind::Enum;
265 case CXCursor_TypeAliasDecl:
266 case CXCursor_TypeAliasTemplateDecl:
267 case CXCursor_TypedefDecl:
268 case CXCursor_MemberRef:
269 case CXCursor_TypeRef:
270 return CompletionItemKind::Reference;
271 default:
272 return CompletionItemKind::Missing;
273 }
274}
275
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000276std::string escapeSnippet(const llvm::StringRef Text) {
277 std::string Result;
278 Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
279 for (const auto Character : Text) {
280 if (Character == '$' || Character == '}' || Character == '\\')
281 Result.push_back('\\');
282 Result.push_back(Character);
283 }
284 return Result;
285}
286
Ilya Biryukov38d79772017-05-16 09:38:59 +0000287class CompletionItemsCollector : public CodeCompleteConsumer {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000288
289public:
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000290 CompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
291 std::vector<CompletionItem> &Items)
Ilya Biryukov38d79772017-05-16 09:38:59 +0000292 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
293 Items(Items),
294 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
295 CCTUInfo(Allocator) {}
296
297 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
298 CodeCompletionResult *Results,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000299 unsigned NumResults) override final {
300 Items.reserve(NumResults);
301 for (unsigned I = 0; I < NumResults; ++I) {
302 auto &Result = Results[I];
303 const auto *CCS = Result.CreateCodeCompletionString(
Ilya Biryukov38d79772017-05-16 09:38:59 +0000304 S, Context, *Allocator, CCTUInfo,
305 CodeCompleteOpts.IncludeBriefComments);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000306 assert(CCS && "Expected the CodeCompletionString to be non-null");
307 Items.push_back(ProcessCodeCompleteResult(Result, *CCS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000308 }
309 }
310
311 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
312
313 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000314
315private:
316 CompletionItem
317 ProcessCodeCompleteResult(const CodeCompletionResult &Result,
318 const CodeCompletionString &CCS) const {
319
320 // Adjust this to InsertTextFormat::Snippet iff we encounter a
321 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
322 CompletionItem Item;
323 Item.insertTextFormat = InsertTextFormat::PlainText;
324
325 FillDocumentation(CCS, Item);
326
327 // Fill in the label, detail, insertText and filterText fields of the
328 // CompletionItem.
329 ProcessChunks(CCS, Item);
330
331 // Fill in the kind field of the CompletionItem.
332 Item.kind = getKind(Result.CursorKind);
333
334 FillSortText(CCS, Item);
335
336 return Item;
337 }
338
339 virtual void ProcessChunks(const CodeCompletionString &CCS,
340 CompletionItem &Item) const = 0;
341
342 void FillDocumentation(const CodeCompletionString &CCS,
343 CompletionItem &Item) const {
344 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
345 // information in the documentation field.
346 const unsigned AnnotationCount = CCS.getAnnotationCount();
347 if (AnnotationCount > 0) {
348 Item.documentation += "Annotation";
349 if (AnnotationCount == 1) {
350 Item.documentation += ": ";
351 } else /* AnnotationCount > 1 */ {
352 Item.documentation += "s: ";
353 }
354 for (unsigned I = 0; I < AnnotationCount; ++I) {
355 Item.documentation += CCS.getAnnotation(I);
356 Item.documentation.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
357 }
358 }
359
360 // Add brief documentation (if there is any).
361 if (CCS.getBriefComment() != nullptr) {
362 if (!Item.documentation.empty()) {
363 // This means we previously added annotations. Add an extra newline
364 // character to make the annotations stand out.
365 Item.documentation.push_back('\n');
366 }
367 Item.documentation += CCS.getBriefComment();
368 }
369 }
370
371 void FillSortText(const CodeCompletionString &CCS,
372 CompletionItem &Item) const {
373 // Fill in the sortText of the CompletionItem.
374 assert(CCS.getPriority() < 99999 && "Expecting code completion result "
375 "priority to have at most 5-digits");
376 llvm::raw_string_ostream(Item.sortText)
377 << llvm::format("%05d%s", CCS.getPriority(), Item.filterText.c_str());
378 }
379
380 std::vector<CompletionItem> &Items;
381 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
382 CodeCompletionTUInfo CCTUInfo;
383
384}; // CompletionItemsCollector
385
386class PlainTextCompletionItemsCollector final
387 : public CompletionItemsCollector {
388
389public:
390 PlainTextCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
391 std::vector<CompletionItem> &Items)
392 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
393
394private:
395 void ProcessChunks(const CodeCompletionString &CCS,
396 CompletionItem &Item) const override {
397 for (const auto &Chunk : CCS) {
398 switch (Chunk.Kind) {
399 case CodeCompletionString::CK_TypedText:
400 // There's always exactly one CK_TypedText chunk.
401 Item.insertText = Item.filterText = Chunk.Text;
402 Item.label += Chunk.Text;
403 break;
404 case CodeCompletionString::CK_ResultType:
405 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
406 Item.detail = Chunk.Text;
407 break;
408 case CodeCompletionString::CK_Optional:
409 break;
410 default:
411 Item.label += Chunk.Text;
412 break;
413 }
414 }
415 }
416}; // PlainTextCompletionItemsCollector
417
418class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
419
420public:
421 SnippetCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
422 std::vector<CompletionItem> &Items)
423 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
424
425private:
426 void ProcessChunks(const CodeCompletionString &CCS,
427 CompletionItem &Item) const override {
428 unsigned ArgCount = 0;
429 for (const auto &Chunk : CCS) {
430 switch (Chunk.Kind) {
431 case CodeCompletionString::CK_TypedText:
432 // The piece of text that the user is expected to type to match
433 // the code-completion string, typically a keyword or the name of
434 // a declarator or macro.
435 Item.filterText = Chunk.Text;
436 // Note intentional fallthrough here.
437 case CodeCompletionString::CK_Text:
438 // A piece of text that should be placed in the buffer,
439 // e.g., parentheses or a comma in a function call.
440 Item.label += Chunk.Text;
441 Item.insertText += Chunk.Text;
442 break;
443 case CodeCompletionString::CK_Optional:
444 // A code completion string that is entirely optional.
445 // For example, an optional code completion string that
446 // describes the default arguments in a function call.
447
448 // FIXME: Maybe add an option to allow presenting the optional chunks?
449 break;
450 case CodeCompletionString::CK_Placeholder:
451 // A string that acts as a placeholder for, e.g., a function call
452 // argument.
453 ++ArgCount;
454 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
455 escapeSnippet(Chunk.Text) + '}';
456 Item.label += Chunk.Text;
457 Item.insertTextFormat = InsertTextFormat::Snippet;
458 break;
459 case CodeCompletionString::CK_Informative:
460 // A piece of text that describes something about the result
461 // but should not be inserted into the buffer.
462 // For example, the word "const" for a const method, or the name of
463 // the base class for methods that are part of the base class.
464 Item.label += Chunk.Text;
465 // Don't put the informative chunks in the insertText.
466 break;
467 case CodeCompletionString::CK_ResultType:
468 // A piece of text that describes the type of an entity or,
469 // for functions and methods, the return type.
470 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
471 Item.detail = Chunk.Text;
472 break;
473 case CodeCompletionString::CK_CurrentParameter:
474 // A piece of text that describes the parameter that corresponds to
475 // the code-completion location within a function call, message send,
476 // macro invocation, etc.
477 //
478 // This should never be present while collecting completion items,
479 // only while collecting overload candidates.
480 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
481 "CompletionItems");
482 break;
483 case CodeCompletionString::CK_LeftParen:
484 // A left parenthesis ('(').
485 case CodeCompletionString::CK_RightParen:
486 // A right parenthesis (')').
487 case CodeCompletionString::CK_LeftBracket:
488 // A left bracket ('[').
489 case CodeCompletionString::CK_RightBracket:
490 // A right bracket (']').
491 case CodeCompletionString::CK_LeftBrace:
492 // A left brace ('{').
493 case CodeCompletionString::CK_RightBrace:
494 // A right brace ('}').
495 case CodeCompletionString::CK_LeftAngle:
496 // A left angle bracket ('<').
497 case CodeCompletionString::CK_RightAngle:
498 // A right angle bracket ('>').
499 case CodeCompletionString::CK_Comma:
500 // A comma separator (',').
501 case CodeCompletionString::CK_Colon:
502 // A colon (':').
503 case CodeCompletionString::CK_SemiColon:
504 // A semicolon (';').
505 case CodeCompletionString::CK_Equal:
506 // An '=' sign.
507 case CodeCompletionString::CK_HorizontalSpace:
508 // Horizontal whitespace (' ').
509 Item.insertText += Chunk.Text;
510 Item.label += Chunk.Text;
511 break;
512 case CodeCompletionString::CK_VerticalSpace:
513 // Vertical whitespace ('\n' or '\r\n', depending on the
514 // platform).
515 Item.insertText += Chunk.Text;
516 // Don't even add a space to the label.
517 break;
518 }
519 }
520 }
521}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000522} // namespace
523
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000524std::vector<CompletionItem>
Ilya Biryukov02d58702017-08-01 15:51:38 +0000525clangd::codeComplete(PathRef FileName, tooling::CompileCommand Command,
526 PrecompiledPreamble const *Preamble, StringRef Contents,
527 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000528 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000529 bool SnippetCompletions, clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000530 std::vector<const char *> ArgStrs;
531 for (const auto &S : Command.CommandLine)
532 ArgStrs.push_back(S.c_str());
533
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000534 VFS->setCurrentWorkingDirectory(Command.Directory);
535
Ilya Biryukov04db3682017-07-21 13:29:29 +0000536 std::unique_ptr<CompilerInvocation> CI;
537 EmptyDiagsConsumer DummyDiagsConsumer;
538 {
539 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
540 CompilerInstance::createDiagnostics(new DiagnosticOptions,
541 &DummyDiagsConsumer, false);
542 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
543 }
544 assert(CI && "Couldn't create CompilerInvocation");
545
546 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
547 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
548
549 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000550 if (Preamble) {
551 auto Bounds =
552 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000553 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
554 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000555 }
556
Ilya Biryukov02d58702017-08-01 15:51:38 +0000557 auto Clang = prepareCompilerInstance(std::move(CI), Preamble,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000558 std::move(ContentsBuffer), PCHs, VFS,
559 DummyDiagsConsumer);
560 auto &DiagOpts = Clang->getDiagnosticOpts();
561 DiagOpts.IgnoreWarnings = true;
562
563 auto &FrontendOpts = Clang->getFrontendOpts();
564 FrontendOpts.SkipFunctionBodies = true;
565
566 FrontendOpts.CodeCompleteOpts.IncludeGlobals = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000567 FrontendOpts.CodeCompleteOpts.IncludeMacros = true;
568 FrontendOpts.CodeCompleteOpts.IncludeBriefComments = true;
569
570 FrontendOpts.CodeCompletionAt.FileName = FileName;
571 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
572 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
573
Ilya Biryukov38d79772017-05-16 09:38:59 +0000574 std::vector<CompletionItem> Items;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000575 if (SnippetCompletions) {
576 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = true;
577 Clang->setCodeCompletionConsumer(new SnippetCompletionItemsCollector(
578 FrontendOpts.CodeCompleteOpts, Items));
579 } else {
580 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = false;
581 Clang->setCodeCompletionConsumer(new PlainTextCompletionItemsCollector(
582 FrontendOpts.CodeCompleteOpts, Items));
583 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000584
Ilya Biryukov04db3682017-07-21 13:29:29 +0000585 SyntaxOnlyAction Action;
586 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000587 Logger.log("BeginSourceFile() failed when running codeComplete for " +
588 FileName);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000589 return Items;
590 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000591 if (!Action.Execute())
592 Logger.log("Execute() failed when running codeComplete for " + FileName);
593
Ilya Biryukov04db3682017-07-21 13:29:29 +0000594 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000595
Ilya Biryukov38d79772017-05-16 09:38:59 +0000596 return Items;
597}
598
Ilya Biryukov02d58702017-08-01 15:51:38 +0000599void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
600 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000601}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000602
Ilya Biryukov02d58702017-08-01 15:51:38 +0000603llvm::Optional<ParsedAST>
604ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
605 const PrecompiledPreamble *Preamble,
606 ArrayRef<serialization::DeclID> PreambleDeclIDs,
607 std::unique_ptr<llvm::MemoryBuffer> Buffer,
608 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000609 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
610 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000611
612 std::vector<DiagWithFixIts> ASTDiags;
613 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
614
615 auto Clang =
616 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
617 VFS, /*ref*/ UnitDiagsConsumer);
618
619 // Recover resources if we crash before exiting this method.
620 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
621 Clang.get());
622
623 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000624 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
625 if (!Action->BeginSourceFile(*Clang, MainInput)) {
626 Logger.log("BeginSourceFile() failed when building AST for " +
627 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000628 return llvm::None;
629 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000630 if (!Action->Execute())
631 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000632
633 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
634 // has a longer lifetime.
635 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
636
637 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
638 std::vector<serialization::DeclID> PendingDecls;
639 if (Preamble) {
640 PendingDecls.reserve(PreambleDeclIDs.size());
641 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
642 PreambleDeclIDs.end());
643 }
644
645 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
646 std::move(PendingDecls), std::move(ASTDiags));
647}
648
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000649namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000650
651SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
652 const FileEntry *FE,
653 unsigned Offset) {
654 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
655 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
656}
657
658SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
659 const FileEntry *FE, Position Pos) {
660 SourceLocation InputLoc =
661 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
662 return Mgr.getMacroArgExpandedLocation(InputLoc);
663}
664
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000665/// Finds declarations locations that a given source location refers to.
666class DeclarationLocationsFinder : public index::IndexDataConsumer {
667 std::vector<Location> DeclarationLocations;
668 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000669 const ASTContext &AST;
670 Preprocessor &PP;
671
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000672public:
673 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000674 const SourceLocation &SearchedLocation,
675 ASTContext &AST, Preprocessor &PP)
676 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000677
678 std::vector<Location> takeLocations() {
679 // Don't keep the same location multiple times.
680 // This can happen when nodes in the AST are visited twice.
681 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000682 auto last =
683 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000684 DeclarationLocations.erase(last, DeclarationLocations.end());
685 return std::move(DeclarationLocations);
686 }
687
Ilya Biryukov02d58702017-08-01 15:51:38 +0000688 bool
689 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
690 ArrayRef<index::SymbolRelation> Relations, FileID FID,
691 unsigned Offset,
692 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000693 if (isSearchedLocation(FID, Offset)) {
694 addDeclarationLocation(D->getSourceRange());
695 }
696 return true;
697 }
698
699private:
700 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000701 const SourceManager &SourceMgr = AST.getSourceManager();
702 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
703 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000704 }
705
Ilya Biryukov04db3682017-07-21 13:29:29 +0000706 void addDeclarationLocation(const SourceRange &ValSourceRange) {
707 const SourceManager &SourceMgr = AST.getSourceManager();
708 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000709 SourceLocation LocStart = ValSourceRange.getBegin();
710 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000711 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000712 Position Begin;
713 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
714 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
715 Position End;
716 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
717 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
718 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000719 Location L;
720 L.uri = URI::fromFile(
721 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
722 L.range = R;
723 DeclarationLocations.push_back(L);
724 }
725
Kirill Bobyrev46213872017-06-28 20:57:28 +0000726 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000727 // Also handle possible macro at the searched location.
728 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000729 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
730 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000731 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000732 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000733 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000734 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000735 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
736 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000737 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000738 // Get the definition just before the searched location so that a macro
739 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000740 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
741 AST.getSourceManager(),
742 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000743 DecLoc.second - 1);
744 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000745 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
746 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000747 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000748 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
749 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000750 }
751 }
752 }
753 }
754};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000755
Ilya Biryukov02d58702017-08-01 15:51:38 +0000756SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
757 const FileEntry *FE) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000758 // The language server protocol uses zero-based line and column numbers.
759 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000760
Ilya Biryukov02d58702017-08-01 15:51:38 +0000761 const ASTContext &AST = Unit.getASTContext();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000762 const SourceManager &SourceMgr = AST.getSourceManager();
763
764 SourceLocation InputLocation =
765 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000766 if (Pos.character == 0) {
767 return InputLocation;
768 }
769
770 // This handle cases where the position is in the middle of a token or right
771 // after the end of a token. In theory we could just use GetBeginningOfToken
772 // to find the start of the token at the input position, but this doesn't
773 // work when right after the end, i.e. foo|.
774 // So try to go back by one and see if we're still inside the an identifier
775 // token. If so, Take the beginning of this token.
776 // (It should be the same identifier because you can't have two adjacent
777 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000778 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
779 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000780 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000781 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000782 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000783 // getRawToken failed, just use InputLocation.
784 return InputLocation;
785 }
786
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000787 if (Result.is(tok::raw_identifier)) {
788 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000789 AST.getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000790 }
791
792 return InputLocation;
793}
Ilya Biryukov02d58702017-08-01 15:51:38 +0000794} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000795
Ilya Biryukove5128f72017-09-20 07:24:15 +0000796std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
797 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000798 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
799 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
800 if (!FE)
801 return {};
802
803 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
804
805 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
806 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
807 AST.getPreprocessor());
808 index::IndexingOptions IndexOpts;
809 IndexOpts.SystemSymbolFilter =
810 index::IndexingOptions::SystemSymbolFilterKind::All;
811 IndexOpts.IndexFunctionLocals = true;
812
813 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
814 DeclLocationsFinder, IndexOpts);
815
816 return DeclLocationsFinder->takeLocations();
817}
818
819void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000820 if (PendingTopLevelDecls.empty())
821 return;
822
823 std::vector<const Decl *> Resolved;
824 Resolved.reserve(PendingTopLevelDecls.size());
825
826 ExternalASTSource &Source = *getASTContext().getExternalSource();
827 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
828 // Resolve the declaration ID to an actual declaration, possibly
829 // deserializing the declaration in the process.
830 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
831 Resolved.push_back(D);
832 }
833
834 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
835 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
836
837 PendingTopLevelDecls.clear();
838}
839
Ilya Biryukov02d58702017-08-01 15:51:38 +0000840ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000841
Ilya Biryukov02d58702017-08-01 15:51:38 +0000842ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000843
Ilya Biryukov02d58702017-08-01 15:51:38 +0000844ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000845 if (Action) {
846 Action->EndSourceFile();
847 }
848}
849
Ilya Biryukov02d58702017-08-01 15:51:38 +0000850ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
851
852const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000853 return Clang->getASTContext();
854}
855
Ilya Biryukov02d58702017-08-01 15:51:38 +0000856Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000857
Ilya Biryukov02d58702017-08-01 15:51:38 +0000858const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000859 return Clang->getPreprocessor();
860}
861
Ilya Biryukov02d58702017-08-01 15:51:38 +0000862ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000863 ensurePreambleDeclsDeserialized();
864 return TopLevelDecls;
865}
866
Ilya Biryukov02d58702017-08-01 15:51:38 +0000867const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000868 return Diags;
869}
870
Ilya Biryukov02d58702017-08-01 15:51:38 +0000871ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
872 std::unique_ptr<FrontendAction> Action,
873 std::vector<const Decl *> TopLevelDecls,
874 std::vector<serialization::DeclID> PendingTopLevelDecls,
875 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000876 : Clang(std::move(Clang)), Action(std::move(Action)),
877 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
878 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
879 assert(this->Clang);
880 assert(this->Action);
881}
882
Ilya Biryukov02d58702017-08-01 15:51:38 +0000883ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
884 : AST(std::move(Wrapper.AST)) {}
885
886ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
887 : AST(std::move(AST)) {}
888
889PreambleData::PreambleData(PrecompiledPreamble Preamble,
890 std::vector<serialization::DeclID> TopLevelDeclIDs,
891 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000892 : Preamble(std::move(Preamble)),
893 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +0000894
895std::shared_ptr<CppFile>
896CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000897 std::shared_ptr<PCHContainerOperations> PCHs, clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000898 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000899 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000900}
901
902CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000903 std::shared_ptr<PCHContainerOperations> PCHs,
904 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000905 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +0000906 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000907
908 std::lock_guard<std::mutex> Lock(Mutex);
909 LatestAvailablePreamble = nullptr;
910 PreamblePromise.set_value(nullptr);
911 PreambleFuture = PreamblePromise.get_future();
912
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000913 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000914 ASTFuture = ASTPromise.get_future();
915}
916
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000917void CppFile::cancelRebuild() { deferCancelRebuild().get(); }
918
919std::future<void> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000920 std::unique_lock<std::mutex> Lock(Mutex);
921 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000922 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000923 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
924 // We want to keep this invariant.
925 if (futureIsReady(PreambleFuture)) {
926 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
927 PreambleFuture = PreamblePromise.get_future();
928 }
929 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000930 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000931 ASTFuture = ASTPromise.get_future();
932 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000933
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000934 Lock.unlock();
935 // Notify about changes to RebuildCounter.
936 RebuildCond.notify_all();
937
938 std::shared_ptr<CppFile> That = shared_from_this();
939 return std::async(std::launch::deferred, [That, RequestRebuildCounter]() {
940 std::unique_lock<std::mutex> Lock(That->Mutex);
941 CppFile *This = &*That;
942 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
943 return !This->RebuildInProgress ||
944 This->RebuildCounter != RequestRebuildCounter;
945 });
946
947 // This computation got cancelled itself, do nothing.
948 if (This->RebuildCounter != RequestRebuildCounter)
949 return;
950
951 // Set empty results for Promises.
952 That->PreamblePromise.set_value(nullptr);
953 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
954 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000955}
956
957llvm::Optional<std::vector<DiagWithFixIts>>
958CppFile::rebuild(StringRef NewContents,
959 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
960 return deferRebuild(NewContents, std::move(VFS)).get();
961}
962
963std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
964CppFile::deferRebuild(StringRef NewContents,
965 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
966 std::shared_ptr<const PreambleData> OldPreamble;
967 std::shared_ptr<PCHContainerOperations> PCHs;
968 unsigned RequestRebuildCounter;
969 {
970 std::unique_lock<std::mutex> Lock(Mutex);
971 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
972 // They will try to exit as early as possible and won't call set_value on
973 // our promises.
974 RequestRebuildCounter = ++this->RebuildCounter;
975 PCHs = this->PCHs;
976
977 // Remember the preamble to be used during rebuild.
978 OldPreamble = this->LatestAvailablePreamble;
979 // Setup std::promises and std::futures for Preamble and AST. Corresponding
980 // futures will wait until the rebuild process is finished.
981 if (futureIsReady(this->PreambleFuture)) {
982 this->PreamblePromise =
983 std::promise<std::shared_ptr<const PreambleData>>();
984 this->PreambleFuture = this->PreamblePromise.get_future();
985 }
986 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000987 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000988 this->ASTFuture = this->ASTPromise.get_future();
989 }
990 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000991 // Notify about changes to RebuildCounter.
992 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000993
994 // A helper to function to finish the rebuild. May be run on a different
995 // thread.
996
997 // Don't let this CppFile die before rebuild is finished.
998 std::shared_ptr<CppFile> That = shared_from_this();
999 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1000 That](std::string NewContents)
1001 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1002 // Only one execution of this method is possible at a time.
1003 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1004 // into a state for doing a rebuild.
1005 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1006 if (Rebuild.wasCancelledBeforeConstruction())
1007 return llvm::None;
1008
1009 std::vector<const char *> ArgStrs;
1010 for (const auto &S : That->Command.CommandLine)
1011 ArgStrs.push_back(S.c_str());
1012
1013 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1014
1015 std::unique_ptr<CompilerInvocation> CI;
1016 {
1017 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1018 // reporting them.
1019 EmptyDiagsConsumer CommandLineDiagsConsumer;
1020 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1021 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1022 &CommandLineDiagsConsumer, false);
1023 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1024 }
1025 assert(CI && "Couldn't create CompilerInvocation");
1026
1027 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1028 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1029
1030 // A helper function to rebuild the preamble or reuse the existing one. Does
1031 // not mutate any fields, only does the actual computation.
1032 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1033 auto Bounds =
1034 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1035 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1036 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1037 return OldPreamble;
1038 }
1039
1040 std::vector<DiagWithFixIts> PreambleDiags;
1041 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1042 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1043 CompilerInstance::createDiagnostics(
1044 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1045 CppFilePreambleCallbacks SerializedDeclsCollector;
1046 auto BuiltPreamble = PrecompiledPreamble::Build(
1047 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
1048 SerializedDeclsCollector);
1049
1050 if (BuiltPreamble) {
1051 return std::make_shared<PreambleData>(
1052 std::move(*BuiltPreamble),
1053 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1054 std::move(PreambleDiags));
1055 } else {
1056 return nullptr;
1057 }
1058 };
1059
1060 // Compute updated Preamble.
1061 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1062 // Publish the new Preamble.
1063 {
1064 std::lock_guard<std::mutex> Lock(That->Mutex);
1065 // We always set LatestAvailablePreamble to the new value, hoping that it
1066 // will still be usable in the further requests.
1067 That->LatestAvailablePreamble = NewPreamble;
1068 if (RequestRebuildCounter != That->RebuildCounter)
1069 return llvm::None; // Our rebuild request was cancelled, do nothing.
1070 That->PreamblePromise.set_value(NewPreamble);
1071 } // unlock Mutex
1072
1073 // Prepare the Preamble and supplementary data for rebuilding AST.
1074 const PrecompiledPreamble *PreambleForAST = nullptr;
1075 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1076 std::vector<DiagWithFixIts> Diagnostics;
1077 if (NewPreamble) {
1078 PreambleForAST = &NewPreamble->Preamble;
1079 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1080 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1081 NewPreamble->Diags.end());
1082 }
1083
1084 // Compute updated AST.
1085 llvm::Optional<ParsedAST> NewAST =
1086 ParsedAST::Build(std::move(CI), PreambleForAST, SerializedPreambleDecls,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001087 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001088
1089 if (NewAST) {
1090 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1091 NewAST->getDiagnostics().end());
1092 } else {
1093 // Don't report even Preamble diagnostics if we coulnd't build AST.
1094 Diagnostics.clear();
1095 }
1096
1097 // Publish the new AST.
1098 {
1099 std::lock_guard<std::mutex> Lock(That->Mutex);
1100 if (RequestRebuildCounter != That->RebuildCounter)
1101 return Diagnostics; // Our rebuild request was cancelled, don't set
1102 // ASTPromise.
1103
Ilya Biryukov574b7532017-08-02 09:08:39 +00001104 That->ASTPromise.set_value(
1105 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001106 } // unlock Mutex
1107
1108 return Diagnostics;
1109 };
1110
1111 return std::async(std::launch::deferred, FinishRebuild, NewContents.str());
1112}
1113
1114std::shared_future<std::shared_ptr<const PreambleData>>
1115CppFile::getPreamble() const {
1116 std::lock_guard<std::mutex> Lock(Mutex);
1117 return PreambleFuture;
1118}
1119
1120std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1121 std::lock_guard<std::mutex> Lock(Mutex);
1122 return LatestAvailablePreamble;
1123}
1124
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001125std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001126 std::lock_guard<std::mutex> Lock(Mutex);
1127 return ASTFuture;
1128}
1129
1130tooling::CompileCommand const &CppFile::getCompileCommand() const {
1131 return Command;
1132}
1133
1134CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1135 unsigned RequestRebuildCounter)
1136 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1137 std::unique_lock<std::mutex> Lock(File.Mutex);
1138 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1139 if (WasCancelledBeforeConstruction)
1140 return;
1141
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001142 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1143 return !File.RebuildInProgress ||
1144 File.RebuildCounter != RequestRebuildCounter;
1145 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001146
1147 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1148 if (WasCancelledBeforeConstruction)
1149 return;
1150
1151 File.RebuildInProgress = true;
1152}
1153
1154bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1155 return WasCancelledBeforeConstruction;
1156}
1157
1158CppFile::RebuildGuard::~RebuildGuard() {
1159 if (WasCancelledBeforeConstruction)
1160 return;
1161
1162 std::unique_lock<std::mutex> Lock(File.Mutex);
1163 assert(File.RebuildInProgress);
1164 File.RebuildInProgress = false;
1165
1166 if (File.RebuildCounter == RequestRebuildCounter) {
1167 // Our rebuild request was successful.
1168 assert(futureIsReady(File.ASTFuture));
1169 assert(futureIsReady(File.PreambleFuture));
1170 } else {
1171 // Our rebuild request was cancelled, because further reparse was requested.
1172 assert(!futureIsReady(File.ASTFuture));
1173 assert(!futureIsReady(File.PreambleFuture));
1174 }
1175
1176 Lock.unlock();
1177 File.RebuildCond.notify_all();
1178}