blob: af9e78133c9eb72b8310e585376cbf01dabdc55b [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 Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000015#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000016#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000017#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000018#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000019#include "clang/Lex/Lexer.h"
20#include "clang/Lex/MacroInfo.h"
21#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000022#include "clang/Lex/PreprocessorOptions.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000029#include "llvm/Support/Format.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
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000371 static int GetSortPriority(const CodeCompletionString &CCS) {
372 int Score = CCS.getPriority();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000373 // Fill in the sortText of the CompletionItem.
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000374 assert(Score <= 99999 && "Expecting code completion result "
375 "priority to have at most 5-digits");
376
377 const int Penalty = 100000;
378 switch (static_cast<CXAvailabilityKind>(CCS.getAvailability())) {
379 case CXAvailability_Available:
380 // No penalty.
381 break;
382 case CXAvailability_Deprecated:
383 Score += Penalty;
384 break;
385 case CXAvailability_NotAccessible:
386 Score += 2 * Penalty;
387 break;
388 case CXAvailability_NotAvailable:
389 Score += 3 * Penalty;
390 break;
391 }
392
393 return Score;
394 }
395
396 static void FillSortText(const CodeCompletionString &CCS,
397 CompletionItem &Item) {
398 int Priority = GetSortPriority(CCS);
399 // Fill in the sortText of the CompletionItem.
400 assert(Priority <= 999999 &&
401 "Expecting sort priority to have at most 6-digits");
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000402 llvm::raw_string_ostream(Item.sortText)
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000403 << llvm::format("%06d%s", Priority, Item.filterText.c_str());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000404 }
405
406 std::vector<CompletionItem> &Items;
407 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
408 CodeCompletionTUInfo CCTUInfo;
409
410}; // CompletionItemsCollector
411
412class PlainTextCompletionItemsCollector final
413 : public CompletionItemsCollector {
414
415public:
416 PlainTextCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
417 std::vector<CompletionItem> &Items)
418 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
419
420private:
421 void ProcessChunks(const CodeCompletionString &CCS,
422 CompletionItem &Item) const override {
423 for (const auto &Chunk : CCS) {
424 switch (Chunk.Kind) {
425 case CodeCompletionString::CK_TypedText:
426 // There's always exactly one CK_TypedText chunk.
427 Item.insertText = Item.filterText = Chunk.Text;
428 Item.label += Chunk.Text;
429 break;
430 case CodeCompletionString::CK_ResultType:
431 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
432 Item.detail = Chunk.Text;
433 break;
434 case CodeCompletionString::CK_Optional:
435 break;
436 default:
437 Item.label += Chunk.Text;
438 break;
439 }
440 }
441 }
442}; // PlainTextCompletionItemsCollector
443
444class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
445
446public:
447 SnippetCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
448 std::vector<CompletionItem> &Items)
449 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
450
451private:
452 void ProcessChunks(const CodeCompletionString &CCS,
453 CompletionItem &Item) const override {
454 unsigned ArgCount = 0;
455 for (const auto &Chunk : CCS) {
456 switch (Chunk.Kind) {
457 case CodeCompletionString::CK_TypedText:
458 // The piece of text that the user is expected to type to match
459 // the code-completion string, typically a keyword or the name of
460 // a declarator or macro.
461 Item.filterText = Chunk.Text;
462 // Note intentional fallthrough here.
463 case CodeCompletionString::CK_Text:
464 // A piece of text that should be placed in the buffer,
465 // e.g., parentheses or a comma in a function call.
466 Item.label += Chunk.Text;
467 Item.insertText += Chunk.Text;
468 break;
469 case CodeCompletionString::CK_Optional:
470 // A code completion string that is entirely optional.
471 // For example, an optional code completion string that
472 // describes the default arguments in a function call.
473
474 // FIXME: Maybe add an option to allow presenting the optional chunks?
475 break;
476 case CodeCompletionString::CK_Placeholder:
477 // A string that acts as a placeholder for, e.g., a function call
478 // argument.
479 ++ArgCount;
480 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
481 escapeSnippet(Chunk.Text) + '}';
482 Item.label += Chunk.Text;
483 Item.insertTextFormat = InsertTextFormat::Snippet;
484 break;
485 case CodeCompletionString::CK_Informative:
486 // A piece of text that describes something about the result
487 // but should not be inserted into the buffer.
488 // For example, the word "const" for a const method, or the name of
489 // the base class for methods that are part of the base class.
490 Item.label += Chunk.Text;
491 // Don't put the informative chunks in the insertText.
492 break;
493 case CodeCompletionString::CK_ResultType:
494 // A piece of text that describes the type of an entity or,
495 // for functions and methods, the return type.
496 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
497 Item.detail = Chunk.Text;
498 break;
499 case CodeCompletionString::CK_CurrentParameter:
500 // A piece of text that describes the parameter that corresponds to
501 // the code-completion location within a function call, message send,
502 // macro invocation, etc.
503 //
504 // This should never be present while collecting completion items,
505 // only while collecting overload candidates.
506 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
507 "CompletionItems");
508 break;
509 case CodeCompletionString::CK_LeftParen:
510 // A left parenthesis ('(').
511 case CodeCompletionString::CK_RightParen:
512 // A right parenthesis (')').
513 case CodeCompletionString::CK_LeftBracket:
514 // A left bracket ('[').
515 case CodeCompletionString::CK_RightBracket:
516 // A right bracket (']').
517 case CodeCompletionString::CK_LeftBrace:
518 // A left brace ('{').
519 case CodeCompletionString::CK_RightBrace:
520 // A right brace ('}').
521 case CodeCompletionString::CK_LeftAngle:
522 // A left angle bracket ('<').
523 case CodeCompletionString::CK_RightAngle:
524 // A right angle bracket ('>').
525 case CodeCompletionString::CK_Comma:
526 // A comma separator (',').
527 case CodeCompletionString::CK_Colon:
528 // A colon (':').
529 case CodeCompletionString::CK_SemiColon:
530 // A semicolon (';').
531 case CodeCompletionString::CK_Equal:
532 // An '=' sign.
533 case CodeCompletionString::CK_HorizontalSpace:
534 // Horizontal whitespace (' ').
535 Item.insertText += Chunk.Text;
536 Item.label += Chunk.Text;
537 break;
538 case CodeCompletionString::CK_VerticalSpace:
539 // Vertical whitespace ('\n' or '\r\n', depending on the
540 // platform).
541 Item.insertText += Chunk.Text;
542 // Don't even add a space to the label.
543 break;
544 }
545 }
546 }
547}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000548} // namespace
549
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000550std::vector<CompletionItem>
Ilya Biryukov02d58702017-08-01 15:51:38 +0000551clangd::codeComplete(PathRef FileName, tooling::CompileCommand Command,
552 PrecompiledPreamble const *Preamble, StringRef Contents,
553 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000554 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000555 bool SnippetCompletions, clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000556 std::vector<const char *> ArgStrs;
557 for (const auto &S : Command.CommandLine)
558 ArgStrs.push_back(S.c_str());
559
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000560 VFS->setCurrentWorkingDirectory(Command.Directory);
561
Ilya Biryukov04db3682017-07-21 13:29:29 +0000562 std::unique_ptr<CompilerInvocation> CI;
563 EmptyDiagsConsumer DummyDiagsConsumer;
564 {
565 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
566 CompilerInstance::createDiagnostics(new DiagnosticOptions,
567 &DummyDiagsConsumer, false);
568 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
569 }
570 assert(CI && "Couldn't create CompilerInvocation");
571
572 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
573 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
574
575 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000576 if (Preamble) {
577 auto Bounds =
578 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000579 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
580 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000581 }
582
Ilya Biryukov02d58702017-08-01 15:51:38 +0000583 auto Clang = prepareCompilerInstance(std::move(CI), Preamble,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000584 std::move(ContentsBuffer), PCHs, VFS,
585 DummyDiagsConsumer);
586 auto &DiagOpts = Clang->getDiagnosticOpts();
587 DiagOpts.IgnoreWarnings = true;
588
589 auto &FrontendOpts = Clang->getFrontendOpts();
590 FrontendOpts.SkipFunctionBodies = true;
591
592 FrontendOpts.CodeCompleteOpts.IncludeGlobals = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000593 FrontendOpts.CodeCompleteOpts.IncludeMacros = true;
594 FrontendOpts.CodeCompleteOpts.IncludeBriefComments = true;
595
596 FrontendOpts.CodeCompletionAt.FileName = FileName;
597 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
598 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
599
Ilya Biryukov38d79772017-05-16 09:38:59 +0000600 std::vector<CompletionItem> Items;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000601 if (SnippetCompletions) {
602 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = true;
603 Clang->setCodeCompletionConsumer(new SnippetCompletionItemsCollector(
604 FrontendOpts.CodeCompleteOpts, Items));
605 } else {
606 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = false;
607 Clang->setCodeCompletionConsumer(new PlainTextCompletionItemsCollector(
608 FrontendOpts.CodeCompleteOpts, Items));
609 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000610
Ilya Biryukov04db3682017-07-21 13:29:29 +0000611 SyntaxOnlyAction Action;
612 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000613 Logger.log("BeginSourceFile() failed when running codeComplete for " +
614 FileName);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000615 return Items;
616 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000617 if (!Action.Execute())
618 Logger.log("Execute() failed when running codeComplete for " + FileName);
619
Ilya Biryukov04db3682017-07-21 13:29:29 +0000620 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000621
Ilya Biryukov38d79772017-05-16 09:38:59 +0000622 return Items;
623}
624
Ilya Biryukov02d58702017-08-01 15:51:38 +0000625void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
626 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000627}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000628
Ilya Biryukov02d58702017-08-01 15:51:38 +0000629llvm::Optional<ParsedAST>
630ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
631 const PrecompiledPreamble *Preamble,
632 ArrayRef<serialization::DeclID> PreambleDeclIDs,
633 std::unique_ptr<llvm::MemoryBuffer> Buffer,
634 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000635 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
636 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000637
638 std::vector<DiagWithFixIts> ASTDiags;
639 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
640
641 auto Clang =
642 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
643 VFS, /*ref*/ UnitDiagsConsumer);
644
645 // Recover resources if we crash before exiting this method.
646 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
647 Clang.get());
648
649 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000650 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
651 if (!Action->BeginSourceFile(*Clang, MainInput)) {
652 Logger.log("BeginSourceFile() failed when building AST for " +
653 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000654 return llvm::None;
655 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000656 if (!Action->Execute())
657 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000658
659 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
660 // has a longer lifetime.
661 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
662
663 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
664 std::vector<serialization::DeclID> PendingDecls;
665 if (Preamble) {
666 PendingDecls.reserve(PreambleDeclIDs.size());
667 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
668 PreambleDeclIDs.end());
669 }
670
671 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
672 std::move(PendingDecls), std::move(ASTDiags));
673}
674
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000675namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000676
677SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
678 const FileEntry *FE,
679 unsigned Offset) {
680 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
681 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
682}
683
684SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
685 const FileEntry *FE, Position Pos) {
686 SourceLocation InputLoc =
687 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
688 return Mgr.getMacroArgExpandedLocation(InputLoc);
689}
690
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000691/// Finds declarations locations that a given source location refers to.
692class DeclarationLocationsFinder : public index::IndexDataConsumer {
693 std::vector<Location> DeclarationLocations;
694 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000695 const ASTContext &AST;
696 Preprocessor &PP;
697
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000698public:
699 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000700 const SourceLocation &SearchedLocation,
701 ASTContext &AST, Preprocessor &PP)
702 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000703
704 std::vector<Location> takeLocations() {
705 // Don't keep the same location multiple times.
706 // This can happen when nodes in the AST are visited twice.
707 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000708 auto last =
709 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000710 DeclarationLocations.erase(last, DeclarationLocations.end());
711 return std::move(DeclarationLocations);
712 }
713
Ilya Biryukov02d58702017-08-01 15:51:38 +0000714 bool
715 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
716 ArrayRef<index::SymbolRelation> Relations, FileID FID,
717 unsigned Offset,
718 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000719 if (isSearchedLocation(FID, Offset)) {
720 addDeclarationLocation(D->getSourceRange());
721 }
722 return true;
723 }
724
725private:
726 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000727 const SourceManager &SourceMgr = AST.getSourceManager();
728 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
729 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000730 }
731
Ilya Biryukov04db3682017-07-21 13:29:29 +0000732 void addDeclarationLocation(const SourceRange &ValSourceRange) {
733 const SourceManager &SourceMgr = AST.getSourceManager();
734 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000735 SourceLocation LocStart = ValSourceRange.getBegin();
736 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000737 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000738 Position Begin;
739 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
740 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
741 Position End;
742 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
743 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
744 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000745 Location L;
746 L.uri = URI::fromFile(
747 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
748 L.range = R;
749 DeclarationLocations.push_back(L);
750 }
751
Kirill Bobyrev46213872017-06-28 20:57:28 +0000752 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000753 // Also handle possible macro at the searched location.
754 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000755 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
756 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000757 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000758 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000759 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000760 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000761 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
762 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000763 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000764 // Get the definition just before the searched location so that a macro
765 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000766 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
767 AST.getSourceManager(),
768 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000769 DecLoc.second - 1);
770 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000771 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
772 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000773 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000774 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
775 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000776 }
777 }
778 }
779 }
780};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000781
Ilya Biryukov02d58702017-08-01 15:51:38 +0000782SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
783 const FileEntry *FE) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000784 // The language server protocol uses zero-based line and column numbers.
785 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000786
Ilya Biryukov02d58702017-08-01 15:51:38 +0000787 const ASTContext &AST = Unit.getASTContext();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000788 const SourceManager &SourceMgr = AST.getSourceManager();
789
790 SourceLocation InputLocation =
791 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000792 if (Pos.character == 0) {
793 return InputLocation;
794 }
795
796 // This handle cases where the position is in the middle of a token or right
797 // after the end of a token. In theory we could just use GetBeginningOfToken
798 // to find the start of the token at the input position, but this doesn't
799 // work when right after the end, i.e. foo|.
800 // So try to go back by one and see if we're still inside the an identifier
801 // token. If so, Take the beginning of this token.
802 // (It should be the same identifier because you can't have two adjacent
803 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000804 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
805 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000806 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000807 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000808 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000809 // getRawToken failed, just use InputLocation.
810 return InputLocation;
811 }
812
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000813 if (Result.is(tok::raw_identifier)) {
814 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000815 AST.getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000816 }
817
818 return InputLocation;
819}
Ilya Biryukov02d58702017-08-01 15:51:38 +0000820} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000821
Ilya Biryukove5128f72017-09-20 07:24:15 +0000822std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
823 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000824 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
825 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
826 if (!FE)
827 return {};
828
829 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
830
831 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
832 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
833 AST.getPreprocessor());
834 index::IndexingOptions IndexOpts;
835 IndexOpts.SystemSymbolFilter =
836 index::IndexingOptions::SystemSymbolFilterKind::All;
837 IndexOpts.IndexFunctionLocals = true;
838
839 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
840 DeclLocationsFinder, IndexOpts);
841
842 return DeclLocationsFinder->takeLocations();
843}
844
845void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000846 if (PendingTopLevelDecls.empty())
847 return;
848
849 std::vector<const Decl *> Resolved;
850 Resolved.reserve(PendingTopLevelDecls.size());
851
852 ExternalASTSource &Source = *getASTContext().getExternalSource();
853 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
854 // Resolve the declaration ID to an actual declaration, possibly
855 // deserializing the declaration in the process.
856 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
857 Resolved.push_back(D);
858 }
859
860 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
861 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
862
863 PendingTopLevelDecls.clear();
864}
865
Ilya Biryukov02d58702017-08-01 15:51:38 +0000866ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000867
Ilya Biryukov02d58702017-08-01 15:51:38 +0000868ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000869
Ilya Biryukov02d58702017-08-01 15:51:38 +0000870ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000871 if (Action) {
872 Action->EndSourceFile();
873 }
874}
875
Ilya Biryukov02d58702017-08-01 15:51:38 +0000876ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
877
878const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000879 return Clang->getASTContext();
880}
881
Ilya Biryukov02d58702017-08-01 15:51:38 +0000882Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000883
Ilya Biryukov02d58702017-08-01 15:51:38 +0000884const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000885 return Clang->getPreprocessor();
886}
887
Ilya Biryukov02d58702017-08-01 15:51:38 +0000888ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000889 ensurePreambleDeclsDeserialized();
890 return TopLevelDecls;
891}
892
Ilya Biryukov02d58702017-08-01 15:51:38 +0000893const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000894 return Diags;
895}
896
Ilya Biryukov02d58702017-08-01 15:51:38 +0000897ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
898 std::unique_ptr<FrontendAction> Action,
899 std::vector<const Decl *> TopLevelDecls,
900 std::vector<serialization::DeclID> PendingTopLevelDecls,
901 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000902 : Clang(std::move(Clang)), Action(std::move(Action)),
903 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
904 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
905 assert(this->Clang);
906 assert(this->Action);
907}
908
Ilya Biryukov02d58702017-08-01 15:51:38 +0000909ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
910 : AST(std::move(Wrapper.AST)) {}
911
912ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
913 : AST(std::move(AST)) {}
914
915PreambleData::PreambleData(PrecompiledPreamble Preamble,
916 std::vector<serialization::DeclID> TopLevelDeclIDs,
917 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000918 : Preamble(std::move(Preamble)),
919 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +0000920
921std::shared_ptr<CppFile>
922CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +0000923 std::shared_ptr<PCHContainerOperations> PCHs,
924 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000925 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000926 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000927}
928
929CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000930 std::shared_ptr<PCHContainerOperations> PCHs,
931 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000932 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +0000933 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000934
935 std::lock_guard<std::mutex> Lock(Mutex);
936 LatestAvailablePreamble = nullptr;
937 PreamblePromise.set_value(nullptr);
938 PreambleFuture = PreamblePromise.get_future();
939
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000940 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000941 ASTFuture = ASTPromise.get_future();
942}
943
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000944void CppFile::cancelRebuild() { deferCancelRebuild().get(); }
945
946std::future<void> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000947 std::unique_lock<std::mutex> Lock(Mutex);
948 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000949 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000950 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
951 // We want to keep this invariant.
952 if (futureIsReady(PreambleFuture)) {
953 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
954 PreambleFuture = PreamblePromise.get_future();
955 }
956 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000957 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000958 ASTFuture = ASTPromise.get_future();
959 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000960
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000961 Lock.unlock();
962 // Notify about changes to RebuildCounter.
963 RebuildCond.notify_all();
964
965 std::shared_ptr<CppFile> That = shared_from_this();
966 return std::async(std::launch::deferred, [That, RequestRebuildCounter]() {
967 std::unique_lock<std::mutex> Lock(That->Mutex);
968 CppFile *This = &*That;
969 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
970 return !This->RebuildInProgress ||
971 This->RebuildCounter != RequestRebuildCounter;
972 });
973
974 // This computation got cancelled itself, do nothing.
975 if (This->RebuildCounter != RequestRebuildCounter)
976 return;
977
978 // Set empty results for Promises.
979 That->PreamblePromise.set_value(nullptr);
980 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
981 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000982}
983
984llvm::Optional<std::vector<DiagWithFixIts>>
985CppFile::rebuild(StringRef NewContents,
986 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
987 return deferRebuild(NewContents, std::move(VFS)).get();
988}
989
990std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
991CppFile::deferRebuild(StringRef NewContents,
992 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
993 std::shared_ptr<const PreambleData> OldPreamble;
994 std::shared_ptr<PCHContainerOperations> PCHs;
995 unsigned RequestRebuildCounter;
996 {
997 std::unique_lock<std::mutex> Lock(Mutex);
998 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
999 // They will try to exit as early as possible and won't call set_value on
1000 // our promises.
1001 RequestRebuildCounter = ++this->RebuildCounter;
1002 PCHs = this->PCHs;
1003
1004 // Remember the preamble to be used during rebuild.
1005 OldPreamble = this->LatestAvailablePreamble;
1006 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1007 // futures will wait until the rebuild process is finished.
1008 if (futureIsReady(this->PreambleFuture)) {
1009 this->PreamblePromise =
1010 std::promise<std::shared_ptr<const PreambleData>>();
1011 this->PreambleFuture = this->PreamblePromise.get_future();
1012 }
1013 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001014 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001015 this->ASTFuture = this->ASTPromise.get_future();
1016 }
1017 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001018 // Notify about changes to RebuildCounter.
1019 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001020
1021 // A helper to function to finish the rebuild. May be run on a different
1022 // thread.
1023
1024 // Don't let this CppFile die before rebuild is finished.
1025 std::shared_ptr<CppFile> That = shared_from_this();
1026 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1027 That](std::string NewContents)
1028 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1029 // Only one execution of this method is possible at a time.
1030 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1031 // into a state for doing a rebuild.
1032 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1033 if (Rebuild.wasCancelledBeforeConstruction())
1034 return llvm::None;
1035
1036 std::vector<const char *> ArgStrs;
1037 for (const auto &S : That->Command.CommandLine)
1038 ArgStrs.push_back(S.c_str());
1039
1040 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1041
1042 std::unique_ptr<CompilerInvocation> CI;
1043 {
1044 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1045 // reporting them.
1046 EmptyDiagsConsumer CommandLineDiagsConsumer;
1047 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1048 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1049 &CommandLineDiagsConsumer, false);
1050 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1051 }
1052 assert(CI && "Couldn't create CompilerInvocation");
1053
1054 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1055 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1056
1057 // A helper function to rebuild the preamble or reuse the existing one. Does
1058 // not mutate any fields, only does the actual computation.
1059 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1060 auto Bounds =
1061 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1062 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1063 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1064 return OldPreamble;
1065 }
1066
1067 std::vector<DiagWithFixIts> PreambleDiags;
1068 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1069 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1070 CompilerInstance::createDiagnostics(
1071 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1072 CppFilePreambleCallbacks SerializedDeclsCollector;
1073 auto BuiltPreamble = PrecompiledPreamble::Build(
1074 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
1075 SerializedDeclsCollector);
1076
1077 if (BuiltPreamble) {
1078 return std::make_shared<PreambleData>(
1079 std::move(*BuiltPreamble),
1080 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1081 std::move(PreambleDiags));
1082 } else {
1083 return nullptr;
1084 }
1085 };
1086
1087 // Compute updated Preamble.
1088 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1089 // Publish the new Preamble.
1090 {
1091 std::lock_guard<std::mutex> Lock(That->Mutex);
1092 // We always set LatestAvailablePreamble to the new value, hoping that it
1093 // will still be usable in the further requests.
1094 That->LatestAvailablePreamble = NewPreamble;
1095 if (RequestRebuildCounter != That->RebuildCounter)
1096 return llvm::None; // Our rebuild request was cancelled, do nothing.
1097 That->PreamblePromise.set_value(NewPreamble);
1098 } // unlock Mutex
1099
1100 // Prepare the Preamble and supplementary data for rebuilding AST.
1101 const PrecompiledPreamble *PreambleForAST = nullptr;
1102 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1103 std::vector<DiagWithFixIts> Diagnostics;
1104 if (NewPreamble) {
1105 PreambleForAST = &NewPreamble->Preamble;
1106 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1107 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1108 NewPreamble->Diags.end());
1109 }
1110
1111 // Compute updated AST.
1112 llvm::Optional<ParsedAST> NewAST =
1113 ParsedAST::Build(std::move(CI), PreambleForAST, SerializedPreambleDecls,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001114 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001115
1116 if (NewAST) {
1117 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1118 NewAST->getDiagnostics().end());
1119 } else {
1120 // Don't report even Preamble diagnostics if we coulnd't build AST.
1121 Diagnostics.clear();
1122 }
1123
1124 // Publish the new AST.
1125 {
1126 std::lock_guard<std::mutex> Lock(That->Mutex);
1127 if (RequestRebuildCounter != That->RebuildCounter)
1128 return Diagnostics; // Our rebuild request was cancelled, don't set
1129 // ASTPromise.
1130
Ilya Biryukov574b7532017-08-02 09:08:39 +00001131 That->ASTPromise.set_value(
1132 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001133 } // unlock Mutex
1134
1135 return Diagnostics;
1136 };
1137
1138 return std::async(std::launch::deferred, FinishRebuild, NewContents.str());
1139}
1140
1141std::shared_future<std::shared_ptr<const PreambleData>>
1142CppFile::getPreamble() const {
1143 std::lock_guard<std::mutex> Lock(Mutex);
1144 return PreambleFuture;
1145}
1146
1147std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1148 std::lock_guard<std::mutex> Lock(Mutex);
1149 return LatestAvailablePreamble;
1150}
1151
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001152std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001153 std::lock_guard<std::mutex> Lock(Mutex);
1154 return ASTFuture;
1155}
1156
1157tooling::CompileCommand const &CppFile::getCompileCommand() const {
1158 return Command;
1159}
1160
1161CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1162 unsigned RequestRebuildCounter)
1163 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1164 std::unique_lock<std::mutex> Lock(File.Mutex);
1165 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1166 if (WasCancelledBeforeConstruction)
1167 return;
1168
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001169 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1170 return !File.RebuildInProgress ||
1171 File.RebuildCounter != RequestRebuildCounter;
1172 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001173
1174 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1175 if (WasCancelledBeforeConstruction)
1176 return;
1177
1178 File.RebuildInProgress = true;
1179}
1180
1181bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1182 return WasCancelledBeforeConstruction;
1183}
1184
1185CppFile::RebuildGuard::~RebuildGuard() {
1186 if (WasCancelledBeforeConstruction)
1187 return;
1188
1189 std::unique_lock<std::mutex> Lock(File.Mutex);
1190 assert(File.RebuildInProgress);
1191 File.RebuildInProgress = false;
1192
1193 if (File.RebuildCounter == RequestRebuildCounter) {
1194 // Our rebuild request was successful.
1195 assert(futureIsReady(File.ASTFuture));
1196 assert(futureIsReady(File.PreambleFuture));
1197 } else {
1198 // Our rebuild request was cancelled, because further reparse was requested.
1199 assert(!futureIsReady(File.ASTFuture));
1200 assert(!futureIsReady(File.PreambleFuture));
1201 }
1202
1203 Lock.unlock();
1204 File.RebuildCond.notify_all();
1205}