blob: c5f6880733932c22530c17889c2f7d3b40032df4 [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) {
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000238 Preamble->AddImplicitPreamble(*CI, VFS, Buffer.get());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000239 } 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
Sam McCalla40371b2017-11-15 09:16:29 +0000371/// A scored code completion result.
372/// It may be promoted to a CompletionItem if it's among the top-ranked results.
373struct CompletionCandidate {
374 CompletionCandidate(CodeCompletionResult &Result)
375 : Result(&Result), Score(score(Result)) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000376
Sam McCalla40371b2017-11-15 09:16:29 +0000377 CodeCompletionResult *Result;
Sam McCallb8d548a2017-11-23 17:09:04 +0000378 float Score; // 0 to 1, higher is better.
Sam McCalla40371b2017-11-15 09:16:29 +0000379
380 // Comparison reflects rank: better candidates are smaller.
381 bool operator<(const CompletionCandidate &C) const {
382 if (Score != C.Score)
Sam McCallb8d548a2017-11-23 17:09:04 +0000383 return Score > C.Score;
Sam McCalla40371b2017-11-15 09:16:29 +0000384 return *Result < *C.Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000385 }
386
Sam McCallb8d548a2017-11-23 17:09:04 +0000387 // Returns a string that sorts in the same order as operator<, for LSP.
388 // Conceptually, this is [-Score, Name]. We convert -Score to an integer, and
389 // hex-encode it for readability. Example: [0.5, "foo"] -> "41000000foo"
Sam McCalla40371b2017-11-15 09:16:29 +0000390 std::string sortText() const {
Sam McCalla40371b2017-11-15 09:16:29 +0000391 std::string S, NameStorage;
Sam McCallb8d548a2017-11-23 17:09:04 +0000392 llvm::raw_string_ostream OS(S);
393 write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
394 /*Width=*/2 * sizeof(Score));
395 OS << Result->getOrderedName(NameStorage);
396 return OS.str();
Sam McCalla40371b2017-11-15 09:16:29 +0000397 }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000398
399private:
Sam McCallb8d548a2017-11-23 17:09:04 +0000400 static float score(const CodeCompletionResult &Result) {
401 // Priority 80 is a really bad score.
402 float Score = 1 - std::min<float>(80, Result.Priority) / 80;
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000403
Sam McCalla40371b2017-11-15 09:16:29 +0000404 switch (static_cast<CXAvailabilityKind>(Result.Availability)) {
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000405 case CXAvailability_Available:
406 // No penalty.
407 break;
408 case CXAvailability_Deprecated:
Sam McCallb8d548a2017-11-23 17:09:04 +0000409 Score *= 0.1;
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000410 break;
411 case CXAvailability_NotAccessible:
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000412 case CXAvailability_NotAvailable:
Sam McCallb8d548a2017-11-23 17:09:04 +0000413 Score = 0;
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000414 break;
415 }
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000416 return Score;
417 }
Sam McCallb8d548a2017-11-23 17:09:04 +0000418
419 // Produces an integer that sorts in the same order as F.
420 // That is: a < b <==> encodeFloat(a) < encodeFloat(b).
421 static uint32_t encodeFloat(float F) {
422 static_assert(std::numeric_limits<float>::is_iec559, "");
423 static_assert(sizeof(float) == sizeof(uint32_t), "");
424 constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
425
426 // Get the bits of the float. Endianness is the same as for integers.
427 uint32_t U;
428 memcpy(&U, &F, sizeof(float));
429 // IEEE 754 floats compare like sign-magnitude integers.
430 if (U & TopBit) // Negative float.
431 return 0 - U; // Map onto the low half of integers, order reversed.
432 return U + TopBit; // Positive floats map onto the high half of integers.
433 }
Sam McCalla40371b2017-11-15 09:16:29 +0000434};
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000435
Sam McCalla40371b2017-11-15 09:16:29 +0000436class CompletionItemsCollector : public CodeCompleteConsumer {
437public:
438 CompletionItemsCollector(const clangd::CodeCompleteOptions &CodeCompleteOpts,
439 CompletionList &Items)
440 : CodeCompleteConsumer(CodeCompleteOpts.getClangCompleteOpts(),
441 /*OutputIsBinary=*/false),
442 ClangdOpts(CodeCompleteOpts), Items(Items),
443 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
444 CCTUInfo(Allocator) {}
445
446 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
447 CodeCompletionResult *Results,
448 unsigned NumResults) override final {
449 std::priority_queue<CompletionCandidate> Candidates;
450 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCalladccab62017-11-23 16:58:22 +0000451 auto &Result = Results[I];
452 if (!ClangdOpts.IncludeIneligibleResults &&
453 (Result.Availability == CXAvailability_NotAvailable ||
454 Result.Availability == CXAvailability_NotAccessible))
455 continue;
456 Candidates.emplace(Result);
Sam McCalla40371b2017-11-15 09:16:29 +0000457 if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
458 Candidates.pop();
459 Items.isIncomplete = true;
460 }
461 }
462 while (!Candidates.empty()) {
463 auto &Candidate = Candidates.top();
464 const auto *CCS = Candidate.Result->CreateCodeCompletionString(
465 S, Context, *Allocator, CCTUInfo,
466 CodeCompleteOpts.IncludeBriefComments);
467 assert(CCS && "Expected the CodeCompletionString to be non-null");
468 Items.items.push_back(ProcessCodeCompleteResult(Candidate, *CCS));
469 Candidates.pop();
470 }
471 std::reverse(Items.items.begin(), Items.items.end());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000472 }
473
Sam McCalla40371b2017-11-15 09:16:29 +0000474 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
475
476 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
477
478private:
479 CompletionItem
480 ProcessCodeCompleteResult(const CompletionCandidate &Candidate,
481 const CodeCompletionString &CCS) const {
482
483 // Adjust this to InsertTextFormat::Snippet iff we encounter a
484 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
485 CompletionItem Item;
486 Item.insertTextFormat = InsertTextFormat::PlainText;
487
488 Item.documentation = getDocumentation(CCS);
489 Item.sortText = Candidate.sortText();
490
491 // Fill in the label, detail, insertText and filterText fields of the
492 // CompletionItem.
493 ProcessChunks(CCS, Item);
494
495 // Fill in the kind field of the CompletionItem.
496 Item.kind = getKind(Candidate.Result->Kind, Candidate.Result->CursorKind);
497
498 return Item;
499 }
500
501 virtual void ProcessChunks(const CodeCompletionString &CCS,
502 CompletionItem &Item) const = 0;
503
504 clangd::CodeCompleteOptions ClangdOpts;
505 CompletionList &Items;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000506 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
507 CodeCompletionTUInfo CCTUInfo;
508
509}; // CompletionItemsCollector
510
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000511bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
512 return Chunk.Kind == CodeCompletionString::CK_Informative &&
513 StringRef(Chunk.Text).endswith("::");
514}
515
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000516class PlainTextCompletionItemsCollector final
517 : public CompletionItemsCollector {
518
519public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000520 PlainTextCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000521 const clangd::CodeCompleteOptions &CodeCompleteOpts,
522 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000523 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
524
525private:
526 void ProcessChunks(const CodeCompletionString &CCS,
527 CompletionItem &Item) const override {
528 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000529 // Informative qualifier chunks only clutter completion results, skip
530 // them.
531 if (isInformativeQualifierChunk(Chunk))
532 continue;
533
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000534 switch (Chunk.Kind) {
535 case CodeCompletionString::CK_TypedText:
536 // There's always exactly one CK_TypedText chunk.
537 Item.insertText = Item.filterText = Chunk.Text;
538 Item.label += Chunk.Text;
539 break;
540 case CodeCompletionString::CK_ResultType:
541 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
542 Item.detail = Chunk.Text;
543 break;
544 case CodeCompletionString::CK_Optional:
545 break;
546 default:
547 Item.label += Chunk.Text;
548 break;
549 }
550 }
551 }
552}; // PlainTextCompletionItemsCollector
553
554class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
555
556public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000557 SnippetCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000558 const clangd::CodeCompleteOptions &CodeCompleteOpts,
559 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000560 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
561
562private:
563 void ProcessChunks(const CodeCompletionString &CCS,
564 CompletionItem &Item) const override {
565 unsigned ArgCount = 0;
566 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000567 // Informative qualifier chunks only clutter completion results, skip
568 // them.
569 if (isInformativeQualifierChunk(Chunk))
570 continue;
571
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000572 switch (Chunk.Kind) {
573 case CodeCompletionString::CK_TypedText:
574 // The piece of text that the user is expected to type to match
575 // the code-completion string, typically a keyword or the name of
576 // a declarator or macro.
577 Item.filterText = Chunk.Text;
Simon Pilgrim948c0bc2017-11-01 09:22:03 +0000578 LLVM_FALLTHROUGH;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000579 case CodeCompletionString::CK_Text:
580 // A piece of text that should be placed in the buffer,
581 // e.g., parentheses or a comma in a function call.
582 Item.label += Chunk.Text;
583 Item.insertText += Chunk.Text;
584 break;
585 case CodeCompletionString::CK_Optional:
586 // A code completion string that is entirely optional.
587 // For example, an optional code completion string that
588 // describes the default arguments in a function call.
589
590 // FIXME: Maybe add an option to allow presenting the optional chunks?
591 break;
592 case CodeCompletionString::CK_Placeholder:
593 // A string that acts as a placeholder for, e.g., a function call
594 // argument.
595 ++ArgCount;
596 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
597 escapeSnippet(Chunk.Text) + '}';
598 Item.label += Chunk.Text;
599 Item.insertTextFormat = InsertTextFormat::Snippet;
600 break;
601 case CodeCompletionString::CK_Informative:
602 // A piece of text that describes something about the result
603 // but should not be inserted into the buffer.
604 // For example, the word "const" for a const method, or the name of
605 // the base class for methods that are part of the base class.
606 Item.label += Chunk.Text;
607 // Don't put the informative chunks in the insertText.
608 break;
609 case CodeCompletionString::CK_ResultType:
610 // A piece of text that describes the type of an entity or,
611 // for functions and methods, the return type.
612 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
613 Item.detail = Chunk.Text;
614 break;
615 case CodeCompletionString::CK_CurrentParameter:
616 // A piece of text that describes the parameter that corresponds to
617 // the code-completion location within a function call, message send,
618 // macro invocation, etc.
619 //
620 // This should never be present while collecting completion items,
621 // only while collecting overload candidates.
622 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
623 "CompletionItems");
624 break;
625 case CodeCompletionString::CK_LeftParen:
626 // A left parenthesis ('(').
627 case CodeCompletionString::CK_RightParen:
628 // A right parenthesis (')').
629 case CodeCompletionString::CK_LeftBracket:
630 // A left bracket ('[').
631 case CodeCompletionString::CK_RightBracket:
632 // A right bracket (']').
633 case CodeCompletionString::CK_LeftBrace:
634 // A left brace ('{').
635 case CodeCompletionString::CK_RightBrace:
636 // A right brace ('}').
637 case CodeCompletionString::CK_LeftAngle:
638 // A left angle bracket ('<').
639 case CodeCompletionString::CK_RightAngle:
640 // A right angle bracket ('>').
641 case CodeCompletionString::CK_Comma:
642 // A comma separator (',').
643 case CodeCompletionString::CK_Colon:
644 // A colon (':').
645 case CodeCompletionString::CK_SemiColon:
646 // A semicolon (';').
647 case CodeCompletionString::CK_Equal:
648 // An '=' sign.
649 case CodeCompletionString::CK_HorizontalSpace:
650 // Horizontal whitespace (' ').
651 Item.insertText += Chunk.Text;
652 Item.label += Chunk.Text;
653 break;
654 case CodeCompletionString::CK_VerticalSpace:
655 // Vertical whitespace ('\n' or '\r\n', depending on the
656 // platform).
657 Item.insertText += Chunk.Text;
658 // Don't even add a space to the label.
659 break;
660 }
661 }
662 }
663}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000664
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000665class SignatureHelpCollector final : public CodeCompleteConsumer {
666
667public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000668 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000669 SignatureHelp &SigHelp)
670 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
671 SigHelp(SigHelp),
672 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
673 CCTUInfo(Allocator) {}
674
675 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
676 OverloadCandidate *Candidates,
677 unsigned NumCandidates) override {
678 SigHelp.signatures.reserve(NumCandidates);
679 // FIXME(rwols): How can we determine the "active overload candidate"?
680 // Right now the overloaded candidates seem to be provided in a "best fit"
681 // order, so I'm not too worried about this.
682 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000683 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000684 "too many arguments");
685 SigHelp.activeParameter = static_cast<int>(CurrentArg);
686 for (unsigned I = 0; I < NumCandidates; ++I) {
687 const auto &Candidate = Candidates[I];
688 const auto *CCS = Candidate.CreateSignatureString(
689 CurrentArg, S, *Allocator, CCTUInfo, true);
690 assert(CCS && "Expected the CodeCompletionString to be non-null");
691 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
692 }
693 }
694
695 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
696
697 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
698
699private:
700 SignatureInformation
701 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
702 const CodeCompletionString &CCS) const {
703 SignatureInformation Result;
704 const char *ReturnType = nullptr;
705
706 Result.documentation = getDocumentation(CCS);
707
708 for (const auto &Chunk : CCS) {
709 switch (Chunk.Kind) {
710 case CodeCompletionString::CK_ResultType:
711 // A piece of text that describes the type of an entity or,
712 // for functions and methods, the return type.
713 assert(!ReturnType && "Unexpected CK_ResultType");
714 ReturnType = Chunk.Text;
715 break;
716 case CodeCompletionString::CK_Placeholder:
717 // A string that acts as a placeholder for, e.g., a function call
718 // argument.
719 // Intentional fallthrough here.
720 case CodeCompletionString::CK_CurrentParameter: {
721 // A piece of text that describes the parameter that corresponds to
722 // the code-completion location within a function call, message send,
723 // macro invocation, etc.
724 Result.label += Chunk.Text;
725 ParameterInformation Info;
726 Info.label = Chunk.Text;
727 Result.parameters.push_back(std::move(Info));
728 break;
729 }
730 case CodeCompletionString::CK_Optional: {
731 // The rest of the parameters are defaulted/optional.
732 assert(Chunk.Optional &&
733 "Expected the optional code completion string to be non-null.");
734 Result.label +=
735 getOptionalParameters(*Chunk.Optional, Result.parameters);
736 break;
737 }
738 case CodeCompletionString::CK_VerticalSpace:
739 break;
740 default:
741 Result.label += Chunk.Text;
742 break;
743 }
744 }
745 if (ReturnType) {
746 Result.label += " -> ";
747 Result.label += ReturnType;
748 }
749 return Result;
750 }
751
752 SignatureHelp &SigHelp;
753 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
754 CodeCompletionTUInfo CCTUInfo;
755
756}; // SignatureHelpCollector
757
758bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000759 const clang::CodeCompleteOptions &Options,
760 PathRef FileName,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000761 const tooling::CompileCommand &Command,
762 PrecompiledPreamble const *Preamble, StringRef Contents,
763 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
764 std::shared_ptr<PCHContainerOperations> PCHs,
765 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000766 std::vector<const char *> ArgStrs;
767 for (const auto &S : Command.CommandLine)
768 ArgStrs.push_back(S.c_str());
769
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000770 VFS->setCurrentWorkingDirectory(Command.Directory);
771
Ilya Biryukov04db3682017-07-21 13:29:29 +0000772 std::unique_ptr<CompilerInvocation> CI;
773 EmptyDiagsConsumer DummyDiagsConsumer;
774 {
775 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
776 CompilerInstance::createDiagnostics(new DiagnosticOptions,
777 &DummyDiagsConsumer, false);
778 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
779 }
780 assert(CI && "Couldn't create CompilerInvocation");
781
782 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
783 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
784
785 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000786 if (Preamble) {
787 auto Bounds =
788 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000789 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
790 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000791 }
792
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000793 auto Clang = prepareCompilerInstance(
794 std::move(CI), Preamble, std::move(ContentsBuffer), std::move(PCHs),
795 std::move(VFS), DummyDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000796 auto &DiagOpts = Clang->getDiagnosticOpts();
797 DiagOpts.IgnoreWarnings = true;
798
799 auto &FrontendOpts = Clang->getFrontendOpts();
800 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000801 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000802 FrontendOpts.CodeCompletionAt.FileName = FileName;
803 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
804 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
805
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000806 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000807
Ilya Biryukov04db3682017-07-21 13:29:29 +0000808 SyntaxOnlyAction Action;
809 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000810 Logger.log("BeginSourceFile() failed when running codeComplete for " +
811 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000812 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000813 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000814 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000815 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000816 return false;
817 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000818
Ilya Biryukov04db3682017-07-21 13:29:29 +0000819 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000820
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000821 return true;
822}
823
824} // namespace
825
Sam McCalla40371b2017-11-15 09:16:29 +0000826clang::CodeCompleteOptions
827clangd::CodeCompleteOptions::getClangCompleteOpts() const {
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000828 clang::CodeCompleteOptions Result;
829 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
830 Result.IncludeMacros = IncludeMacros;
831 Result.IncludeGlobals = IncludeGlobals;
832 Result.IncludeBriefComments = IncludeBriefComments;
833
834 return Result;
835}
836
Sam McCalla40371b2017-11-15 09:16:29 +0000837CompletionList
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000838clangd::codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000839 PrecompiledPreamble const *Preamble, StringRef Contents,
840 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
841 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000842 clangd::CodeCompleteOptions Opts, clangd::Logger &Logger) {
Sam McCalla40371b2017-11-15 09:16:29 +0000843 CompletionList Results;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000844 std::unique_ptr<CodeCompleteConsumer> Consumer;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000845 if (Opts.EnableSnippets) {
Sam McCalla40371b2017-11-15 09:16:29 +0000846 Consumer =
847 llvm::make_unique<SnippetCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000848 } else {
Sam McCalla40371b2017-11-15 09:16:29 +0000849 Consumer =
850 llvm::make_unique<PlainTextCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000851 }
Sam McCalla40371b2017-11-15 09:16:29 +0000852 invokeCodeComplete(std::move(Consumer), Opts.getClangCompleteOpts(), FileName,
853 Command, Preamble, Contents, Pos, std::move(VFS),
854 std::move(PCHs), Logger);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000855 return Results;
856}
857
858SignatureHelp
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000859clangd::signatureHelp(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000860 PrecompiledPreamble const *Preamble, StringRef Contents,
861 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
862 std::shared_ptr<PCHContainerOperations> PCHs,
863 clangd::Logger &Logger) {
864 SignatureHelp Result;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000865 clang::CodeCompleteOptions Options;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000866 Options.IncludeGlobals = false;
867 Options.IncludeMacros = false;
868 Options.IncludeCodePatterns = false;
869 Options.IncludeBriefComments = true;
870 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
871 Options, FileName, Command, Preamble, Contents, Pos,
872 std::move(VFS), std::move(PCHs), Logger);
873 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000874}
875
Ilya Biryukov02d58702017-08-01 15:51:38 +0000876void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
877 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000878}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000879
Ilya Biryukov02d58702017-08-01 15:51:38 +0000880llvm::Optional<ParsedAST>
881ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000882 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000883 std::unique_ptr<llvm::MemoryBuffer> Buffer,
884 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000885 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
886 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000887
888 std::vector<DiagWithFixIts> ASTDiags;
889 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
890
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000891 const PrecompiledPreamble *PreamblePCH =
892 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000893 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000894 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000895 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000896
897 // Recover resources if we crash before exiting this method.
898 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
899 Clang.get());
900
901 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000902 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
903 if (!Action->BeginSourceFile(*Clang, MainInput)) {
904 Logger.log("BeginSourceFile() failed when building AST for " +
905 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000906 return llvm::None;
907 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000908 if (!Action->Execute())
909 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000910
911 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
912 // has a longer lifetime.
913 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
914
915 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000916 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
917 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000918}
919
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000920namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000921
922SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
923 const FileEntry *FE,
924 unsigned Offset) {
925 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
926 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
927}
928
929SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
930 const FileEntry *FE, Position Pos) {
931 SourceLocation InputLoc =
932 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
933 return Mgr.getMacroArgExpandedLocation(InputLoc);
934}
935
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000936/// Finds declarations locations that a given source location refers to.
937class DeclarationLocationsFinder : public index::IndexDataConsumer {
938 std::vector<Location> DeclarationLocations;
939 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000940 const ASTContext &AST;
941 Preprocessor &PP;
942
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000943public:
944 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000945 const SourceLocation &SearchedLocation,
946 ASTContext &AST, Preprocessor &PP)
947 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000948
949 std::vector<Location> takeLocations() {
950 // Don't keep the same location multiple times.
951 // This can happen when nodes in the AST are visited twice.
952 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000953 auto last =
954 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000955 DeclarationLocations.erase(last, DeclarationLocations.end());
956 return std::move(DeclarationLocations);
957 }
958
Ilya Biryukov02d58702017-08-01 15:51:38 +0000959 bool
960 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
961 ArrayRef<index::SymbolRelation> Relations, FileID FID,
962 unsigned Offset,
963 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000964 if (isSearchedLocation(FID, Offset)) {
965 addDeclarationLocation(D->getSourceRange());
966 }
967 return true;
968 }
969
970private:
971 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000972 const SourceManager &SourceMgr = AST.getSourceManager();
973 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
974 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000975 }
976
Ilya Biryukov04db3682017-07-21 13:29:29 +0000977 void addDeclarationLocation(const SourceRange &ValSourceRange) {
978 const SourceManager &SourceMgr = AST.getSourceManager();
979 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000980 SourceLocation LocStart = ValSourceRange.getBegin();
981 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000982 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000983 Position Begin;
984 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
985 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
986 Position End;
987 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
988 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
989 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000990 Location L;
Marc-Andre Laperleba070102017-11-07 16:16:45 +0000991 if (const FileEntry *F =
992 SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) {
993 StringRef FilePath = F->tryGetRealPathName();
994 if (FilePath.empty())
995 FilePath = F->getName();
996 L.uri = URI::fromFile(FilePath);
997 L.range = R;
998 DeclarationLocations.push_back(L);
999 }
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001000 }
1001
Kirill Bobyrev46213872017-06-28 20:57:28 +00001002 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001003 // Also handle possible macro at the searched location.
1004 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001005 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
1006 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001007 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001008 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001009 }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001010 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001011 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
1012 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001013 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001014 // Get the definition just before the searched location so that a macro
1015 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +00001016 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
1017 AST.getSourceManager(),
1018 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001019 DecLoc.second - 1);
1020 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001021 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
1022 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001023 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001024 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
1025 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001026 }
1027 }
1028 }
1029 }
1030};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001031
Ilya Biryukov02d58702017-08-01 15:51:38 +00001032} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001033
Ilya Biryukove5128f72017-09-20 07:24:15 +00001034std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1035 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001036 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1037 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1038 if (!FE)
1039 return {};
1040
1041 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1042
1043 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1044 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1045 AST.getPreprocessor());
1046 index::IndexingOptions IndexOpts;
1047 IndexOpts.SystemSymbolFilter =
1048 index::IndexingOptions::SystemSymbolFilterKind::All;
1049 IndexOpts.IndexFunctionLocals = true;
1050
1051 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1052 DeclLocationsFinder, IndexOpts);
1053
1054 return DeclLocationsFinder->takeLocations();
1055}
1056
1057void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001058 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001059 return;
1060
1061 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001062 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +00001063
1064 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001065 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001066 // Resolve the declaration ID to an actual declaration, possibly
1067 // deserializing the declaration in the process.
1068 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1069 Resolved.push_back(D);
1070 }
1071
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001072 TopLevelDecls.reserve(TopLevelDecls.size() +
1073 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +00001074 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1075
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001076 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001077}
1078
Ilya Biryukov02d58702017-08-01 15:51:38 +00001079ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001080
Ilya Biryukov02d58702017-08-01 15:51:38 +00001081ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001082
Ilya Biryukov02d58702017-08-01 15:51:38 +00001083ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001084 if (Action) {
1085 Action->EndSourceFile();
1086 }
1087}
1088
Ilya Biryukov02d58702017-08-01 15:51:38 +00001089ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1090
1091const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001092 return Clang->getASTContext();
1093}
1094
Ilya Biryukov02d58702017-08-01 15:51:38 +00001095Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001096
Ilya Biryukov02d58702017-08-01 15:51:38 +00001097const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001098 return Clang->getPreprocessor();
1099}
1100
Ilya Biryukov02d58702017-08-01 15:51:38 +00001101ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001102 ensurePreambleDeclsDeserialized();
1103 return TopLevelDecls;
1104}
1105
Ilya Biryukov02d58702017-08-01 15:51:38 +00001106const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001107 return Diags;
1108}
1109
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001110PreambleData::PreambleData(PrecompiledPreamble Preamble,
1111 std::vector<serialization::DeclID> TopLevelDeclIDs,
1112 std::vector<DiagWithFixIts> Diags)
1113 : Preamble(std::move(Preamble)),
1114 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
1115
1116ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
1117 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001118 std::unique_ptr<FrontendAction> Action,
1119 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001120 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001121 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
1122 Action(std::move(Action)), Diags(std::move(Diags)),
1123 TopLevelDecls(std::move(TopLevelDecls)),
1124 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001125 assert(this->Clang);
1126 assert(this->Action);
1127}
1128
Ilya Biryukov02d58702017-08-01 15:51:38 +00001129ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1130 : AST(std::move(Wrapper.AST)) {}
1131
1132ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1133 : AST(std::move(AST)) {}
1134
Ilya Biryukov02d58702017-08-01 15:51:38 +00001135std::shared_ptr<CppFile>
1136CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001137 bool StorePreamblesInMemory,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001138 std::shared_ptr<PCHContainerOperations> PCHs,
1139 clangd::Logger &Logger) {
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001140 return std::shared_ptr<CppFile>(new CppFile(FileName, std::move(Command),
1141 StorePreamblesInMemory,
1142 std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001143}
1144
1145CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001146 bool StorePreamblesInMemory,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001147 std::shared_ptr<PCHContainerOperations> PCHs,
1148 clangd::Logger &Logger)
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001149 : FileName(FileName), Command(std::move(Command)),
1150 StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001151 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001152
1153 std::lock_guard<std::mutex> Lock(Mutex);
1154 LatestAvailablePreamble = nullptr;
1155 PreamblePromise.set_value(nullptr);
1156 PreambleFuture = PreamblePromise.get_future();
1157
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001158 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001159 ASTFuture = ASTPromise.get_future();
1160}
1161
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001162void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001163
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001164UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001165 std::unique_lock<std::mutex> Lock(Mutex);
1166 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001167 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001168 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1169 // We want to keep this invariant.
1170 if (futureIsReady(PreambleFuture)) {
1171 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1172 PreambleFuture = PreamblePromise.get_future();
1173 }
1174 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001175 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001176 ASTFuture = ASTPromise.get_future();
1177 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001178
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001179 Lock.unlock();
1180 // Notify about changes to RebuildCounter.
1181 RebuildCond.notify_all();
1182
1183 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001184 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001185 std::unique_lock<std::mutex> Lock(That->Mutex);
1186 CppFile *This = &*That;
1187 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1188 return !This->RebuildInProgress ||
1189 This->RebuildCounter != RequestRebuildCounter;
1190 });
1191
1192 // This computation got cancelled itself, do nothing.
1193 if (This->RebuildCounter != RequestRebuildCounter)
1194 return;
1195
1196 // Set empty results for Promises.
1197 That->PreamblePromise.set_value(nullptr);
1198 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001199 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001200}
1201
1202llvm::Optional<std::vector<DiagWithFixIts>>
1203CppFile::rebuild(StringRef NewContents,
1204 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001205 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001206}
1207
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001208UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001209CppFile::deferRebuild(StringRef NewContents,
1210 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1211 std::shared_ptr<const PreambleData> OldPreamble;
1212 std::shared_ptr<PCHContainerOperations> PCHs;
1213 unsigned RequestRebuildCounter;
1214 {
1215 std::unique_lock<std::mutex> Lock(Mutex);
1216 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1217 // They will try to exit as early as possible and won't call set_value on
1218 // our promises.
1219 RequestRebuildCounter = ++this->RebuildCounter;
1220 PCHs = this->PCHs;
1221
1222 // Remember the preamble to be used during rebuild.
1223 OldPreamble = this->LatestAvailablePreamble;
1224 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1225 // futures will wait until the rebuild process is finished.
1226 if (futureIsReady(this->PreambleFuture)) {
1227 this->PreamblePromise =
1228 std::promise<std::shared_ptr<const PreambleData>>();
1229 this->PreambleFuture = this->PreamblePromise.get_future();
1230 }
1231 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001232 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001233 this->ASTFuture = this->ASTPromise.get_future();
1234 }
1235 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001236 // Notify about changes to RebuildCounter.
1237 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001238
1239 // A helper to function to finish the rebuild. May be run on a different
1240 // thread.
1241
1242 // Don't let this CppFile die before rebuild is finished.
1243 std::shared_ptr<CppFile> That = shared_from_this();
1244 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
Ilya Biryukov11a02522017-11-17 19:05:56 +00001245 That](std::string NewContents) mutable // 'mutable' to
1246 // allow changing
1247 // OldPreamble.
Ilya Biryukov02d58702017-08-01 15:51:38 +00001248 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1249 // Only one execution of this method is possible at a time.
1250 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1251 // into a state for doing a rebuild.
1252 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1253 if (Rebuild.wasCancelledBeforeConstruction())
1254 return llvm::None;
1255
1256 std::vector<const char *> ArgStrs;
1257 for (const auto &S : That->Command.CommandLine)
1258 ArgStrs.push_back(S.c_str());
1259
1260 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1261
1262 std::unique_ptr<CompilerInvocation> CI;
1263 {
1264 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1265 // reporting them.
1266 EmptyDiagsConsumer CommandLineDiagsConsumer;
1267 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1268 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1269 &CommandLineDiagsConsumer, false);
1270 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1271 }
1272 assert(CI && "Couldn't create CompilerInvocation");
1273
1274 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1275 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1276
1277 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +00001278 // not mutate any fields of CppFile, only does the actual computation.
1279 // Lamdba is marked mutable to call reset() on OldPreamble.
1280 auto DoRebuildPreamble =
1281 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001282 auto Bounds =
1283 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1284 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1285 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1286 return OldPreamble;
1287 }
Ilya Biryukov11a02522017-11-17 19:05:56 +00001288 // We won't need the OldPreamble anymore, release it so it can be deleted
1289 // (if there are no other references to it).
1290 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001291
Sam McCall9cfd9c92017-11-23 17:12:04 +00001292 trace::Span Tracer("Preamble");
1293 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001294 std::vector<DiagWithFixIts> PreambleDiags;
1295 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1296 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1297 CompilerInstance::createDiagnostics(
1298 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1299 CppFilePreambleCallbacks SerializedDeclsCollector;
1300 auto BuiltPreamble = PrecompiledPreamble::Build(
1301 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001302 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001303 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.
Ilya Biryukov02d58702017-08-01 15:51:38 +00001329 std::vector<DiagWithFixIts> Diagnostics;
1330 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001331 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1332 NewPreamble->Diags.end());
1333 }
1334
1335 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +00001336 llvm::Optional<ParsedAST> NewAST;
1337 {
Sam McCall9cfd9c92017-11-23 17:12:04 +00001338 trace::Span Tracer("Build");
1339 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov2660cc92017-11-24 13:04:21 +00001340 NewAST =
1341 ParsedAST::Build(std::move(CI), std::move(NewPreamble),
1342 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Sam McCall8567cb32017-11-02 09:21:51 +00001343 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001344
1345 if (NewAST) {
1346 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1347 NewAST->getDiagnostics().end());
1348 } else {
1349 // Don't report even Preamble diagnostics if we coulnd't build AST.
1350 Diagnostics.clear();
1351 }
1352
1353 // Publish the new AST.
1354 {
1355 std::lock_guard<std::mutex> Lock(That->Mutex);
1356 if (RequestRebuildCounter != That->RebuildCounter)
1357 return Diagnostics; // Our rebuild request was cancelled, don't set
1358 // ASTPromise.
1359
Ilya Biryukov574b7532017-08-02 09:08:39 +00001360 That->ASTPromise.set_value(
1361 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001362 } // unlock Mutex
1363
1364 return Diagnostics;
1365 };
1366
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001367 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001368}
1369
1370std::shared_future<std::shared_ptr<const PreambleData>>
1371CppFile::getPreamble() const {
1372 std::lock_guard<std::mutex> Lock(Mutex);
1373 return PreambleFuture;
1374}
1375
1376std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1377 std::lock_guard<std::mutex> Lock(Mutex);
1378 return LatestAvailablePreamble;
1379}
1380
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001381std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001382 std::lock_guard<std::mutex> Lock(Mutex);
1383 return ASTFuture;
1384}
1385
1386tooling::CompileCommand const &CppFile::getCompileCommand() const {
1387 return Command;
1388}
1389
1390CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1391 unsigned RequestRebuildCounter)
1392 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1393 std::unique_lock<std::mutex> Lock(File.Mutex);
1394 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1395 if (WasCancelledBeforeConstruction)
1396 return;
1397
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001398 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1399 return !File.RebuildInProgress ||
1400 File.RebuildCounter != RequestRebuildCounter;
1401 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001402
1403 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1404 if (WasCancelledBeforeConstruction)
1405 return;
1406
1407 File.RebuildInProgress = true;
1408}
1409
1410bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1411 return WasCancelledBeforeConstruction;
1412}
1413
1414CppFile::RebuildGuard::~RebuildGuard() {
1415 if (WasCancelledBeforeConstruction)
1416 return;
1417
1418 std::unique_lock<std::mutex> Lock(File.Mutex);
1419 assert(File.RebuildInProgress);
1420 File.RebuildInProgress = false;
1421
1422 if (File.RebuildCounter == RequestRebuildCounter) {
1423 // Our rebuild request was successful.
1424 assert(futureIsReady(File.ASTFuture));
1425 assert(futureIsReady(File.PreambleFuture));
1426 } else {
1427 // Our rebuild request was cancelled, because further reparse was requested.
1428 assert(!futureIsReady(File.ASTFuture));
1429 assert(!futureIsReady(File.PreambleFuture));
1430 }
1431
1432 Lock.unlock();
1433 File.RebuildCond.notify_all();
1434}
Haojian Wu345099c2017-11-09 11:30:04 +00001435
1436SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
1437 const Position &Pos,
1438 const FileEntry *FE) {
1439 // The language server protocol uses zero-based line and column numbers.
1440 // Clang uses one-based numbers.
1441
1442 const ASTContext &AST = Unit.getASTContext();
1443 const SourceManager &SourceMgr = AST.getSourceManager();
1444
1445 SourceLocation InputLocation =
1446 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
1447 if (Pos.character == 0) {
1448 return InputLocation;
1449 }
1450
1451 // This handle cases where the position is in the middle of a token or right
1452 // after the end of a token. In theory we could just use GetBeginningOfToken
1453 // to find the start of the token at the input position, but this doesn't
1454 // work when right after the end, i.e. foo|.
1455 // So try to go back by one and see if we're still inside the an identifier
1456 // token. If so, Take the beginning of this token.
1457 // (It should be the same identifier because you can't have two adjacent
1458 // identifiers without another token in between.)
1459 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
1460 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
1461 Token Result;
1462 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
1463 AST.getLangOpts(), false)) {
1464 // getRawToken failed, just use InputLocation.
1465 return InputLocation;
1466 }
1467
1468 if (Result.is(tok::raw_identifier)) {
1469 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
1470 AST.getLangOpts());
1471 }
1472
1473 return InputLocation;
1474}