blob: 83c97b2babff4e201dc2cc8b1e803b76b4569074 [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"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Lex/PreprocessorOptions.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000027#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000030#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000031
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000033#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000034
Ilya Biryukov38d79772017-05-16 09:38:59 +000035using namespace clang::clangd;
36using namespace clang;
37
Ilya Biryukov04db3682017-07-21 13:29:29 +000038namespace {
39
40class DeclTrackingASTConsumer : public ASTConsumer {
41public:
42 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
43 : TopLevelDecls(TopLevelDecls) {}
44
45 bool HandleTopLevelDecl(DeclGroupRef DG) override {
46 for (const Decl *D : DG) {
47 // ObjCMethodDecl are not actually top-level decls.
48 if (isa<ObjCMethodDecl>(D))
49 continue;
50
51 TopLevelDecls.push_back(D);
52 }
53 return true;
54 }
55
56private:
57 std::vector<const Decl *> &TopLevelDecls;
58};
59
60class ClangdFrontendAction : public SyntaxOnlyAction {
61public:
62 std::vector<const Decl *> takeTopLevelDecls() {
63 return std::move(TopLevelDecls);
64 }
65
66protected:
67 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
68 StringRef InFile) override {
69 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
70 }
71
72private:
73 std::vector<const Decl *> TopLevelDecls;
74};
75
Ilya Biryukov02d58702017-08-01 15:51:38 +000076class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000077public:
78 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
79 return std::move(TopLevelDeclIDs);
80 }
81
82 void AfterPCHEmitted(ASTWriter &Writer) override {
83 TopLevelDeclIDs.reserve(TopLevelDecls.size());
84 for (Decl *D : TopLevelDecls) {
85 // Invalid top-level decls may not have been serialized.
86 if (D->isInvalidDecl())
87 continue;
88 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
89 }
90 }
91
92 void HandleTopLevelDecl(DeclGroupRef DG) override {
93 for (Decl *D : DG) {
94 if (isa<ObjCMethodDecl>(D))
95 continue;
96 TopLevelDecls.push_back(D);
97 }
98 }
99
100private:
101 std::vector<Decl *> TopLevelDecls;
102 std::vector<serialization::DeclID> TopLevelDeclIDs;
103};
104
105/// Convert from clang diagnostic level to LSP severity.
106static int getSeverity(DiagnosticsEngine::Level L) {
107 switch (L) {
108 case DiagnosticsEngine::Remark:
109 return 4;
110 case DiagnosticsEngine::Note:
111 return 3;
112 case DiagnosticsEngine::Warning:
113 return 2;
114 case DiagnosticsEngine::Fatal:
115 case DiagnosticsEngine::Error:
116 return 1;
117 case DiagnosticsEngine::Ignored:
118 return 0;
119 }
120 llvm_unreachable("Unknown diagnostic level!");
121}
122
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000123/// Get the optional chunk as a string. This function is possibly recursive.
124///
125/// The parameter info for each parameter is appended to the Parameters.
126std::string
127getOptionalParameters(const CodeCompletionString &CCS,
128 std::vector<ParameterInformation> &Parameters) {
129 std::string Result;
130 for (const auto &Chunk : CCS) {
131 switch (Chunk.Kind) {
132 case CodeCompletionString::CK_Optional:
133 assert(Chunk.Optional &&
134 "Expected the optional code completion string to be non-null.");
135 Result += getOptionalParameters(*Chunk.Optional, Parameters);
136 break;
137 case CodeCompletionString::CK_VerticalSpace:
138 break;
139 case CodeCompletionString::CK_Placeholder:
140 // A string that acts as a placeholder for, e.g., a function call
141 // argument.
142 // Intentional fallthrough here.
143 case CodeCompletionString::CK_CurrentParameter: {
144 // A piece of text that describes the parameter that corresponds to
145 // the code-completion location within a function call, message send,
146 // macro invocation, etc.
147 Result += Chunk.Text;
148 ParameterInformation Info;
149 Info.label = Chunk.Text;
150 Parameters.push_back(std::move(Info));
151 break;
152 }
153 default:
154 Result += Chunk.Text;
155 break;
156 }
157 }
158 return Result;
159}
160
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000161llvm::Optional<DiagWithFixIts> toClangdDiag(const StoredDiagnostic &D) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000162 auto Location = D.getLocation();
163 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
164 return llvm::None;
165
166 Position P;
167 P.line = Location.getSpellingLineNumber() - 1;
168 P.character = Location.getSpellingColumnNumber();
169 Range R = {P, P};
170 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
171
172 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
173 for (const FixItHint &Fix : D.getFixIts()) {
174 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
175 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
176 }
177 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
178}
179
180class StoreDiagsConsumer : public DiagnosticConsumer {
181public:
182 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
183
184 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
185 const clang::Diagnostic &Info) override {
186 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
187
188 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
189 Output.push_back(std::move(*convertedDiag));
190 }
191
192private:
193 std::vector<DiagWithFixIts> &Output;
194};
195
196class EmptyDiagsConsumer : public DiagnosticConsumer {
197public:
198 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
199 const clang::Diagnostic &Info) override {}
200};
201
202std::unique_ptr<CompilerInvocation>
203createCompilerInvocation(ArrayRef<const char *> ArgList,
204 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
205 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
206 auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags),
207 std::move(VFS));
208 // We rely on CompilerInstance to manage the resource (i.e. free them on
209 // EndSourceFile), but that won't happen if DisableFree is set to true.
210 // Since createInvocationFromCommandLine sets it to true, we have to override
211 // it.
212 CI->getFrontendOpts().DisableFree = false;
213 return CI;
214}
215
216/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
217/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
218/// null. Note that vfs::FileSystem inside returned instance may differ from \p
219/// VFS if additional file remapping were set in command-line arguments.
220/// On some errors, returns null. When non-null value is returned, it's expected
221/// to be consumed by the FrontendAction as it will have a pointer to the \p
222/// Buffer that will only be deleted if BeginSourceFile is called.
223std::unique_ptr<CompilerInstance>
224prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
225 const PrecompiledPreamble *Preamble,
226 std::unique_ptr<llvm::MemoryBuffer> Buffer,
227 std::shared_ptr<PCHContainerOperations> PCHs,
228 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
229 DiagnosticConsumer &DiagsClient) {
230 assert(VFS && "VFS is null");
231 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
232 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
233 "of ContentsBuffer");
234
235 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
236 // sure it will be released if no error is emitted.
237 if (Preamble) {
238 Preamble->AddImplicitPreamble(*CI, Buffer.get());
239 } else {
240 CI->getPreprocessorOpts().addRemappedFile(
241 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
242 }
243
244 auto Clang = llvm::make_unique<CompilerInstance>(PCHs);
245 Clang->setInvocation(std::move(CI));
246 Clang->createDiagnostics(&DiagsClient, false);
247
248 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
249 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
250 VFS = VFSWithRemapping;
251 Clang->setVirtualFileSystem(VFS);
252
253 Clang->setTarget(TargetInfo::CreateTargetInfo(
254 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
255 if (!Clang->hasTarget())
256 return nullptr;
257
258 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
259 // release it.
260 Buffer.release();
261 return Clang;
262}
263
Ilya Biryukov02d58702017-08-01 15:51:38 +0000264template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
265 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
266}
267
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268} // namespace
269
Ilya Biryukov38d79772017-05-16 09:38:59 +0000270namespace {
271
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000272CompletionItemKind getKindOfDecl(CXCursorKind CursorKind) {
273 switch (CursorKind) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000274 case CXCursor_MacroInstantiation:
275 case CXCursor_MacroDefinition:
276 return CompletionItemKind::Text;
277 case CXCursor_CXXMethod:
278 return CompletionItemKind::Method;
279 case CXCursor_FunctionDecl:
280 case CXCursor_FunctionTemplate:
281 return CompletionItemKind::Function;
282 case CXCursor_Constructor:
283 case CXCursor_Destructor:
284 return CompletionItemKind::Constructor;
285 case CXCursor_FieldDecl:
286 return CompletionItemKind::Field;
287 case CXCursor_VarDecl:
288 case CXCursor_ParmDecl:
289 return CompletionItemKind::Variable;
290 case CXCursor_ClassDecl:
291 case CXCursor_StructDecl:
292 case CXCursor_UnionDecl:
293 case CXCursor_ClassTemplate:
294 case CXCursor_ClassTemplatePartialSpecialization:
295 return CompletionItemKind::Class;
296 case CXCursor_Namespace:
297 case CXCursor_NamespaceAlias:
298 case CXCursor_NamespaceRef:
299 return CompletionItemKind::Module;
300 case CXCursor_EnumConstantDecl:
301 return CompletionItemKind::Value;
302 case CXCursor_EnumDecl:
303 return CompletionItemKind::Enum;
304 case CXCursor_TypeAliasDecl:
305 case CXCursor_TypeAliasTemplateDecl:
306 case CXCursor_TypedefDecl:
307 case CXCursor_MemberRef:
308 case CXCursor_TypeRef:
309 return CompletionItemKind::Reference;
310 default:
311 return CompletionItemKind::Missing;
312 }
313}
314
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000315CompletionItemKind getKind(CodeCompletionResult::ResultKind ResKind,
316 CXCursorKind CursorKind) {
317 switch (ResKind) {
318 case CodeCompletionResult::RK_Declaration:
319 return getKindOfDecl(CursorKind);
320 case CodeCompletionResult::RK_Keyword:
321 return CompletionItemKind::Keyword;
322 case CodeCompletionResult::RK_Macro:
323 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
324 // completion items in LSP.
325 case CodeCompletionResult::RK_Pattern:
326 return CompletionItemKind::Snippet;
327 }
328 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
329}
330
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000331std::string escapeSnippet(const llvm::StringRef Text) {
332 std::string Result;
333 Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
334 for (const auto Character : Text) {
335 if (Character == '$' || Character == '}' || Character == '\\')
336 Result.push_back('\\');
337 Result.push_back(Character);
338 }
339 return Result;
340}
341
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000342std::string getDocumentation(const CodeCompletionString &CCS) {
343 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
344 // information in the documentation field.
345 std::string Result;
346 const unsigned AnnotationCount = CCS.getAnnotationCount();
347 if (AnnotationCount > 0) {
348 Result += "Annotation";
349 if (AnnotationCount == 1) {
350 Result += ": ";
351 } else /* AnnotationCount > 1 */ {
352 Result += "s: ";
353 }
354 for (unsigned I = 0; I < AnnotationCount; ++I) {
355 Result += CCS.getAnnotation(I);
356 Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
357 }
358 }
359 // Add brief documentation (if there is any).
360 if (CCS.getBriefComment() != nullptr) {
361 if (!Result.empty()) {
362 // This means we previously added annotations. Add an extra newline
363 // character to make the annotations stand out.
364 Result.push_back('\n');
365 }
366 Result += CCS.getBriefComment();
367 }
368 return Result;
369}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000370
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000371class CompletionItemsCollector : public CodeCompleteConsumer {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000372public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000373 CompletionItemsCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000374 std::vector<CompletionItem> &Items)
Ilya Biryukov38d79772017-05-16 09:38:59 +0000375 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
376 Items(Items),
377 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
378 CCTUInfo(Allocator) {}
379
380 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
381 CodeCompletionResult *Results,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000382 unsigned NumResults) override final {
383 Items.reserve(NumResults);
384 for (unsigned I = 0; I < NumResults; ++I) {
385 auto &Result = Results[I];
386 const auto *CCS = Result.CreateCodeCompletionString(
Ilya Biryukov38d79772017-05-16 09:38:59 +0000387 S, Context, *Allocator, CCTUInfo,
388 CodeCompleteOpts.IncludeBriefComments);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000389 assert(CCS && "Expected the CodeCompletionString to be non-null");
390 Items.push_back(ProcessCodeCompleteResult(Result, *CCS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000391 }
392 }
393
394 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
395
396 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000397
398private:
399 CompletionItem
400 ProcessCodeCompleteResult(const CodeCompletionResult &Result,
401 const CodeCompletionString &CCS) const {
402
403 // Adjust this to InsertTextFormat::Snippet iff we encounter a
404 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
405 CompletionItem Item;
406 Item.insertTextFormat = InsertTextFormat::PlainText;
407
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000408 Item.documentation = getDocumentation(CCS);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000409
410 // Fill in the label, detail, insertText and filterText fields of the
411 // CompletionItem.
412 ProcessChunks(CCS, Item);
413
414 // Fill in the kind field of the CompletionItem.
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000415 Item.kind = getKind(Result.Kind, Result.CursorKind);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000416
417 FillSortText(CCS, Item);
418
419 return Item;
420 }
421
422 virtual void ProcessChunks(const CodeCompletionString &CCS,
423 CompletionItem &Item) const = 0;
424
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000425 static int GetSortPriority(const CodeCompletionString &CCS) {
426 int Score = CCS.getPriority();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000427 // Fill in the sortText of the CompletionItem.
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000428 assert(Score <= 99999 && "Expecting code completion result "
429 "priority to have at most 5-digits");
430
431 const int Penalty = 100000;
432 switch (static_cast<CXAvailabilityKind>(CCS.getAvailability())) {
433 case CXAvailability_Available:
434 // No penalty.
435 break;
436 case CXAvailability_Deprecated:
437 Score += Penalty;
438 break;
439 case CXAvailability_NotAccessible:
440 Score += 2 * Penalty;
441 break;
442 case CXAvailability_NotAvailable:
443 Score += 3 * Penalty;
444 break;
445 }
446
447 return Score;
448 }
449
450 static void FillSortText(const CodeCompletionString &CCS,
451 CompletionItem &Item) {
452 int Priority = GetSortPriority(CCS);
453 // Fill in the sortText of the CompletionItem.
454 assert(Priority <= 999999 &&
455 "Expecting sort priority to have at most 6-digits");
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000456 llvm::raw_string_ostream(Item.sortText)
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000457 << llvm::format("%06d%s", Priority, Item.filterText.c_str());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000458 }
459
460 std::vector<CompletionItem> &Items;
461 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
462 CodeCompletionTUInfo CCTUInfo;
463
464}; // CompletionItemsCollector
465
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000466bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
467 return Chunk.Kind == CodeCompletionString::CK_Informative &&
468 StringRef(Chunk.Text).endswith("::");
469}
470
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000471class PlainTextCompletionItemsCollector final
472 : public CompletionItemsCollector {
473
474public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000475 PlainTextCompletionItemsCollector(
476 const clang::CodeCompleteOptions &CodeCompleteOpts,
477 std::vector<CompletionItem> &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000478 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
479
480private:
481 void ProcessChunks(const CodeCompletionString &CCS,
482 CompletionItem &Item) const override {
483 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000484 // Informative qualifier chunks only clutter completion results, skip
485 // them.
486 if (isInformativeQualifierChunk(Chunk))
487 continue;
488
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000489 switch (Chunk.Kind) {
490 case CodeCompletionString::CK_TypedText:
491 // There's always exactly one CK_TypedText chunk.
492 Item.insertText = Item.filterText = Chunk.Text;
493 Item.label += Chunk.Text;
494 break;
495 case CodeCompletionString::CK_ResultType:
496 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
497 Item.detail = Chunk.Text;
498 break;
499 case CodeCompletionString::CK_Optional:
500 break;
501 default:
502 Item.label += Chunk.Text;
503 break;
504 }
505 }
506 }
507}; // PlainTextCompletionItemsCollector
508
509class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
510
511public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000512 SnippetCompletionItemsCollector(
513 const clang::CodeCompleteOptions &CodeCompleteOpts,
514 std::vector<CompletionItem> &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000515 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
516
517private:
518 void ProcessChunks(const CodeCompletionString &CCS,
519 CompletionItem &Item) const override {
520 unsigned ArgCount = 0;
521 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000522 // Informative qualifier chunks only clutter completion results, skip
523 // them.
524 if (isInformativeQualifierChunk(Chunk))
525 continue;
526
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000527 switch (Chunk.Kind) {
528 case CodeCompletionString::CK_TypedText:
529 // The piece of text that the user is expected to type to match
530 // the code-completion string, typically a keyword or the name of
531 // a declarator or macro.
532 Item.filterText = Chunk.Text;
Simon Pilgrim948c0bc2017-11-01 09:22:03 +0000533 LLVM_FALLTHROUGH;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000534 case CodeCompletionString::CK_Text:
535 // A piece of text that should be placed in the buffer,
536 // e.g., parentheses or a comma in a function call.
537 Item.label += Chunk.Text;
538 Item.insertText += Chunk.Text;
539 break;
540 case CodeCompletionString::CK_Optional:
541 // A code completion string that is entirely optional.
542 // For example, an optional code completion string that
543 // describes the default arguments in a function call.
544
545 // FIXME: Maybe add an option to allow presenting the optional chunks?
546 break;
547 case CodeCompletionString::CK_Placeholder:
548 // A string that acts as a placeholder for, e.g., a function call
549 // argument.
550 ++ArgCount;
551 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
552 escapeSnippet(Chunk.Text) + '}';
553 Item.label += Chunk.Text;
554 Item.insertTextFormat = InsertTextFormat::Snippet;
555 break;
556 case CodeCompletionString::CK_Informative:
557 // A piece of text that describes something about the result
558 // but should not be inserted into the buffer.
559 // For example, the word "const" for a const method, or the name of
560 // the base class for methods that are part of the base class.
561 Item.label += Chunk.Text;
562 // Don't put the informative chunks in the insertText.
563 break;
564 case CodeCompletionString::CK_ResultType:
565 // A piece of text that describes the type of an entity or,
566 // for functions and methods, the return type.
567 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
568 Item.detail = Chunk.Text;
569 break;
570 case CodeCompletionString::CK_CurrentParameter:
571 // A piece of text that describes the parameter that corresponds to
572 // the code-completion location within a function call, message send,
573 // macro invocation, etc.
574 //
575 // This should never be present while collecting completion items,
576 // only while collecting overload candidates.
577 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
578 "CompletionItems");
579 break;
580 case CodeCompletionString::CK_LeftParen:
581 // A left parenthesis ('(').
582 case CodeCompletionString::CK_RightParen:
583 // A right parenthesis (')').
584 case CodeCompletionString::CK_LeftBracket:
585 // A left bracket ('[').
586 case CodeCompletionString::CK_RightBracket:
587 // A right bracket (']').
588 case CodeCompletionString::CK_LeftBrace:
589 // A left brace ('{').
590 case CodeCompletionString::CK_RightBrace:
591 // A right brace ('}').
592 case CodeCompletionString::CK_LeftAngle:
593 // A left angle bracket ('<').
594 case CodeCompletionString::CK_RightAngle:
595 // A right angle bracket ('>').
596 case CodeCompletionString::CK_Comma:
597 // A comma separator (',').
598 case CodeCompletionString::CK_Colon:
599 // A colon (':').
600 case CodeCompletionString::CK_SemiColon:
601 // A semicolon (';').
602 case CodeCompletionString::CK_Equal:
603 // An '=' sign.
604 case CodeCompletionString::CK_HorizontalSpace:
605 // Horizontal whitespace (' ').
606 Item.insertText += Chunk.Text;
607 Item.label += Chunk.Text;
608 break;
609 case CodeCompletionString::CK_VerticalSpace:
610 // Vertical whitespace ('\n' or '\r\n', depending on the
611 // platform).
612 Item.insertText += Chunk.Text;
613 // Don't even add a space to the label.
614 break;
615 }
616 }
617 }
618}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000619
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000620class SignatureHelpCollector final : public CodeCompleteConsumer {
621
622public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000623 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000624 SignatureHelp &SigHelp)
625 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
626 SigHelp(SigHelp),
627 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
628 CCTUInfo(Allocator) {}
629
630 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
631 OverloadCandidate *Candidates,
632 unsigned NumCandidates) override {
633 SigHelp.signatures.reserve(NumCandidates);
634 // FIXME(rwols): How can we determine the "active overload candidate"?
635 // Right now the overloaded candidates seem to be provided in a "best fit"
636 // order, so I'm not too worried about this.
637 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000638 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000639 "too many arguments");
640 SigHelp.activeParameter = static_cast<int>(CurrentArg);
641 for (unsigned I = 0; I < NumCandidates; ++I) {
642 const auto &Candidate = Candidates[I];
643 const auto *CCS = Candidate.CreateSignatureString(
644 CurrentArg, S, *Allocator, CCTUInfo, true);
645 assert(CCS && "Expected the CodeCompletionString to be non-null");
646 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
647 }
648 }
649
650 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
651
652 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
653
654private:
655 SignatureInformation
656 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
657 const CodeCompletionString &CCS) const {
658 SignatureInformation Result;
659 const char *ReturnType = nullptr;
660
661 Result.documentation = getDocumentation(CCS);
662
663 for (const auto &Chunk : CCS) {
664 switch (Chunk.Kind) {
665 case CodeCompletionString::CK_ResultType:
666 // A piece of text that describes the type of an entity or,
667 // for functions and methods, the return type.
668 assert(!ReturnType && "Unexpected CK_ResultType");
669 ReturnType = Chunk.Text;
670 break;
671 case CodeCompletionString::CK_Placeholder:
672 // A string that acts as a placeholder for, e.g., a function call
673 // argument.
674 // Intentional fallthrough here.
675 case CodeCompletionString::CK_CurrentParameter: {
676 // A piece of text that describes the parameter that corresponds to
677 // the code-completion location within a function call, message send,
678 // macro invocation, etc.
679 Result.label += Chunk.Text;
680 ParameterInformation Info;
681 Info.label = Chunk.Text;
682 Result.parameters.push_back(std::move(Info));
683 break;
684 }
685 case CodeCompletionString::CK_Optional: {
686 // The rest of the parameters are defaulted/optional.
687 assert(Chunk.Optional &&
688 "Expected the optional code completion string to be non-null.");
689 Result.label +=
690 getOptionalParameters(*Chunk.Optional, Result.parameters);
691 break;
692 }
693 case CodeCompletionString::CK_VerticalSpace:
694 break;
695 default:
696 Result.label += Chunk.Text;
697 break;
698 }
699 }
700 if (ReturnType) {
701 Result.label += " -> ";
702 Result.label += ReturnType;
703 }
704 return Result;
705 }
706
707 SignatureHelp &SigHelp;
708 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
709 CodeCompletionTUInfo CCTUInfo;
710
711}; // SignatureHelpCollector
712
713bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000714 const clang::CodeCompleteOptions &Options,
715 PathRef FileName,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000716 const tooling::CompileCommand &Command,
717 PrecompiledPreamble const *Preamble, StringRef Contents,
718 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
719 std::shared_ptr<PCHContainerOperations> PCHs,
720 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000721 std::vector<const char *> ArgStrs;
722 for (const auto &S : Command.CommandLine)
723 ArgStrs.push_back(S.c_str());
724
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000725 VFS->setCurrentWorkingDirectory(Command.Directory);
726
Ilya Biryukov04db3682017-07-21 13:29:29 +0000727 std::unique_ptr<CompilerInvocation> CI;
728 EmptyDiagsConsumer DummyDiagsConsumer;
729 {
730 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
731 CompilerInstance::createDiagnostics(new DiagnosticOptions,
732 &DummyDiagsConsumer, false);
733 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
734 }
735 assert(CI && "Couldn't create CompilerInvocation");
736
737 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
738 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
739
740 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000741 if (Preamble) {
742 auto Bounds =
743 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000744 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
745 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000746 }
747
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000748 auto Clang = prepareCompilerInstance(
749 std::move(CI), Preamble, std::move(ContentsBuffer), std::move(PCHs),
750 std::move(VFS), DummyDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000751 auto &DiagOpts = Clang->getDiagnosticOpts();
752 DiagOpts.IgnoreWarnings = true;
753
754 auto &FrontendOpts = Clang->getFrontendOpts();
755 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000756 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000757 FrontendOpts.CodeCompletionAt.FileName = FileName;
758 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
759 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
760
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000761 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000762
Ilya Biryukov04db3682017-07-21 13:29:29 +0000763 SyntaxOnlyAction Action;
764 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000765 Logger.log("BeginSourceFile() failed when running codeComplete for " +
766 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000767 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000768 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000769 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000770 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000771 return false;
772 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000773
Ilya Biryukov04db3682017-07-21 13:29:29 +0000774 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000775
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000776 return true;
777}
778
779} // namespace
780
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000781clangd::CodeCompleteOptions::CodeCompleteOptions(
782 bool EnableSnippetsAndCodePatterns)
783 : CodeCompleteOptions() {
784 EnableSnippets = EnableSnippetsAndCodePatterns;
785 IncludeCodePatterns = EnableSnippetsAndCodePatterns;
786}
787
788clangd::CodeCompleteOptions::CodeCompleteOptions(bool EnableSnippets,
789 bool IncludeCodePatterns,
790 bool IncludeMacros,
791 bool IncludeGlobals,
792 bool IncludeBriefComments)
793 : EnableSnippets(EnableSnippets), IncludeCodePatterns(IncludeCodePatterns),
794 IncludeMacros(IncludeMacros), IncludeGlobals(IncludeGlobals),
795 IncludeBriefComments(IncludeBriefComments) {}
796
797clang::CodeCompleteOptions clangd::CodeCompleteOptions::getClangCompleteOpts() {
798 clang::CodeCompleteOptions Result;
799 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
800 Result.IncludeMacros = IncludeMacros;
801 Result.IncludeGlobals = IncludeGlobals;
802 Result.IncludeBriefComments = IncludeBriefComments;
803
804 return Result;
805}
806
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000807std::vector<CompletionItem>
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000808clangd::codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000809 PrecompiledPreamble const *Preamble, StringRef Contents,
810 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
811 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000812 clangd::CodeCompleteOptions Opts, clangd::Logger &Logger) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000813 std::vector<CompletionItem> Results;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000814 std::unique_ptr<CodeCompleteConsumer> Consumer;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000815 clang::CodeCompleteOptions ClangCompleteOpts = Opts.getClangCompleteOpts();
816 if (Opts.EnableSnippets) {
817 Consumer = llvm::make_unique<SnippetCompletionItemsCollector>(
818 ClangCompleteOpts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000819 } else {
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000820 Consumer = llvm::make_unique<PlainTextCompletionItemsCollector>(
821 ClangCompleteOpts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000822 }
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000823 invokeCodeComplete(std::move(Consumer), ClangCompleteOpts, FileName, Command,
824 Preamble, Contents, Pos, std::move(VFS), std::move(PCHs),
825 Logger);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000826 return Results;
827}
828
829SignatureHelp
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000830clangd::signatureHelp(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000831 PrecompiledPreamble const *Preamble, StringRef Contents,
832 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
833 std::shared_ptr<PCHContainerOperations> PCHs,
834 clangd::Logger &Logger) {
835 SignatureHelp Result;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000836 clang::CodeCompleteOptions Options;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000837 Options.IncludeGlobals = false;
838 Options.IncludeMacros = false;
839 Options.IncludeCodePatterns = false;
840 Options.IncludeBriefComments = true;
841 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
842 Options, FileName, Command, Preamble, Contents, Pos,
843 std::move(VFS), std::move(PCHs), Logger);
844 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000845}
846
Ilya Biryukov02d58702017-08-01 15:51:38 +0000847void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
848 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000849}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000850
Ilya Biryukov02d58702017-08-01 15:51:38 +0000851llvm::Optional<ParsedAST>
852ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
853 const PrecompiledPreamble *Preamble,
854 ArrayRef<serialization::DeclID> PreambleDeclIDs,
855 std::unique_ptr<llvm::MemoryBuffer> Buffer,
856 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000857 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
858 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000859
860 std::vector<DiagWithFixIts> ASTDiags;
861 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
862
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000863 auto Clang = prepareCompilerInstance(
864 std::move(CI), Preamble, std::move(Buffer), std::move(PCHs),
865 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000866
867 // Recover resources if we crash before exiting this method.
868 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
869 Clang.get());
870
871 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000872 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
873 if (!Action->BeginSourceFile(*Clang, MainInput)) {
874 Logger.log("BeginSourceFile() failed when building AST for " +
875 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000876 return llvm::None;
877 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000878 if (!Action->Execute())
879 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000880
881 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
882 // has a longer lifetime.
883 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
884
885 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
886 std::vector<serialization::DeclID> PendingDecls;
887 if (Preamble) {
888 PendingDecls.reserve(PreambleDeclIDs.size());
889 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
890 PreambleDeclIDs.end());
891 }
892
893 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
894 std::move(PendingDecls), std::move(ASTDiags));
895}
896
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000897namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000898
899SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
900 const FileEntry *FE,
901 unsigned Offset) {
902 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
903 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
904}
905
906SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
907 const FileEntry *FE, Position Pos) {
908 SourceLocation InputLoc =
909 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
910 return Mgr.getMacroArgExpandedLocation(InputLoc);
911}
912
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000913/// Finds declarations locations that a given source location refers to.
914class DeclarationLocationsFinder : public index::IndexDataConsumer {
915 std::vector<Location> DeclarationLocations;
916 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000917 const ASTContext &AST;
918 Preprocessor &PP;
919
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000920public:
921 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000922 const SourceLocation &SearchedLocation,
923 ASTContext &AST, Preprocessor &PP)
924 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000925
926 std::vector<Location> takeLocations() {
927 // Don't keep the same location multiple times.
928 // This can happen when nodes in the AST are visited twice.
929 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000930 auto last =
931 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000932 DeclarationLocations.erase(last, DeclarationLocations.end());
933 return std::move(DeclarationLocations);
934 }
935
Ilya Biryukov02d58702017-08-01 15:51:38 +0000936 bool
937 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
938 ArrayRef<index::SymbolRelation> Relations, FileID FID,
939 unsigned Offset,
940 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000941 if (isSearchedLocation(FID, Offset)) {
942 addDeclarationLocation(D->getSourceRange());
943 }
944 return true;
945 }
946
947private:
948 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000949 const SourceManager &SourceMgr = AST.getSourceManager();
950 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
951 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000952 }
953
Ilya Biryukov04db3682017-07-21 13:29:29 +0000954 void addDeclarationLocation(const SourceRange &ValSourceRange) {
955 const SourceManager &SourceMgr = AST.getSourceManager();
956 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000957 SourceLocation LocStart = ValSourceRange.getBegin();
958 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000959 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000960 Position Begin;
961 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
962 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
963 Position End;
964 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
965 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
966 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000967 Location L;
Marc-Andre Laperleba070102017-11-07 16:16:45 +0000968 if (const FileEntry *F =
969 SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) {
970 StringRef FilePath = F->tryGetRealPathName();
971 if (FilePath.empty())
972 FilePath = F->getName();
973 L.uri = URI::fromFile(FilePath);
974 L.range = R;
975 DeclarationLocations.push_back(L);
976 }
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000977 }
978
Kirill Bobyrev46213872017-06-28 20:57:28 +0000979 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000980 // Also handle possible macro at the searched location.
981 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000982 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
983 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000984 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000985 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000986 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000987 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000988 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
989 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000990 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000991 // Get the definition just before the searched location so that a macro
992 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000993 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
994 AST.getSourceManager(),
995 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000996 DecLoc.second - 1);
997 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000998 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
999 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001000 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001001 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
1002 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001003 }
1004 }
1005 }
1006 }
1007};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001008
Ilya Biryukov02d58702017-08-01 15:51:38 +00001009SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
1010 const FileEntry *FE) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001011 // The language server protocol uses zero-based line and column numbers.
1012 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001013
Ilya Biryukov02d58702017-08-01 15:51:38 +00001014 const ASTContext &AST = Unit.getASTContext();
Ilya Biryukov04db3682017-07-21 13:29:29 +00001015 const SourceManager &SourceMgr = AST.getSourceManager();
1016
1017 SourceLocation InputLocation =
1018 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001019 if (Pos.character == 0) {
1020 return InputLocation;
1021 }
1022
1023 // This handle cases where the position is in the middle of a token or right
1024 // after the end of a token. In theory we could just use GetBeginningOfToken
1025 // to find the start of the token at the input position, but this doesn't
1026 // work when right after the end, i.e. foo|.
1027 // So try to go back by one and see if we're still inside the an identifier
1028 // token. If so, Take the beginning of this token.
1029 // (It should be the same identifier because you can't have two adjacent
1030 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001031 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
1032 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001033 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +00001034 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +00001035 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +00001036 // getRawToken failed, just use InputLocation.
1037 return InputLocation;
1038 }
1039
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001040 if (Result.is(tok::raw_identifier)) {
1041 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001042 AST.getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001043 }
1044
1045 return InputLocation;
1046}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001047} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001048
Ilya Biryukove5128f72017-09-20 07:24:15 +00001049std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1050 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001051 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1052 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1053 if (!FE)
1054 return {};
1055
1056 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1057
1058 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1059 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1060 AST.getPreprocessor());
1061 index::IndexingOptions IndexOpts;
1062 IndexOpts.SystemSymbolFilter =
1063 index::IndexingOptions::SystemSymbolFilterKind::All;
1064 IndexOpts.IndexFunctionLocals = true;
1065
1066 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1067 DeclLocationsFinder, IndexOpts);
1068
1069 return DeclLocationsFinder->takeLocations();
1070}
1071
1072void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001073 if (PendingTopLevelDecls.empty())
1074 return;
1075
1076 std::vector<const Decl *> Resolved;
1077 Resolved.reserve(PendingTopLevelDecls.size());
1078
1079 ExternalASTSource &Source = *getASTContext().getExternalSource();
1080 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
1081 // Resolve the declaration ID to an actual declaration, possibly
1082 // deserializing the declaration in the process.
1083 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1084 Resolved.push_back(D);
1085 }
1086
1087 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
1088 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1089
1090 PendingTopLevelDecls.clear();
1091}
1092
Ilya Biryukov02d58702017-08-01 15:51:38 +00001093ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001094
Ilya Biryukov02d58702017-08-01 15:51:38 +00001095ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001096
Ilya Biryukov02d58702017-08-01 15:51:38 +00001097ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001098 if (Action) {
1099 Action->EndSourceFile();
1100 }
1101}
1102
Ilya Biryukov02d58702017-08-01 15:51:38 +00001103ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1104
1105const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001106 return Clang->getASTContext();
1107}
1108
Ilya Biryukov02d58702017-08-01 15:51:38 +00001109Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001110
Ilya Biryukov02d58702017-08-01 15:51:38 +00001111const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001112 return Clang->getPreprocessor();
1113}
1114
Ilya Biryukov02d58702017-08-01 15:51:38 +00001115ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001116 ensurePreambleDeclsDeserialized();
1117 return TopLevelDecls;
1118}
1119
Ilya Biryukov02d58702017-08-01 15:51:38 +00001120const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001121 return Diags;
1122}
1123
Ilya Biryukov02d58702017-08-01 15:51:38 +00001124ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
1125 std::unique_ptr<FrontendAction> Action,
1126 std::vector<const Decl *> TopLevelDecls,
1127 std::vector<serialization::DeclID> PendingTopLevelDecls,
1128 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001129 : Clang(std::move(Clang)), Action(std::move(Action)),
1130 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
1131 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
1132 assert(this->Clang);
1133 assert(this->Action);
1134}
1135
Ilya Biryukov02d58702017-08-01 15:51:38 +00001136ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1137 : AST(std::move(Wrapper.AST)) {}
1138
1139ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1140 : AST(std::move(AST)) {}
1141
1142PreambleData::PreambleData(PrecompiledPreamble Preamble,
1143 std::vector<serialization::DeclID> TopLevelDeclIDs,
1144 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001145 : Preamble(std::move(Preamble)),
1146 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001147
1148std::shared_ptr<CppFile>
1149CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001150 std::shared_ptr<PCHContainerOperations> PCHs,
1151 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001152 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +00001153 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001154}
1155
1156CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001157 std::shared_ptr<PCHContainerOperations> PCHs,
1158 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +00001159 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001160 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001161
1162 std::lock_guard<std::mutex> Lock(Mutex);
1163 LatestAvailablePreamble = nullptr;
1164 PreamblePromise.set_value(nullptr);
1165 PreambleFuture = PreamblePromise.get_future();
1166
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001167 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001168 ASTFuture = ASTPromise.get_future();
1169}
1170
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001171void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001172
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001173UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001174 std::unique_lock<std::mutex> Lock(Mutex);
1175 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001176 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001177 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1178 // We want to keep this invariant.
1179 if (futureIsReady(PreambleFuture)) {
1180 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1181 PreambleFuture = PreamblePromise.get_future();
1182 }
1183 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001184 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001185 ASTFuture = ASTPromise.get_future();
1186 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001187
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001188 Lock.unlock();
1189 // Notify about changes to RebuildCounter.
1190 RebuildCond.notify_all();
1191
1192 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001193 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001194 std::unique_lock<std::mutex> Lock(That->Mutex);
1195 CppFile *This = &*That;
1196 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1197 return !This->RebuildInProgress ||
1198 This->RebuildCounter != RequestRebuildCounter;
1199 });
1200
1201 // This computation got cancelled itself, do nothing.
1202 if (This->RebuildCounter != RequestRebuildCounter)
1203 return;
1204
1205 // Set empty results for Promises.
1206 That->PreamblePromise.set_value(nullptr);
1207 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001208 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001209}
1210
1211llvm::Optional<std::vector<DiagWithFixIts>>
1212CppFile::rebuild(StringRef NewContents,
1213 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001214 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001215}
1216
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001217UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001218CppFile::deferRebuild(StringRef NewContents,
1219 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1220 std::shared_ptr<const PreambleData> OldPreamble;
1221 std::shared_ptr<PCHContainerOperations> PCHs;
1222 unsigned RequestRebuildCounter;
1223 {
1224 std::unique_lock<std::mutex> Lock(Mutex);
1225 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1226 // They will try to exit as early as possible and won't call set_value on
1227 // our promises.
1228 RequestRebuildCounter = ++this->RebuildCounter;
1229 PCHs = this->PCHs;
1230
1231 // Remember the preamble to be used during rebuild.
1232 OldPreamble = this->LatestAvailablePreamble;
1233 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1234 // futures will wait until the rebuild process is finished.
1235 if (futureIsReady(this->PreambleFuture)) {
1236 this->PreamblePromise =
1237 std::promise<std::shared_ptr<const PreambleData>>();
1238 this->PreambleFuture = this->PreamblePromise.get_future();
1239 }
1240 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001241 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001242 this->ASTFuture = this->ASTPromise.get_future();
1243 }
1244 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001245 // Notify about changes to RebuildCounter.
1246 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001247
1248 // A helper to function to finish the rebuild. May be run on a different
1249 // thread.
1250
1251 // Don't let this CppFile die before rebuild is finished.
1252 std::shared_ptr<CppFile> That = shared_from_this();
1253 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1254 That](std::string NewContents)
1255 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1256 // Only one execution of this method is possible at a time.
1257 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1258 // into a state for doing a rebuild.
1259 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1260 if (Rebuild.wasCancelledBeforeConstruction())
1261 return llvm::None;
1262
1263 std::vector<const char *> ArgStrs;
1264 for (const auto &S : That->Command.CommandLine)
1265 ArgStrs.push_back(S.c_str());
1266
1267 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1268
1269 std::unique_ptr<CompilerInvocation> CI;
1270 {
1271 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1272 // reporting them.
1273 EmptyDiagsConsumer CommandLineDiagsConsumer;
1274 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1275 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1276 &CommandLineDiagsConsumer, false);
1277 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1278 }
1279 assert(CI && "Couldn't create CompilerInvocation");
1280
1281 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1282 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1283
1284 // A helper function to rebuild the preamble or reuse the existing one. Does
1285 // not mutate any fields, only does the actual computation.
1286 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1287 auto Bounds =
1288 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1289 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1290 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1291 return OldPreamble;
1292 }
1293
Sam McCall8567cb32017-11-02 09:21:51 +00001294 trace::Span Tracer(llvm::Twine("Preamble: ") + That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001295 std::vector<DiagWithFixIts> PreambleDiags;
1296 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1297 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1298 CompilerInstance::createDiagnostics(
1299 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1300 CppFilePreambleCallbacks SerializedDeclsCollector;
1301 auto BuiltPreamble = PrecompiledPreamble::Build(
1302 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
1303 SerializedDeclsCollector);
1304
1305 if (BuiltPreamble) {
1306 return std::make_shared<PreambleData>(
1307 std::move(*BuiltPreamble),
1308 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1309 std::move(PreambleDiags));
1310 } else {
1311 return nullptr;
1312 }
1313 };
1314
1315 // Compute updated Preamble.
1316 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1317 // Publish the new Preamble.
1318 {
1319 std::lock_guard<std::mutex> Lock(That->Mutex);
1320 // We always set LatestAvailablePreamble to the new value, hoping that it
1321 // will still be usable in the further requests.
1322 That->LatestAvailablePreamble = NewPreamble;
1323 if (RequestRebuildCounter != That->RebuildCounter)
1324 return llvm::None; // Our rebuild request was cancelled, do nothing.
1325 That->PreamblePromise.set_value(NewPreamble);
1326 } // unlock Mutex
1327
1328 // Prepare the Preamble and supplementary data for rebuilding AST.
1329 const PrecompiledPreamble *PreambleForAST = nullptr;
1330 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1331 std::vector<DiagWithFixIts> Diagnostics;
1332 if (NewPreamble) {
1333 PreambleForAST = &NewPreamble->Preamble;
1334 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1335 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1336 NewPreamble->Diags.end());
1337 }
1338
1339 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +00001340 llvm::Optional<ParsedAST> NewAST;
1341 {
1342 trace::Span Tracer(llvm::Twine("Build: ") + That->FileName);
1343 NewAST = ParsedAST::Build(
1344 std::move(CI), PreambleForAST, SerializedPreambleDecls,
1345 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
1346 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001347
1348 if (NewAST) {
1349 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1350 NewAST->getDiagnostics().end());
1351 } else {
1352 // Don't report even Preamble diagnostics if we coulnd't build AST.
1353 Diagnostics.clear();
1354 }
1355
1356 // Publish the new AST.
1357 {
1358 std::lock_guard<std::mutex> Lock(That->Mutex);
1359 if (RequestRebuildCounter != That->RebuildCounter)
1360 return Diagnostics; // Our rebuild request was cancelled, don't set
1361 // ASTPromise.
1362
Ilya Biryukov574b7532017-08-02 09:08:39 +00001363 That->ASTPromise.set_value(
1364 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001365 } // unlock Mutex
1366
1367 return Diagnostics;
1368 };
1369
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001370 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001371}
1372
1373std::shared_future<std::shared_ptr<const PreambleData>>
1374CppFile::getPreamble() const {
1375 std::lock_guard<std::mutex> Lock(Mutex);
1376 return PreambleFuture;
1377}
1378
1379std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1380 std::lock_guard<std::mutex> Lock(Mutex);
1381 return LatestAvailablePreamble;
1382}
1383
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001384std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001385 std::lock_guard<std::mutex> Lock(Mutex);
1386 return ASTFuture;
1387}
1388
1389tooling::CompileCommand const &CppFile::getCompileCommand() const {
1390 return Command;
1391}
1392
1393CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1394 unsigned RequestRebuildCounter)
1395 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1396 std::unique_lock<std::mutex> Lock(File.Mutex);
1397 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1398 if (WasCancelledBeforeConstruction)
1399 return;
1400
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001401 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1402 return !File.RebuildInProgress ||
1403 File.RebuildCounter != RequestRebuildCounter;
1404 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001405
1406 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1407 if (WasCancelledBeforeConstruction)
1408 return;
1409
1410 File.RebuildInProgress = true;
1411}
1412
1413bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1414 return WasCancelledBeforeConstruction;
1415}
1416
1417CppFile::RebuildGuard::~RebuildGuard() {
1418 if (WasCancelledBeforeConstruction)
1419 return;
1420
1421 std::unique_lock<std::mutex> Lock(File.Mutex);
1422 assert(File.RebuildInProgress);
1423 File.RebuildInProgress = false;
1424
1425 if (File.RebuildCounter == RequestRebuildCounter) {
1426 // Our rebuild request was successful.
1427 assert(futureIsReady(File.ASTFuture));
1428 assert(futureIsReady(File.PreambleFuture));
1429 } else {
1430 // Our rebuild request was cancelled, because further reparse was requested.
1431 assert(!futureIsReady(File.ASTFuture));
1432 assert(!futureIsReady(File.PreambleFuture));
1433 }
1434
1435 Lock.unlock();
1436 File.RebuildCond.notify_all();
1437}