blob: bd205e02ca5096a5ed10f8198ea71b2ebe15b267 [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;
378 // Higher score is worse. FIXME: use a more natural scale!
379 int Score;
380
381 // Comparison reflects rank: better candidates are smaller.
382 bool operator<(const CompletionCandidate &C) const {
383 if (Score != C.Score)
384 return Score < C.Score;
385 return *Result < *C.Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000386 }
387
Sam McCalla40371b2017-11-15 09:16:29 +0000388 std::string sortText() const {
389 // Fill in the sortText of the CompletionItem.
390 assert(Score <= 999999 && "Expecting score to have at most 6-digits");
391 std::string S, NameStorage;
392 StringRef Name = Result->getOrderedName(NameStorage);
393 llvm::raw_string_ostream(S)
394 << llvm::format("%06d%.*s", Score, Name.size(), Name.data());
395 return S;
396 }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000397
398private:
Sam McCalla40371b2017-11-15 09:16:29 +0000399 static int score(const CodeCompletionResult &Result) {
400 int Score = Result.Priority;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000401 // Fill in the sortText of the CompletionItem.
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000402 assert(Score <= 99999 && "Expecting code completion result "
403 "priority to have at most 5-digits");
404
405 const int Penalty = 100000;
Sam McCalla40371b2017-11-15 09:16:29 +0000406 switch (static_cast<CXAvailabilityKind>(Result.Availability)) {
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000407 case CXAvailability_Available:
408 // No penalty.
409 break;
410 case CXAvailability_Deprecated:
411 Score += Penalty;
412 break;
413 case CXAvailability_NotAccessible:
414 Score += 2 * Penalty;
415 break;
416 case CXAvailability_NotAvailable:
417 Score += 3 * Penalty;
418 break;
419 }
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000420 return Score;
421 }
Sam McCalla40371b2017-11-15 09:16:29 +0000422};
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000423
Sam McCalla40371b2017-11-15 09:16:29 +0000424class CompletionItemsCollector : public CodeCompleteConsumer {
425public:
426 CompletionItemsCollector(const clangd::CodeCompleteOptions &CodeCompleteOpts,
427 CompletionList &Items)
428 : CodeCompleteConsumer(CodeCompleteOpts.getClangCompleteOpts(),
429 /*OutputIsBinary=*/false),
430 ClangdOpts(CodeCompleteOpts), Items(Items),
431 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
432 CCTUInfo(Allocator) {}
433
434 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
435 CodeCompletionResult *Results,
436 unsigned NumResults) override final {
437 std::priority_queue<CompletionCandidate> Candidates;
438 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCalladccab62017-11-23 16:58:22 +0000439 auto &Result = Results[I];
440 if (!ClangdOpts.IncludeIneligibleResults &&
441 (Result.Availability == CXAvailability_NotAvailable ||
442 Result.Availability == CXAvailability_NotAccessible))
443 continue;
444 Candidates.emplace(Result);
Sam McCalla40371b2017-11-15 09:16:29 +0000445 if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
446 Candidates.pop();
447 Items.isIncomplete = true;
448 }
449 }
450 while (!Candidates.empty()) {
451 auto &Candidate = Candidates.top();
452 const auto *CCS = Candidate.Result->CreateCodeCompletionString(
453 S, Context, *Allocator, CCTUInfo,
454 CodeCompleteOpts.IncludeBriefComments);
455 assert(CCS && "Expected the CodeCompletionString to be non-null");
456 Items.items.push_back(ProcessCodeCompleteResult(Candidate, *CCS));
457 Candidates.pop();
458 }
459 std::reverse(Items.items.begin(), Items.items.end());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000460 }
461
Sam McCalla40371b2017-11-15 09:16:29 +0000462 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
463
464 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
465
466private:
467 CompletionItem
468 ProcessCodeCompleteResult(const CompletionCandidate &Candidate,
469 const CodeCompletionString &CCS) const {
470
471 // Adjust this to InsertTextFormat::Snippet iff we encounter a
472 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
473 CompletionItem Item;
474 Item.insertTextFormat = InsertTextFormat::PlainText;
475
476 Item.documentation = getDocumentation(CCS);
477 Item.sortText = Candidate.sortText();
478
479 // Fill in the label, detail, insertText and filterText fields of the
480 // CompletionItem.
481 ProcessChunks(CCS, Item);
482
483 // Fill in the kind field of the CompletionItem.
484 Item.kind = getKind(Candidate.Result->Kind, Candidate.Result->CursorKind);
485
486 return Item;
487 }
488
489 virtual void ProcessChunks(const CodeCompletionString &CCS,
490 CompletionItem &Item) const = 0;
491
492 clangd::CodeCompleteOptions ClangdOpts;
493 CompletionList &Items;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000494 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
495 CodeCompletionTUInfo CCTUInfo;
496
497}; // CompletionItemsCollector
498
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000499bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
500 return Chunk.Kind == CodeCompletionString::CK_Informative &&
501 StringRef(Chunk.Text).endswith("::");
502}
503
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000504class PlainTextCompletionItemsCollector final
505 : public CompletionItemsCollector {
506
507public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000508 PlainTextCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000509 const clangd::CodeCompleteOptions &CodeCompleteOpts,
510 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000511 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
512
513private:
514 void ProcessChunks(const CodeCompletionString &CCS,
515 CompletionItem &Item) const override {
516 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000517 // Informative qualifier chunks only clutter completion results, skip
518 // them.
519 if (isInformativeQualifierChunk(Chunk))
520 continue;
521
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000522 switch (Chunk.Kind) {
523 case CodeCompletionString::CK_TypedText:
524 // There's always exactly one CK_TypedText chunk.
525 Item.insertText = Item.filterText = Chunk.Text;
526 Item.label += Chunk.Text;
527 break;
528 case CodeCompletionString::CK_ResultType:
529 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
530 Item.detail = Chunk.Text;
531 break;
532 case CodeCompletionString::CK_Optional:
533 break;
534 default:
535 Item.label += Chunk.Text;
536 break;
537 }
538 }
539 }
540}; // PlainTextCompletionItemsCollector
541
542class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
543
544public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000545 SnippetCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000546 const clangd::CodeCompleteOptions &CodeCompleteOpts,
547 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000548 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
549
550private:
551 void ProcessChunks(const CodeCompletionString &CCS,
552 CompletionItem &Item) const override {
553 unsigned ArgCount = 0;
554 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000555 // Informative qualifier chunks only clutter completion results, skip
556 // them.
557 if (isInformativeQualifierChunk(Chunk))
558 continue;
559
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000560 switch (Chunk.Kind) {
561 case CodeCompletionString::CK_TypedText:
562 // The piece of text that the user is expected to type to match
563 // the code-completion string, typically a keyword or the name of
564 // a declarator or macro.
565 Item.filterText = Chunk.Text;
Simon Pilgrim948c0bc2017-11-01 09:22:03 +0000566 LLVM_FALLTHROUGH;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000567 case CodeCompletionString::CK_Text:
568 // A piece of text that should be placed in the buffer,
569 // e.g., parentheses or a comma in a function call.
570 Item.label += Chunk.Text;
571 Item.insertText += Chunk.Text;
572 break;
573 case CodeCompletionString::CK_Optional:
574 // A code completion string that is entirely optional.
575 // For example, an optional code completion string that
576 // describes the default arguments in a function call.
577
578 // FIXME: Maybe add an option to allow presenting the optional chunks?
579 break;
580 case CodeCompletionString::CK_Placeholder:
581 // A string that acts as a placeholder for, e.g., a function call
582 // argument.
583 ++ArgCount;
584 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
585 escapeSnippet(Chunk.Text) + '}';
586 Item.label += Chunk.Text;
587 Item.insertTextFormat = InsertTextFormat::Snippet;
588 break;
589 case CodeCompletionString::CK_Informative:
590 // A piece of text that describes something about the result
591 // but should not be inserted into the buffer.
592 // For example, the word "const" for a const method, or the name of
593 // the base class for methods that are part of the base class.
594 Item.label += Chunk.Text;
595 // Don't put the informative chunks in the insertText.
596 break;
597 case CodeCompletionString::CK_ResultType:
598 // A piece of text that describes the type of an entity or,
599 // for functions and methods, the return type.
600 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
601 Item.detail = Chunk.Text;
602 break;
603 case CodeCompletionString::CK_CurrentParameter:
604 // A piece of text that describes the parameter that corresponds to
605 // the code-completion location within a function call, message send,
606 // macro invocation, etc.
607 //
608 // This should never be present while collecting completion items,
609 // only while collecting overload candidates.
610 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
611 "CompletionItems");
612 break;
613 case CodeCompletionString::CK_LeftParen:
614 // A left parenthesis ('(').
615 case CodeCompletionString::CK_RightParen:
616 // A right parenthesis (')').
617 case CodeCompletionString::CK_LeftBracket:
618 // A left bracket ('[').
619 case CodeCompletionString::CK_RightBracket:
620 // A right bracket (']').
621 case CodeCompletionString::CK_LeftBrace:
622 // A left brace ('{').
623 case CodeCompletionString::CK_RightBrace:
624 // A right brace ('}').
625 case CodeCompletionString::CK_LeftAngle:
626 // A left angle bracket ('<').
627 case CodeCompletionString::CK_RightAngle:
628 // A right angle bracket ('>').
629 case CodeCompletionString::CK_Comma:
630 // A comma separator (',').
631 case CodeCompletionString::CK_Colon:
632 // A colon (':').
633 case CodeCompletionString::CK_SemiColon:
634 // A semicolon (';').
635 case CodeCompletionString::CK_Equal:
636 // An '=' sign.
637 case CodeCompletionString::CK_HorizontalSpace:
638 // Horizontal whitespace (' ').
639 Item.insertText += Chunk.Text;
640 Item.label += Chunk.Text;
641 break;
642 case CodeCompletionString::CK_VerticalSpace:
643 // Vertical whitespace ('\n' or '\r\n', depending on the
644 // platform).
645 Item.insertText += Chunk.Text;
646 // Don't even add a space to the label.
647 break;
648 }
649 }
650 }
651}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000652
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000653class SignatureHelpCollector final : public CodeCompleteConsumer {
654
655public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000656 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000657 SignatureHelp &SigHelp)
658 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
659 SigHelp(SigHelp),
660 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
661 CCTUInfo(Allocator) {}
662
663 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
664 OverloadCandidate *Candidates,
665 unsigned NumCandidates) override {
666 SigHelp.signatures.reserve(NumCandidates);
667 // FIXME(rwols): How can we determine the "active overload candidate"?
668 // Right now the overloaded candidates seem to be provided in a "best fit"
669 // order, so I'm not too worried about this.
670 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000671 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000672 "too many arguments");
673 SigHelp.activeParameter = static_cast<int>(CurrentArg);
674 for (unsigned I = 0; I < NumCandidates; ++I) {
675 const auto &Candidate = Candidates[I];
676 const auto *CCS = Candidate.CreateSignatureString(
677 CurrentArg, S, *Allocator, CCTUInfo, true);
678 assert(CCS && "Expected the CodeCompletionString to be non-null");
679 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
680 }
681 }
682
683 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
684
685 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
686
687private:
688 SignatureInformation
689 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
690 const CodeCompletionString &CCS) const {
691 SignatureInformation Result;
692 const char *ReturnType = nullptr;
693
694 Result.documentation = getDocumentation(CCS);
695
696 for (const auto &Chunk : CCS) {
697 switch (Chunk.Kind) {
698 case CodeCompletionString::CK_ResultType:
699 // A piece of text that describes the type of an entity or,
700 // for functions and methods, the return type.
701 assert(!ReturnType && "Unexpected CK_ResultType");
702 ReturnType = Chunk.Text;
703 break;
704 case CodeCompletionString::CK_Placeholder:
705 // A string that acts as a placeholder for, e.g., a function call
706 // argument.
707 // Intentional fallthrough here.
708 case CodeCompletionString::CK_CurrentParameter: {
709 // A piece of text that describes the parameter that corresponds to
710 // the code-completion location within a function call, message send,
711 // macro invocation, etc.
712 Result.label += Chunk.Text;
713 ParameterInformation Info;
714 Info.label = Chunk.Text;
715 Result.parameters.push_back(std::move(Info));
716 break;
717 }
718 case CodeCompletionString::CK_Optional: {
719 // The rest of the parameters are defaulted/optional.
720 assert(Chunk.Optional &&
721 "Expected the optional code completion string to be non-null.");
722 Result.label +=
723 getOptionalParameters(*Chunk.Optional, Result.parameters);
724 break;
725 }
726 case CodeCompletionString::CK_VerticalSpace:
727 break;
728 default:
729 Result.label += Chunk.Text;
730 break;
731 }
732 }
733 if (ReturnType) {
734 Result.label += " -> ";
735 Result.label += ReturnType;
736 }
737 return Result;
738 }
739
740 SignatureHelp &SigHelp;
741 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
742 CodeCompletionTUInfo CCTUInfo;
743
744}; // SignatureHelpCollector
745
746bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000747 const clang::CodeCompleteOptions &Options,
748 PathRef FileName,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000749 const tooling::CompileCommand &Command,
750 PrecompiledPreamble const *Preamble, StringRef Contents,
751 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
752 std::shared_ptr<PCHContainerOperations> PCHs,
753 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000754 std::vector<const char *> ArgStrs;
755 for (const auto &S : Command.CommandLine)
756 ArgStrs.push_back(S.c_str());
757
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000758 VFS->setCurrentWorkingDirectory(Command.Directory);
759
Ilya Biryukov04db3682017-07-21 13:29:29 +0000760 std::unique_ptr<CompilerInvocation> CI;
761 EmptyDiagsConsumer DummyDiagsConsumer;
762 {
763 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
764 CompilerInstance::createDiagnostics(new DiagnosticOptions,
765 &DummyDiagsConsumer, false);
766 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
767 }
768 assert(CI && "Couldn't create CompilerInvocation");
769
770 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
771 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
772
773 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000774 if (Preamble) {
775 auto Bounds =
776 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000777 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
778 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000779 }
780
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000781 auto Clang = prepareCompilerInstance(
782 std::move(CI), Preamble, std::move(ContentsBuffer), std::move(PCHs),
783 std::move(VFS), DummyDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000784 auto &DiagOpts = Clang->getDiagnosticOpts();
785 DiagOpts.IgnoreWarnings = true;
786
787 auto &FrontendOpts = Clang->getFrontendOpts();
788 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000789 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000790 FrontendOpts.CodeCompletionAt.FileName = FileName;
791 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
792 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
793
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000794 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000795
Ilya Biryukov04db3682017-07-21 13:29:29 +0000796 SyntaxOnlyAction Action;
797 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000798 Logger.log("BeginSourceFile() failed when running codeComplete for " +
799 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000800 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000801 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000802 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000803 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000804 return false;
805 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000806
Ilya Biryukov04db3682017-07-21 13:29:29 +0000807 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000808
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000809 return true;
810}
811
812} // namespace
813
Sam McCalla40371b2017-11-15 09:16:29 +0000814clang::CodeCompleteOptions
815clangd::CodeCompleteOptions::getClangCompleteOpts() const {
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000816 clang::CodeCompleteOptions Result;
817 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
818 Result.IncludeMacros = IncludeMacros;
819 Result.IncludeGlobals = IncludeGlobals;
820 Result.IncludeBriefComments = IncludeBriefComments;
821
822 return Result;
823}
824
Sam McCalla40371b2017-11-15 09:16:29 +0000825CompletionList
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000826clangd::codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000827 PrecompiledPreamble const *Preamble, StringRef Contents,
828 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
829 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000830 clangd::CodeCompleteOptions Opts, clangd::Logger &Logger) {
Sam McCalla40371b2017-11-15 09:16:29 +0000831 CompletionList Results;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000832 std::unique_ptr<CodeCompleteConsumer> Consumer;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000833 if (Opts.EnableSnippets) {
Sam McCalla40371b2017-11-15 09:16:29 +0000834 Consumer =
835 llvm::make_unique<SnippetCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000836 } else {
Sam McCalla40371b2017-11-15 09:16:29 +0000837 Consumer =
838 llvm::make_unique<PlainTextCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000839 }
Sam McCalla40371b2017-11-15 09:16:29 +0000840 invokeCodeComplete(std::move(Consumer), Opts.getClangCompleteOpts(), FileName,
841 Command, Preamble, Contents, Pos, std::move(VFS),
842 std::move(PCHs), Logger);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000843 return Results;
844}
845
846SignatureHelp
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000847clangd::signatureHelp(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000848 PrecompiledPreamble const *Preamble, StringRef Contents,
849 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
850 std::shared_ptr<PCHContainerOperations> PCHs,
851 clangd::Logger &Logger) {
852 SignatureHelp Result;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000853 clang::CodeCompleteOptions Options;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000854 Options.IncludeGlobals = false;
855 Options.IncludeMacros = false;
856 Options.IncludeCodePatterns = false;
857 Options.IncludeBriefComments = true;
858 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
859 Options, FileName, Command, Preamble, Contents, Pos,
860 std::move(VFS), std::move(PCHs), Logger);
861 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000862}
863
Ilya Biryukov02d58702017-08-01 15:51:38 +0000864void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
865 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000866}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000867
Ilya Biryukov02d58702017-08-01 15:51:38 +0000868llvm::Optional<ParsedAST>
869ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
870 const PrecompiledPreamble *Preamble,
871 ArrayRef<serialization::DeclID> PreambleDeclIDs,
872 std::unique_ptr<llvm::MemoryBuffer> Buffer,
873 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000874 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
875 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000876
877 std::vector<DiagWithFixIts> ASTDiags;
878 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
879
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000880 auto Clang = prepareCompilerInstance(
881 std::move(CI), Preamble, std::move(Buffer), std::move(PCHs),
882 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000883
884 // Recover resources if we crash before exiting this method.
885 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
886 Clang.get());
887
888 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000889 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
890 if (!Action->BeginSourceFile(*Clang, MainInput)) {
891 Logger.log("BeginSourceFile() failed when building AST for " +
892 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000893 return llvm::None;
894 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000895 if (!Action->Execute())
896 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000897
898 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
899 // has a longer lifetime.
900 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
901
902 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
903 std::vector<serialization::DeclID> PendingDecls;
904 if (Preamble) {
905 PendingDecls.reserve(PreambleDeclIDs.size());
906 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
907 PreambleDeclIDs.end());
908 }
909
910 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
911 std::move(PendingDecls), std::move(ASTDiags));
912}
913
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000914namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000915
916SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
917 const FileEntry *FE,
918 unsigned Offset) {
919 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
920 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
921}
922
923SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
924 const FileEntry *FE, Position Pos) {
925 SourceLocation InputLoc =
926 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
927 return Mgr.getMacroArgExpandedLocation(InputLoc);
928}
929
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000930/// Finds declarations locations that a given source location refers to.
931class DeclarationLocationsFinder : public index::IndexDataConsumer {
932 std::vector<Location> DeclarationLocations;
933 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000934 const ASTContext &AST;
935 Preprocessor &PP;
936
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000937public:
938 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000939 const SourceLocation &SearchedLocation,
940 ASTContext &AST, Preprocessor &PP)
941 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000942
943 std::vector<Location> takeLocations() {
944 // Don't keep the same location multiple times.
945 // This can happen when nodes in the AST are visited twice.
946 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000947 auto last =
948 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000949 DeclarationLocations.erase(last, DeclarationLocations.end());
950 return std::move(DeclarationLocations);
951 }
952
Ilya Biryukov02d58702017-08-01 15:51:38 +0000953 bool
954 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
955 ArrayRef<index::SymbolRelation> Relations, FileID FID,
956 unsigned Offset,
957 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000958 if (isSearchedLocation(FID, Offset)) {
959 addDeclarationLocation(D->getSourceRange());
960 }
961 return true;
962 }
963
964private:
965 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000966 const SourceManager &SourceMgr = AST.getSourceManager();
967 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
968 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000969 }
970
Ilya Biryukov04db3682017-07-21 13:29:29 +0000971 void addDeclarationLocation(const SourceRange &ValSourceRange) {
972 const SourceManager &SourceMgr = AST.getSourceManager();
973 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000974 SourceLocation LocStart = ValSourceRange.getBegin();
975 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000976 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000977 Position Begin;
978 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
979 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
980 Position End;
981 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
982 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
983 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000984 Location L;
Marc-Andre Laperleba070102017-11-07 16:16:45 +0000985 if (const FileEntry *F =
986 SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) {
987 StringRef FilePath = F->tryGetRealPathName();
988 if (FilePath.empty())
989 FilePath = F->getName();
990 L.uri = URI::fromFile(FilePath);
991 L.range = R;
992 DeclarationLocations.push_back(L);
993 }
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000994 }
995
Kirill Bobyrev46213872017-06-28 20:57:28 +0000996 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000997 // Also handle possible macro at the searched location.
998 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000999 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
1000 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001001 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001002 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001003 }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001004 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001005 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
1006 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001007 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001008 // Get the definition just before the searched location so that a macro
1009 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +00001010 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
1011 AST.getSourceManager(),
1012 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001013 DecLoc.second - 1);
1014 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001015 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
1016 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001017 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001018 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
1019 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001020 }
1021 }
1022 }
1023 }
1024};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001025
Ilya Biryukov02d58702017-08-01 15:51:38 +00001026} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001027
Ilya Biryukove5128f72017-09-20 07:24:15 +00001028std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1029 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001030 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1031 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1032 if (!FE)
1033 return {};
1034
1035 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1036
1037 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1038 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1039 AST.getPreprocessor());
1040 index::IndexingOptions IndexOpts;
1041 IndexOpts.SystemSymbolFilter =
1042 index::IndexingOptions::SystemSymbolFilterKind::All;
1043 IndexOpts.IndexFunctionLocals = true;
1044
1045 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1046 DeclLocationsFinder, IndexOpts);
1047
1048 return DeclLocationsFinder->takeLocations();
1049}
1050
1051void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001052 if (PendingTopLevelDecls.empty())
1053 return;
1054
1055 std::vector<const Decl *> Resolved;
1056 Resolved.reserve(PendingTopLevelDecls.size());
1057
1058 ExternalASTSource &Source = *getASTContext().getExternalSource();
1059 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
1060 // Resolve the declaration ID to an actual declaration, possibly
1061 // deserializing the declaration in the process.
1062 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1063 Resolved.push_back(D);
1064 }
1065
1066 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
1067 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1068
1069 PendingTopLevelDecls.clear();
1070}
1071
Ilya Biryukov02d58702017-08-01 15:51:38 +00001072ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001073
Ilya Biryukov02d58702017-08-01 15:51:38 +00001074ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001075
Ilya Biryukov02d58702017-08-01 15:51:38 +00001076ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001077 if (Action) {
1078 Action->EndSourceFile();
1079 }
1080}
1081
Ilya Biryukov02d58702017-08-01 15:51:38 +00001082ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1083
1084const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001085 return Clang->getASTContext();
1086}
1087
Ilya Biryukov02d58702017-08-01 15:51:38 +00001088Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001089
Ilya Biryukov02d58702017-08-01 15:51:38 +00001090const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001091 return Clang->getPreprocessor();
1092}
1093
Ilya Biryukov02d58702017-08-01 15:51:38 +00001094ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001095 ensurePreambleDeclsDeserialized();
1096 return TopLevelDecls;
1097}
1098
Ilya Biryukov02d58702017-08-01 15:51:38 +00001099const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001100 return Diags;
1101}
1102
Ilya Biryukov02d58702017-08-01 15:51:38 +00001103ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
1104 std::unique_ptr<FrontendAction> Action,
1105 std::vector<const Decl *> TopLevelDecls,
1106 std::vector<serialization::DeclID> PendingTopLevelDecls,
1107 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001108 : Clang(std::move(Clang)), Action(std::move(Action)),
1109 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
1110 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
1111 assert(this->Clang);
1112 assert(this->Action);
1113}
1114
Ilya Biryukov02d58702017-08-01 15:51:38 +00001115ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1116 : AST(std::move(Wrapper.AST)) {}
1117
1118ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1119 : AST(std::move(AST)) {}
1120
1121PreambleData::PreambleData(PrecompiledPreamble Preamble,
1122 std::vector<serialization::DeclID> TopLevelDeclIDs,
1123 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001124 : Preamble(std::move(Preamble)),
1125 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001126
1127std::shared_ptr<CppFile>
1128CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001129 bool StorePreamblesInMemory,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001130 std::shared_ptr<PCHContainerOperations> PCHs,
1131 clangd::Logger &Logger) {
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001132 return std::shared_ptr<CppFile>(new CppFile(FileName, std::move(Command),
1133 StorePreamblesInMemory,
1134 std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001135}
1136
1137CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001138 bool StorePreamblesInMemory,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001139 std::shared_ptr<PCHContainerOperations> PCHs,
1140 clangd::Logger &Logger)
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001141 : FileName(FileName), Command(std::move(Command)),
1142 StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001143 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001144
1145 std::lock_guard<std::mutex> Lock(Mutex);
1146 LatestAvailablePreamble = nullptr;
1147 PreamblePromise.set_value(nullptr);
1148 PreambleFuture = PreamblePromise.get_future();
1149
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001150 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001151 ASTFuture = ASTPromise.get_future();
1152}
1153
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001154void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001155
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001156UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001157 std::unique_lock<std::mutex> Lock(Mutex);
1158 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001159 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001160 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1161 // We want to keep this invariant.
1162 if (futureIsReady(PreambleFuture)) {
1163 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1164 PreambleFuture = PreamblePromise.get_future();
1165 }
1166 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001167 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001168 ASTFuture = ASTPromise.get_future();
1169 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001170
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001171 Lock.unlock();
1172 // Notify about changes to RebuildCounter.
1173 RebuildCond.notify_all();
1174
1175 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001176 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001177 std::unique_lock<std::mutex> Lock(That->Mutex);
1178 CppFile *This = &*That;
1179 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1180 return !This->RebuildInProgress ||
1181 This->RebuildCounter != RequestRebuildCounter;
1182 });
1183
1184 // This computation got cancelled itself, do nothing.
1185 if (This->RebuildCounter != RequestRebuildCounter)
1186 return;
1187
1188 // Set empty results for Promises.
1189 That->PreamblePromise.set_value(nullptr);
1190 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001191 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001192}
1193
1194llvm::Optional<std::vector<DiagWithFixIts>>
1195CppFile::rebuild(StringRef NewContents,
1196 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001197 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001198}
1199
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001200UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001201CppFile::deferRebuild(StringRef NewContents,
1202 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1203 std::shared_ptr<const PreambleData> OldPreamble;
1204 std::shared_ptr<PCHContainerOperations> PCHs;
1205 unsigned RequestRebuildCounter;
1206 {
1207 std::unique_lock<std::mutex> Lock(Mutex);
1208 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1209 // They will try to exit as early as possible and won't call set_value on
1210 // our promises.
1211 RequestRebuildCounter = ++this->RebuildCounter;
1212 PCHs = this->PCHs;
1213
1214 // Remember the preamble to be used during rebuild.
1215 OldPreamble = this->LatestAvailablePreamble;
1216 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1217 // futures will wait until the rebuild process is finished.
1218 if (futureIsReady(this->PreambleFuture)) {
1219 this->PreamblePromise =
1220 std::promise<std::shared_ptr<const PreambleData>>();
1221 this->PreambleFuture = this->PreamblePromise.get_future();
1222 }
1223 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001224 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001225 this->ASTFuture = this->ASTPromise.get_future();
1226 }
1227 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001228 // Notify about changes to RebuildCounter.
1229 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001230
1231 // A helper to function to finish the rebuild. May be run on a different
1232 // thread.
1233
1234 // Don't let this CppFile die before rebuild is finished.
1235 std::shared_ptr<CppFile> That = shared_from_this();
1236 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
Ilya Biryukov11a02522017-11-17 19:05:56 +00001237 That](std::string NewContents) mutable // 'mutable' to
1238 // allow changing
1239 // OldPreamble.
Ilya Biryukov02d58702017-08-01 15:51:38 +00001240 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1241 // Only one execution of this method is possible at a time.
1242 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1243 // into a state for doing a rebuild.
1244 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1245 if (Rebuild.wasCancelledBeforeConstruction())
1246 return llvm::None;
1247
1248 std::vector<const char *> ArgStrs;
1249 for (const auto &S : That->Command.CommandLine)
1250 ArgStrs.push_back(S.c_str());
1251
1252 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1253
1254 std::unique_ptr<CompilerInvocation> CI;
1255 {
1256 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1257 // reporting them.
1258 EmptyDiagsConsumer CommandLineDiagsConsumer;
1259 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1260 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1261 &CommandLineDiagsConsumer, false);
1262 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1263 }
1264 assert(CI && "Couldn't create CompilerInvocation");
1265
1266 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1267 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1268
1269 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +00001270 // not mutate any fields of CppFile, only does the actual computation.
1271 // Lamdba is marked mutable to call reset() on OldPreamble.
1272 auto DoRebuildPreamble =
1273 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001274 auto Bounds =
1275 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1276 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1277 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1278 return OldPreamble;
1279 }
Ilya Biryukov11a02522017-11-17 19:05:56 +00001280 // We won't need the OldPreamble anymore, release it so it can be deleted
1281 // (if there are no other references to it).
1282 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001283
Sam McCall8567cb32017-11-02 09:21:51 +00001284 trace::Span Tracer(llvm::Twine("Preamble: ") + That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001285 std::vector<DiagWithFixIts> PreambleDiags;
1286 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1287 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1288 CompilerInstance::createDiagnostics(
1289 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1290 CppFilePreambleCallbacks SerializedDeclsCollector;
1291 auto BuiltPreamble = PrecompiledPreamble::Build(
1292 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +00001293 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001294 SerializedDeclsCollector);
1295
1296 if (BuiltPreamble) {
1297 return std::make_shared<PreambleData>(
1298 std::move(*BuiltPreamble),
1299 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1300 std::move(PreambleDiags));
1301 } else {
1302 return nullptr;
1303 }
1304 };
1305
1306 // Compute updated Preamble.
1307 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1308 // Publish the new Preamble.
1309 {
1310 std::lock_guard<std::mutex> Lock(That->Mutex);
1311 // We always set LatestAvailablePreamble to the new value, hoping that it
1312 // will still be usable in the further requests.
1313 That->LatestAvailablePreamble = NewPreamble;
1314 if (RequestRebuildCounter != That->RebuildCounter)
1315 return llvm::None; // Our rebuild request was cancelled, do nothing.
1316 That->PreamblePromise.set_value(NewPreamble);
1317 } // unlock Mutex
1318
1319 // Prepare the Preamble and supplementary data for rebuilding AST.
1320 const PrecompiledPreamble *PreambleForAST = nullptr;
1321 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1322 std::vector<DiagWithFixIts> Diagnostics;
1323 if (NewPreamble) {
1324 PreambleForAST = &NewPreamble->Preamble;
1325 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1326 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1327 NewPreamble->Diags.end());
1328 }
1329
1330 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +00001331 llvm::Optional<ParsedAST> NewAST;
1332 {
1333 trace::Span Tracer(llvm::Twine("Build: ") + That->FileName);
1334 NewAST = ParsedAST::Build(
1335 std::move(CI), PreambleForAST, SerializedPreambleDecls,
1336 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
1337 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001338
1339 if (NewAST) {
1340 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1341 NewAST->getDiagnostics().end());
1342 } else {
1343 // Don't report even Preamble diagnostics if we coulnd't build AST.
1344 Diagnostics.clear();
1345 }
1346
1347 // Publish the new AST.
1348 {
1349 std::lock_guard<std::mutex> Lock(That->Mutex);
1350 if (RequestRebuildCounter != That->RebuildCounter)
1351 return Diagnostics; // Our rebuild request was cancelled, don't set
1352 // ASTPromise.
1353
Ilya Biryukov574b7532017-08-02 09:08:39 +00001354 That->ASTPromise.set_value(
1355 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001356 } // unlock Mutex
1357
1358 return Diagnostics;
1359 };
1360
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001361 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001362}
1363
1364std::shared_future<std::shared_ptr<const PreambleData>>
1365CppFile::getPreamble() const {
1366 std::lock_guard<std::mutex> Lock(Mutex);
1367 return PreambleFuture;
1368}
1369
1370std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1371 std::lock_guard<std::mutex> Lock(Mutex);
1372 return LatestAvailablePreamble;
1373}
1374
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001375std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001376 std::lock_guard<std::mutex> Lock(Mutex);
1377 return ASTFuture;
1378}
1379
1380tooling::CompileCommand const &CppFile::getCompileCommand() const {
1381 return Command;
1382}
1383
1384CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1385 unsigned RequestRebuildCounter)
1386 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1387 std::unique_lock<std::mutex> Lock(File.Mutex);
1388 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1389 if (WasCancelledBeforeConstruction)
1390 return;
1391
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001392 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1393 return !File.RebuildInProgress ||
1394 File.RebuildCounter != RequestRebuildCounter;
1395 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001396
1397 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1398 if (WasCancelledBeforeConstruction)
1399 return;
1400
1401 File.RebuildInProgress = true;
1402}
1403
1404bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1405 return WasCancelledBeforeConstruction;
1406}
1407
1408CppFile::RebuildGuard::~RebuildGuard() {
1409 if (WasCancelledBeforeConstruction)
1410 return;
1411
1412 std::unique_lock<std::mutex> Lock(File.Mutex);
1413 assert(File.RebuildInProgress);
1414 File.RebuildInProgress = false;
1415
1416 if (File.RebuildCounter == RequestRebuildCounter) {
1417 // Our rebuild request was successful.
1418 assert(futureIsReady(File.ASTFuture));
1419 assert(futureIsReady(File.PreambleFuture));
1420 } else {
1421 // Our rebuild request was cancelled, because further reparse was requested.
1422 assert(!futureIsReady(File.ASTFuture));
1423 assert(!futureIsReady(File.PreambleFuture));
1424 }
1425
1426 Lock.unlock();
1427 File.RebuildCond.notify_all();
1428}
Haojian Wu345099c2017-11-09 11:30:04 +00001429
1430SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
1431 const Position &Pos,
1432 const FileEntry *FE) {
1433 // The language server protocol uses zero-based line and column numbers.
1434 // Clang uses one-based numbers.
1435
1436 const ASTContext &AST = Unit.getASTContext();
1437 const SourceManager &SourceMgr = AST.getSourceManager();
1438
1439 SourceLocation InputLocation =
1440 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
1441 if (Pos.character == 0) {
1442 return InputLocation;
1443 }
1444
1445 // This handle cases where the position is in the middle of a token or right
1446 // after the end of a token. In theory we could just use GetBeginningOfToken
1447 // to find the start of the token at the input position, but this doesn't
1448 // work when right after the end, i.e. foo|.
1449 // So try to go back by one and see if we're still inside the an identifier
1450 // token. If so, Take the beginning of this token.
1451 // (It should be the same identifier because you can't have two adjacent
1452 // identifiers without another token in between.)
1453 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
1454 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
1455 Token Result;
1456 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
1457 AST.getLangOpts(), false)) {
1458 // getRawToken failed, just use InputLocation.
1459 return InputLocation;
1460 }
1461
1462 if (Result.is(tok::raw_identifier)) {
1463 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
1464 AST.getLangOpts());
1465 }
1466
1467 return InputLocation;
1468}