blob: 2fbc7a2d4d24a9ca4dee164a00b2a4dbce755c4e [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9
10#include "ClangdUnit.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000011
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Lex/PreprocessorOptions.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000027#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000030#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000031
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000033#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000034
Ilya Biryukov38d79772017-05-16 09:38:59 +000035using namespace clang::clangd;
36using namespace clang;
37
Ilya Biryukov04db3682017-07-21 13:29:29 +000038namespace {
39
40class DeclTrackingASTConsumer : public ASTConsumer {
41public:
42 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
43 : TopLevelDecls(TopLevelDecls) {}
44
45 bool HandleTopLevelDecl(DeclGroupRef DG) override {
46 for (const Decl *D : DG) {
47 // ObjCMethodDecl are not actually top-level decls.
48 if (isa<ObjCMethodDecl>(D))
49 continue;
50
51 TopLevelDecls.push_back(D);
52 }
53 return true;
54 }
55
56private:
57 std::vector<const Decl *> &TopLevelDecls;
58};
59
60class ClangdFrontendAction : public SyntaxOnlyAction {
61public:
62 std::vector<const Decl *> takeTopLevelDecls() {
63 return std::move(TopLevelDecls);
64 }
65
66protected:
67 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
68 StringRef InFile) override {
69 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
70 }
71
72private:
73 std::vector<const Decl *> TopLevelDecls;
74};
75
Ilya Biryukov02d58702017-08-01 15:51:38 +000076class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000077public:
78 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
79 return std::move(TopLevelDeclIDs);
80 }
81
82 void AfterPCHEmitted(ASTWriter &Writer) override {
83 TopLevelDeclIDs.reserve(TopLevelDecls.size());
84 for (Decl *D : TopLevelDecls) {
85 // Invalid top-level decls may not have been serialized.
86 if (D->isInvalidDecl())
87 continue;
88 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
89 }
90 }
91
92 void HandleTopLevelDecl(DeclGroupRef DG) override {
93 for (Decl *D : DG) {
94 if (isa<ObjCMethodDecl>(D))
95 continue;
96 TopLevelDecls.push_back(D);
97 }
98 }
99
100private:
101 std::vector<Decl *> TopLevelDecls;
102 std::vector<serialization::DeclID> TopLevelDeclIDs;
103};
104
105/// Convert from clang diagnostic level to LSP severity.
106static int getSeverity(DiagnosticsEngine::Level L) {
107 switch (L) {
108 case DiagnosticsEngine::Remark:
109 return 4;
110 case DiagnosticsEngine::Note:
111 return 3;
112 case DiagnosticsEngine::Warning:
113 return 2;
114 case DiagnosticsEngine::Fatal:
115 case DiagnosticsEngine::Error:
116 return 1;
117 case DiagnosticsEngine::Ignored:
118 return 0;
119 }
120 llvm_unreachable("Unknown diagnostic level!");
121}
122
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000123/// Get the optional chunk as a string. This function is possibly recursive.
124///
125/// The parameter info for each parameter is appended to the Parameters.
126std::string
127getOptionalParameters(const CodeCompletionString &CCS,
128 std::vector<ParameterInformation> &Parameters) {
129 std::string Result;
130 for (const auto &Chunk : CCS) {
131 switch (Chunk.Kind) {
132 case CodeCompletionString::CK_Optional:
133 assert(Chunk.Optional &&
134 "Expected the optional code completion string to be non-null.");
135 Result += getOptionalParameters(*Chunk.Optional, Parameters);
136 break;
137 case CodeCompletionString::CK_VerticalSpace:
138 break;
139 case CodeCompletionString::CK_Placeholder:
140 // A string that acts as a placeholder for, e.g., a function call
141 // argument.
142 // Intentional fallthrough here.
143 case CodeCompletionString::CK_CurrentParameter: {
144 // A piece of text that describes the parameter that corresponds to
145 // the code-completion location within a function call, message send,
146 // macro invocation, etc.
147 Result += Chunk.Text;
148 ParameterInformation Info;
149 Info.label = Chunk.Text;
150 Parameters.push_back(std::move(Info));
151 break;
152 }
153 default:
154 Result += Chunk.Text;
155 break;
156 }
157 }
158 return Result;
159}
160
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000161llvm::Optional<DiagWithFixIts> toClangdDiag(const StoredDiagnostic &D) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000162 auto Location = D.getLocation();
163 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
164 return llvm::None;
165
166 Position P;
167 P.line = Location.getSpellingLineNumber() - 1;
168 P.character = Location.getSpellingColumnNumber();
169 Range R = {P, P};
170 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
171
172 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
173 for (const FixItHint &Fix : D.getFixIts()) {
174 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
175 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
176 }
177 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
178}
179
180class StoreDiagsConsumer : public DiagnosticConsumer {
181public:
182 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
183
184 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
185 const clang::Diagnostic &Info) override {
186 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
187
188 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
189 Output.push_back(std::move(*convertedDiag));
190 }
191
192private:
193 std::vector<DiagWithFixIts> &Output;
194};
195
196class EmptyDiagsConsumer : public DiagnosticConsumer {
197public:
198 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
199 const clang::Diagnostic &Info) override {}
200};
201
202std::unique_ptr<CompilerInvocation>
203createCompilerInvocation(ArrayRef<const char *> ArgList,
204 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
205 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
206 auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags),
207 std::move(VFS));
208 // We rely on CompilerInstance to manage the resource (i.e. free them on
209 // EndSourceFile), but that won't happen if DisableFree is set to true.
210 // Since createInvocationFromCommandLine sets it to true, we have to override
211 // it.
212 CI->getFrontendOpts().DisableFree = false;
213 return CI;
214}
215
216/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
217/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
218/// null. Note that vfs::FileSystem inside returned instance may differ from \p
219/// VFS if additional file remapping were set in command-line arguments.
220/// On some errors, returns null. When non-null value is returned, it's expected
221/// to be consumed by the FrontendAction as it will have a pointer to the \p
222/// Buffer that will only be deleted if BeginSourceFile is called.
223std::unique_ptr<CompilerInstance>
224prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
225 const PrecompiledPreamble *Preamble,
226 std::unique_ptr<llvm::MemoryBuffer> Buffer,
227 std::shared_ptr<PCHContainerOperations> PCHs,
228 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
229 DiagnosticConsumer &DiagsClient) {
230 assert(VFS && "VFS is null");
231 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
232 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
233 "of ContentsBuffer");
234
235 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
236 // sure it will be released if no error is emitted.
237 if (Preamble) {
238 Preamble->AddImplicitPreamble(*CI, Buffer.get());
239 } else {
240 CI->getPreprocessorOpts().addRemappedFile(
241 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
242 }
243
244 auto Clang = llvm::make_unique<CompilerInstance>(PCHs);
245 Clang->setInvocation(std::move(CI));
246 Clang->createDiagnostics(&DiagsClient, false);
247
248 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
249 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
250 VFS = VFSWithRemapping;
251 Clang->setVirtualFileSystem(VFS);
252
253 Clang->setTarget(TargetInfo::CreateTargetInfo(
254 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
255 if (!Clang->hasTarget())
256 return nullptr;
257
258 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
259 // release it.
260 Buffer.release();
261 return Clang;
262}
263
Ilya Biryukov02d58702017-08-01 15:51:38 +0000264template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
265 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
266}
267
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268} // namespace
269
Ilya Biryukov38d79772017-05-16 09:38:59 +0000270namespace {
271
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000272CompletionItemKind getKindOfDecl(CXCursorKind CursorKind) {
273 switch (CursorKind) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000274 case CXCursor_MacroInstantiation:
275 case CXCursor_MacroDefinition:
276 return CompletionItemKind::Text;
277 case CXCursor_CXXMethod:
278 return CompletionItemKind::Method;
279 case CXCursor_FunctionDecl:
280 case CXCursor_FunctionTemplate:
281 return CompletionItemKind::Function;
282 case CXCursor_Constructor:
283 case CXCursor_Destructor:
284 return CompletionItemKind::Constructor;
285 case CXCursor_FieldDecl:
286 return CompletionItemKind::Field;
287 case CXCursor_VarDecl:
288 case CXCursor_ParmDecl:
289 return CompletionItemKind::Variable;
290 case CXCursor_ClassDecl:
291 case CXCursor_StructDecl:
292 case CXCursor_UnionDecl:
293 case CXCursor_ClassTemplate:
294 case CXCursor_ClassTemplatePartialSpecialization:
295 return CompletionItemKind::Class;
296 case CXCursor_Namespace:
297 case CXCursor_NamespaceAlias:
298 case CXCursor_NamespaceRef:
299 return CompletionItemKind::Module;
300 case CXCursor_EnumConstantDecl:
301 return CompletionItemKind::Value;
302 case CXCursor_EnumDecl:
303 return CompletionItemKind::Enum;
304 case CXCursor_TypeAliasDecl:
305 case CXCursor_TypeAliasTemplateDecl:
306 case CXCursor_TypedefDecl:
307 case CXCursor_MemberRef:
308 case CXCursor_TypeRef:
309 return CompletionItemKind::Reference;
310 default:
311 return CompletionItemKind::Missing;
312 }
313}
314
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000315CompletionItemKind getKind(CodeCompletionResult::ResultKind ResKind,
316 CXCursorKind CursorKind) {
317 switch (ResKind) {
318 case CodeCompletionResult::RK_Declaration:
319 return getKindOfDecl(CursorKind);
320 case CodeCompletionResult::RK_Keyword:
321 return CompletionItemKind::Keyword;
322 case CodeCompletionResult::RK_Macro:
323 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
324 // completion items in LSP.
325 case CodeCompletionResult::RK_Pattern:
326 return CompletionItemKind::Snippet;
327 }
328 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
329}
330
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000331std::string escapeSnippet(const llvm::StringRef Text) {
332 std::string Result;
333 Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
334 for (const auto Character : Text) {
335 if (Character == '$' || Character == '}' || Character == '\\')
336 Result.push_back('\\');
337 Result.push_back(Character);
338 }
339 return Result;
340}
341
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000342std::string getDocumentation(const CodeCompletionString &CCS) {
343 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
344 // information in the documentation field.
345 std::string Result;
346 const unsigned AnnotationCount = CCS.getAnnotationCount();
347 if (AnnotationCount > 0) {
348 Result += "Annotation";
349 if (AnnotationCount == 1) {
350 Result += ": ";
351 } else /* AnnotationCount > 1 */ {
352 Result += "s: ";
353 }
354 for (unsigned I = 0; I < AnnotationCount; ++I) {
355 Result += CCS.getAnnotation(I);
356 Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
357 }
358 }
359 // Add brief documentation (if there is any).
360 if (CCS.getBriefComment() != nullptr) {
361 if (!Result.empty()) {
362 // This means we previously added annotations. Add an extra newline
363 // character to make the annotations stand out.
364 Result.push_back('\n');
365 }
366 Result += CCS.getBriefComment();
367 }
368 return Result;
369}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000370
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) {
439 Candidates.emplace(Results[I]);
440 if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
441 Candidates.pop();
442 Items.isIncomplete = true;
443 }
444 }
445 while (!Candidates.empty()) {
446 auto &Candidate = Candidates.top();
447 const auto *CCS = Candidate.Result->CreateCodeCompletionString(
448 S, Context, *Allocator, CCTUInfo,
449 CodeCompleteOpts.IncludeBriefComments);
450 assert(CCS && "Expected the CodeCompletionString to be non-null");
451 Items.items.push_back(ProcessCodeCompleteResult(Candidate, *CCS));
452 Candidates.pop();
453 }
454 std::reverse(Items.items.begin(), Items.items.end());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000455 }
456
Sam McCalla40371b2017-11-15 09:16:29 +0000457 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
458
459 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
460
461private:
462 CompletionItem
463 ProcessCodeCompleteResult(const CompletionCandidate &Candidate,
464 const CodeCompletionString &CCS) const {
465
466 // Adjust this to InsertTextFormat::Snippet iff we encounter a
467 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
468 CompletionItem Item;
469 Item.insertTextFormat = InsertTextFormat::PlainText;
470
471 Item.documentation = getDocumentation(CCS);
472 Item.sortText = Candidate.sortText();
473
474 // Fill in the label, detail, insertText and filterText fields of the
475 // CompletionItem.
476 ProcessChunks(CCS, Item);
477
478 // Fill in the kind field of the CompletionItem.
479 Item.kind = getKind(Candidate.Result->Kind, Candidate.Result->CursorKind);
480
481 return Item;
482 }
483
484 virtual void ProcessChunks(const CodeCompletionString &CCS,
485 CompletionItem &Item) const = 0;
486
487 clangd::CodeCompleteOptions ClangdOpts;
488 CompletionList &Items;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000489 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
490 CodeCompletionTUInfo CCTUInfo;
491
492}; // CompletionItemsCollector
493
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000494bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
495 return Chunk.Kind == CodeCompletionString::CK_Informative &&
496 StringRef(Chunk.Text).endswith("::");
497}
498
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000499class PlainTextCompletionItemsCollector final
500 : public CompletionItemsCollector {
501
502public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000503 PlainTextCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000504 const clangd::CodeCompleteOptions &CodeCompleteOpts,
505 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000506 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
507
508private:
509 void ProcessChunks(const CodeCompletionString &CCS,
510 CompletionItem &Item) const override {
511 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000512 // Informative qualifier chunks only clutter completion results, skip
513 // them.
514 if (isInformativeQualifierChunk(Chunk))
515 continue;
516
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000517 switch (Chunk.Kind) {
518 case CodeCompletionString::CK_TypedText:
519 // There's always exactly one CK_TypedText chunk.
520 Item.insertText = Item.filterText = Chunk.Text;
521 Item.label += Chunk.Text;
522 break;
523 case CodeCompletionString::CK_ResultType:
524 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
525 Item.detail = Chunk.Text;
526 break;
527 case CodeCompletionString::CK_Optional:
528 break;
529 default:
530 Item.label += Chunk.Text;
531 break;
532 }
533 }
534 }
535}; // PlainTextCompletionItemsCollector
536
537class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
538
539public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000540 SnippetCompletionItemsCollector(
Sam McCalla40371b2017-11-15 09:16:29 +0000541 const clangd::CodeCompleteOptions &CodeCompleteOpts,
542 CompletionList &Items)
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000543 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
544
545private:
546 void ProcessChunks(const CodeCompletionString &CCS,
547 CompletionItem &Item) const override {
548 unsigned ArgCount = 0;
549 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000550 // Informative qualifier chunks only clutter completion results, skip
551 // them.
552 if (isInformativeQualifierChunk(Chunk))
553 continue;
554
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000555 switch (Chunk.Kind) {
556 case CodeCompletionString::CK_TypedText:
557 // The piece of text that the user is expected to type to match
558 // the code-completion string, typically a keyword or the name of
559 // a declarator or macro.
560 Item.filterText = Chunk.Text;
Simon Pilgrim948c0bc2017-11-01 09:22:03 +0000561 LLVM_FALLTHROUGH;
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000562 case CodeCompletionString::CK_Text:
563 // A piece of text that should be placed in the buffer,
564 // e.g., parentheses or a comma in a function call.
565 Item.label += Chunk.Text;
566 Item.insertText += Chunk.Text;
567 break;
568 case CodeCompletionString::CK_Optional:
569 // A code completion string that is entirely optional.
570 // For example, an optional code completion string that
571 // describes the default arguments in a function call.
572
573 // FIXME: Maybe add an option to allow presenting the optional chunks?
574 break;
575 case CodeCompletionString::CK_Placeholder:
576 // A string that acts as a placeholder for, e.g., a function call
577 // argument.
578 ++ArgCount;
579 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
580 escapeSnippet(Chunk.Text) + '}';
581 Item.label += Chunk.Text;
582 Item.insertTextFormat = InsertTextFormat::Snippet;
583 break;
584 case CodeCompletionString::CK_Informative:
585 // A piece of text that describes something about the result
586 // but should not be inserted into the buffer.
587 // For example, the word "const" for a const method, or the name of
588 // the base class for methods that are part of the base class.
589 Item.label += Chunk.Text;
590 // Don't put the informative chunks in the insertText.
591 break;
592 case CodeCompletionString::CK_ResultType:
593 // A piece of text that describes the type of an entity or,
594 // for functions and methods, the return type.
595 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
596 Item.detail = Chunk.Text;
597 break;
598 case CodeCompletionString::CK_CurrentParameter:
599 // A piece of text that describes the parameter that corresponds to
600 // the code-completion location within a function call, message send,
601 // macro invocation, etc.
602 //
603 // This should never be present while collecting completion items,
604 // only while collecting overload candidates.
605 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
606 "CompletionItems");
607 break;
608 case CodeCompletionString::CK_LeftParen:
609 // A left parenthesis ('(').
610 case CodeCompletionString::CK_RightParen:
611 // A right parenthesis (')').
612 case CodeCompletionString::CK_LeftBracket:
613 // A left bracket ('[').
614 case CodeCompletionString::CK_RightBracket:
615 // A right bracket (']').
616 case CodeCompletionString::CK_LeftBrace:
617 // A left brace ('{').
618 case CodeCompletionString::CK_RightBrace:
619 // A right brace ('}').
620 case CodeCompletionString::CK_LeftAngle:
621 // A left angle bracket ('<').
622 case CodeCompletionString::CK_RightAngle:
623 // A right angle bracket ('>').
624 case CodeCompletionString::CK_Comma:
625 // A comma separator (',').
626 case CodeCompletionString::CK_Colon:
627 // A colon (':').
628 case CodeCompletionString::CK_SemiColon:
629 // A semicolon (';').
630 case CodeCompletionString::CK_Equal:
631 // An '=' sign.
632 case CodeCompletionString::CK_HorizontalSpace:
633 // Horizontal whitespace (' ').
634 Item.insertText += Chunk.Text;
635 Item.label += Chunk.Text;
636 break;
637 case CodeCompletionString::CK_VerticalSpace:
638 // Vertical whitespace ('\n' or '\r\n', depending on the
639 // platform).
640 Item.insertText += Chunk.Text;
641 // Don't even add a space to the label.
642 break;
643 }
644 }
645 }
646}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000647
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000648class SignatureHelpCollector final : public CodeCompleteConsumer {
649
650public:
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000651 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000652 SignatureHelp &SigHelp)
653 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
654 SigHelp(SigHelp),
655 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
656 CCTUInfo(Allocator) {}
657
658 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
659 OverloadCandidate *Candidates,
660 unsigned NumCandidates) override {
661 SigHelp.signatures.reserve(NumCandidates);
662 // FIXME(rwols): How can we determine the "active overload candidate"?
663 // Right now the overloaded candidates seem to be provided in a "best fit"
664 // order, so I'm not too worried about this.
665 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000666 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000667 "too many arguments");
668 SigHelp.activeParameter = static_cast<int>(CurrentArg);
669 for (unsigned I = 0; I < NumCandidates; ++I) {
670 const auto &Candidate = Candidates[I];
671 const auto *CCS = Candidate.CreateSignatureString(
672 CurrentArg, S, *Allocator, CCTUInfo, true);
673 assert(CCS && "Expected the CodeCompletionString to be non-null");
674 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
675 }
676 }
677
678 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
679
680 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
681
682private:
683 SignatureInformation
684 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
685 const CodeCompletionString &CCS) const {
686 SignatureInformation Result;
687 const char *ReturnType = nullptr;
688
689 Result.documentation = getDocumentation(CCS);
690
691 for (const auto &Chunk : CCS) {
692 switch (Chunk.Kind) {
693 case CodeCompletionString::CK_ResultType:
694 // A piece of text that describes the type of an entity or,
695 // for functions and methods, the return type.
696 assert(!ReturnType && "Unexpected CK_ResultType");
697 ReturnType = Chunk.Text;
698 break;
699 case CodeCompletionString::CK_Placeholder:
700 // A string that acts as a placeholder for, e.g., a function call
701 // argument.
702 // Intentional fallthrough here.
703 case CodeCompletionString::CK_CurrentParameter: {
704 // A piece of text that describes the parameter that corresponds to
705 // the code-completion location within a function call, message send,
706 // macro invocation, etc.
707 Result.label += Chunk.Text;
708 ParameterInformation Info;
709 Info.label = Chunk.Text;
710 Result.parameters.push_back(std::move(Info));
711 break;
712 }
713 case CodeCompletionString::CK_Optional: {
714 // The rest of the parameters are defaulted/optional.
715 assert(Chunk.Optional &&
716 "Expected the optional code completion string to be non-null.");
717 Result.label +=
718 getOptionalParameters(*Chunk.Optional, Result.parameters);
719 break;
720 }
721 case CodeCompletionString::CK_VerticalSpace:
722 break;
723 default:
724 Result.label += Chunk.Text;
725 break;
726 }
727 }
728 if (ReturnType) {
729 Result.label += " -> ";
730 Result.label += ReturnType;
731 }
732 return Result;
733 }
734
735 SignatureHelp &SigHelp;
736 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
737 CodeCompletionTUInfo CCTUInfo;
738
739}; // SignatureHelpCollector
740
741bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000742 const clang::CodeCompleteOptions &Options,
743 PathRef FileName,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000744 const tooling::CompileCommand &Command,
745 PrecompiledPreamble const *Preamble, StringRef Contents,
746 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
747 std::shared_ptr<PCHContainerOperations> PCHs,
748 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000749 std::vector<const char *> ArgStrs;
750 for (const auto &S : Command.CommandLine)
751 ArgStrs.push_back(S.c_str());
752
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000753 VFS->setCurrentWorkingDirectory(Command.Directory);
754
Ilya Biryukov04db3682017-07-21 13:29:29 +0000755 std::unique_ptr<CompilerInvocation> CI;
756 EmptyDiagsConsumer DummyDiagsConsumer;
757 {
758 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
759 CompilerInstance::createDiagnostics(new DiagnosticOptions,
760 &DummyDiagsConsumer, false);
761 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
762 }
763 assert(CI && "Couldn't create CompilerInvocation");
764
765 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
766 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
767
768 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000769 if (Preamble) {
770 auto Bounds =
771 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000772 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
773 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000774 }
775
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000776 auto Clang = prepareCompilerInstance(
777 std::move(CI), Preamble, std::move(ContentsBuffer), std::move(PCHs),
778 std::move(VFS), DummyDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000779 auto &DiagOpts = Clang->getDiagnosticOpts();
780 DiagOpts.IgnoreWarnings = true;
781
782 auto &FrontendOpts = Clang->getFrontendOpts();
783 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000784 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000785 FrontendOpts.CodeCompletionAt.FileName = FileName;
786 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
787 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
788
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000789 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000790
Ilya Biryukov04db3682017-07-21 13:29:29 +0000791 SyntaxOnlyAction Action;
792 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000793 Logger.log("BeginSourceFile() failed when running codeComplete for " +
794 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000795 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000796 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000797 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000798 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000799 return false;
800 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000801
Ilya Biryukov04db3682017-07-21 13:29:29 +0000802 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000803
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000804 return true;
805}
806
807} // namespace
808
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000809clangd::CodeCompleteOptions::CodeCompleteOptions(
810 bool EnableSnippetsAndCodePatterns)
811 : CodeCompleteOptions() {
812 EnableSnippets = EnableSnippetsAndCodePatterns;
813 IncludeCodePatterns = EnableSnippetsAndCodePatterns;
814}
815
816clangd::CodeCompleteOptions::CodeCompleteOptions(bool EnableSnippets,
817 bool IncludeCodePatterns,
818 bool IncludeMacros,
819 bool IncludeGlobals,
820 bool IncludeBriefComments)
821 : EnableSnippets(EnableSnippets), IncludeCodePatterns(IncludeCodePatterns),
822 IncludeMacros(IncludeMacros), IncludeGlobals(IncludeGlobals),
823 IncludeBriefComments(IncludeBriefComments) {}
824
Sam McCalla40371b2017-11-15 09:16:29 +0000825clang::CodeCompleteOptions
826clangd::CodeCompleteOptions::getClangCompleteOpts() const {
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000827 clang::CodeCompleteOptions Result;
828 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
829 Result.IncludeMacros = IncludeMacros;
830 Result.IncludeGlobals = IncludeGlobals;
831 Result.IncludeBriefComments = IncludeBriefComments;
832
833 return Result;
834}
835
Sam McCalla40371b2017-11-15 09:16:29 +0000836CompletionList
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000837clangd::codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000838 PrecompiledPreamble const *Preamble, StringRef Contents,
839 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
840 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000841 clangd::CodeCompleteOptions Opts, clangd::Logger &Logger) {
Sam McCalla40371b2017-11-15 09:16:29 +0000842 CompletionList Results;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000843 std::unique_ptr<CodeCompleteConsumer> Consumer;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000844 if (Opts.EnableSnippets) {
Sam McCalla40371b2017-11-15 09:16:29 +0000845 Consumer =
846 llvm::make_unique<SnippetCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000847 } else {
Sam McCalla40371b2017-11-15 09:16:29 +0000848 Consumer =
849 llvm::make_unique<PlainTextCompletionItemsCollector>(Opts, Results);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000850 }
Sam McCalla40371b2017-11-15 09:16:29 +0000851 invokeCodeComplete(std::move(Consumer), Opts.getClangCompleteOpts(), FileName,
852 Command, Preamble, Contents, Pos, std::move(VFS),
853 std::move(PCHs), Logger);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000854 return Results;
855}
856
857SignatureHelp
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000858clangd::signatureHelp(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000859 PrecompiledPreamble const *Preamble, StringRef Contents,
860 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
861 std::shared_ptr<PCHContainerOperations> PCHs,
862 clangd::Logger &Logger) {
863 SignatureHelp Result;
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000864 clang::CodeCompleteOptions Options;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000865 Options.IncludeGlobals = false;
866 Options.IncludeMacros = false;
867 Options.IncludeCodePatterns = false;
868 Options.IncludeBriefComments = true;
869 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
870 Options, FileName, Command, Preamble, Contents, Pos,
871 std::move(VFS), std::move(PCHs), Logger);
872 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000873}
874
Ilya Biryukov02d58702017-08-01 15:51:38 +0000875void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
876 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000877}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000878
Ilya Biryukov02d58702017-08-01 15:51:38 +0000879llvm::Optional<ParsedAST>
880ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
881 const PrecompiledPreamble *Preamble,
882 ArrayRef<serialization::DeclID> PreambleDeclIDs,
883 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
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000891 auto Clang = prepareCompilerInstance(
892 std::move(CI), Preamble, std::move(Buffer), std::move(PCHs),
893 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000894
895 // Recover resources if we crash before exiting this method.
896 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
897 Clang.get());
898
899 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000900 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
901 if (!Action->BeginSourceFile(*Clang, MainInput)) {
902 Logger.log("BeginSourceFile() failed when building AST for " +
903 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000904 return llvm::None;
905 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000906 if (!Action->Execute())
907 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000908
909 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
910 // has a longer lifetime.
911 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
912
913 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
914 std::vector<serialization::DeclID> PendingDecls;
915 if (Preamble) {
916 PendingDecls.reserve(PreambleDeclIDs.size());
917 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
918 PreambleDeclIDs.end());
919 }
920
921 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
922 std::move(PendingDecls), std::move(ASTDiags));
923}
924
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000925namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000926
927SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
928 const FileEntry *FE,
929 unsigned Offset) {
930 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
931 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
932}
933
934SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
935 const FileEntry *FE, Position Pos) {
936 SourceLocation InputLoc =
937 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
938 return Mgr.getMacroArgExpandedLocation(InputLoc);
939}
940
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000941/// Finds declarations locations that a given source location refers to.
942class DeclarationLocationsFinder : public index::IndexDataConsumer {
943 std::vector<Location> DeclarationLocations;
944 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000945 const ASTContext &AST;
946 Preprocessor &PP;
947
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000948public:
949 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000950 const SourceLocation &SearchedLocation,
951 ASTContext &AST, Preprocessor &PP)
952 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000953
954 std::vector<Location> takeLocations() {
955 // Don't keep the same location multiple times.
956 // This can happen when nodes in the AST are visited twice.
957 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000958 auto last =
959 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000960 DeclarationLocations.erase(last, DeclarationLocations.end());
961 return std::move(DeclarationLocations);
962 }
963
Ilya Biryukov02d58702017-08-01 15:51:38 +0000964 bool
965 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
966 ArrayRef<index::SymbolRelation> Relations, FileID FID,
967 unsigned Offset,
968 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000969 if (isSearchedLocation(FID, Offset)) {
970 addDeclarationLocation(D->getSourceRange());
971 }
972 return true;
973 }
974
975private:
976 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000977 const SourceManager &SourceMgr = AST.getSourceManager();
978 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
979 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000980 }
981
Ilya Biryukov04db3682017-07-21 13:29:29 +0000982 void addDeclarationLocation(const SourceRange &ValSourceRange) {
983 const SourceManager &SourceMgr = AST.getSourceManager();
984 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000985 SourceLocation LocStart = ValSourceRange.getBegin();
986 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000987 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000988 Position Begin;
989 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
990 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
991 Position End;
992 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
993 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
994 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000995 Location L;
Marc-Andre Laperleba070102017-11-07 16:16:45 +0000996 if (const FileEntry *F =
997 SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) {
998 StringRef FilePath = F->tryGetRealPathName();
999 if (FilePath.empty())
1000 FilePath = F->getName();
1001 L.uri = URI::fromFile(FilePath);
1002 L.range = R;
1003 DeclarationLocations.push_back(L);
1004 }
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001005 }
1006
Kirill Bobyrev46213872017-06-28 20:57:28 +00001007 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001008 // Also handle possible macro at the searched location.
1009 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001010 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
1011 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001012 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001013 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001014 }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001015 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001016 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
1017 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001018 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001019 // Get the definition just before the searched location so that a macro
1020 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +00001021 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
1022 AST.getSourceManager(),
1023 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001024 DecLoc.second - 1);
1025 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +00001026 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
1027 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001028 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001029 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
1030 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001031 }
1032 }
1033 }
1034 }
1035};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001036
Ilya Biryukov02d58702017-08-01 15:51:38 +00001037} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001038
Ilya Biryukove5128f72017-09-20 07:24:15 +00001039std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1040 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001041 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1042 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1043 if (!FE)
1044 return {};
1045
1046 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1047
1048 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1049 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1050 AST.getPreprocessor());
1051 index::IndexingOptions IndexOpts;
1052 IndexOpts.SystemSymbolFilter =
1053 index::IndexingOptions::SystemSymbolFilterKind::All;
1054 IndexOpts.IndexFunctionLocals = true;
1055
1056 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1057 DeclLocationsFinder, IndexOpts);
1058
1059 return DeclLocationsFinder->takeLocations();
1060}
1061
1062void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001063 if (PendingTopLevelDecls.empty())
1064 return;
1065
1066 std::vector<const Decl *> Resolved;
1067 Resolved.reserve(PendingTopLevelDecls.size());
1068
1069 ExternalASTSource &Source = *getASTContext().getExternalSource();
1070 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
1071 // Resolve the declaration ID to an actual declaration, possibly
1072 // deserializing the declaration in the process.
1073 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1074 Resolved.push_back(D);
1075 }
1076
1077 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
1078 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1079
1080 PendingTopLevelDecls.clear();
1081}
1082
Ilya Biryukov02d58702017-08-01 15:51:38 +00001083ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001084
Ilya Biryukov02d58702017-08-01 15:51:38 +00001085ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001086
Ilya Biryukov02d58702017-08-01 15:51:38 +00001087ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001088 if (Action) {
1089 Action->EndSourceFile();
1090 }
1091}
1092
Ilya Biryukov02d58702017-08-01 15:51:38 +00001093ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1094
1095const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001096 return Clang->getASTContext();
1097}
1098
Ilya Biryukov02d58702017-08-01 15:51:38 +00001099Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001100
Ilya Biryukov02d58702017-08-01 15:51:38 +00001101const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001102 return Clang->getPreprocessor();
1103}
1104
Ilya Biryukov02d58702017-08-01 15:51:38 +00001105ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001106 ensurePreambleDeclsDeserialized();
1107 return TopLevelDecls;
1108}
1109
Ilya Biryukov02d58702017-08-01 15:51:38 +00001110const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001111 return Diags;
1112}
1113
Ilya Biryukov02d58702017-08-01 15:51:38 +00001114ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
1115 std::unique_ptr<FrontendAction> Action,
1116 std::vector<const Decl *> TopLevelDecls,
1117 std::vector<serialization::DeclID> PendingTopLevelDecls,
1118 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001119 : Clang(std::move(Clang)), Action(std::move(Action)),
1120 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
1121 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
1122 assert(this->Clang);
1123 assert(this->Action);
1124}
1125
Ilya Biryukov02d58702017-08-01 15:51:38 +00001126ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1127 : AST(std::move(Wrapper.AST)) {}
1128
1129ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1130 : AST(std::move(AST)) {}
1131
1132PreambleData::PreambleData(PrecompiledPreamble Preamble,
1133 std::vector<serialization::DeclID> TopLevelDeclIDs,
1134 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001135 : Preamble(std::move(Preamble)),
1136 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001137
1138std::shared_ptr<CppFile>
1139CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001140 std::shared_ptr<PCHContainerOperations> PCHs,
1141 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001142 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +00001143 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001144}
1145
1146CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001147 std::shared_ptr<PCHContainerOperations> PCHs,
1148 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +00001149 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001150 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001151
1152 std::lock_guard<std::mutex> Lock(Mutex);
1153 LatestAvailablePreamble = nullptr;
1154 PreamblePromise.set_value(nullptr);
1155 PreambleFuture = PreamblePromise.get_future();
1156
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001157 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001158 ASTFuture = ASTPromise.get_future();
1159}
1160
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001161void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001162
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001163UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001164 std::unique_lock<std::mutex> Lock(Mutex);
1165 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001166 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001167 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1168 // We want to keep this invariant.
1169 if (futureIsReady(PreambleFuture)) {
1170 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1171 PreambleFuture = PreamblePromise.get_future();
1172 }
1173 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001174 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001175 ASTFuture = ASTPromise.get_future();
1176 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001177
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001178 Lock.unlock();
1179 // Notify about changes to RebuildCounter.
1180 RebuildCond.notify_all();
1181
1182 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001183 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001184 std::unique_lock<std::mutex> Lock(That->Mutex);
1185 CppFile *This = &*That;
1186 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1187 return !This->RebuildInProgress ||
1188 This->RebuildCounter != RequestRebuildCounter;
1189 });
1190
1191 // This computation got cancelled itself, do nothing.
1192 if (This->RebuildCounter != RequestRebuildCounter)
1193 return;
1194
1195 // Set empty results for Promises.
1196 That->PreamblePromise.set_value(nullptr);
1197 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001198 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001199}
1200
1201llvm::Optional<std::vector<DiagWithFixIts>>
1202CppFile::rebuild(StringRef NewContents,
1203 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001204 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001205}
1206
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001207UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001208CppFile::deferRebuild(StringRef NewContents,
1209 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1210 std::shared_ptr<const PreambleData> OldPreamble;
1211 std::shared_ptr<PCHContainerOperations> PCHs;
1212 unsigned RequestRebuildCounter;
1213 {
1214 std::unique_lock<std::mutex> Lock(Mutex);
1215 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1216 // They will try to exit as early as possible and won't call set_value on
1217 // our promises.
1218 RequestRebuildCounter = ++this->RebuildCounter;
1219 PCHs = this->PCHs;
1220
1221 // Remember the preamble to be used during rebuild.
1222 OldPreamble = this->LatestAvailablePreamble;
1223 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1224 // futures will wait until the rebuild process is finished.
1225 if (futureIsReady(this->PreambleFuture)) {
1226 this->PreamblePromise =
1227 std::promise<std::shared_ptr<const PreambleData>>();
1228 this->PreambleFuture = this->PreamblePromise.get_future();
1229 }
1230 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001231 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001232 this->ASTFuture = this->ASTPromise.get_future();
1233 }
1234 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001235 // Notify about changes to RebuildCounter.
1236 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001237
1238 // A helper to function to finish the rebuild. May be run on a different
1239 // thread.
1240
1241 // Don't let this CppFile die before rebuild is finished.
1242 std::shared_ptr<CppFile> That = shared_from_this();
1243 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1244 That](std::string NewContents)
1245 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1246 // Only one execution of this method is possible at a time.
1247 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1248 // into a state for doing a rebuild.
1249 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1250 if (Rebuild.wasCancelledBeforeConstruction())
1251 return llvm::None;
1252
1253 std::vector<const char *> ArgStrs;
1254 for (const auto &S : That->Command.CommandLine)
1255 ArgStrs.push_back(S.c_str());
1256
1257 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1258
1259 std::unique_ptr<CompilerInvocation> CI;
1260 {
1261 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1262 // reporting them.
1263 EmptyDiagsConsumer CommandLineDiagsConsumer;
1264 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1265 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1266 &CommandLineDiagsConsumer, false);
1267 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1268 }
1269 assert(CI && "Couldn't create CompilerInvocation");
1270
1271 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1272 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1273
1274 // A helper function to rebuild the preamble or reuse the existing one. Does
1275 // not mutate any fields, only does the actual computation.
1276 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1277 auto Bounds =
1278 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1279 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1280 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1281 return OldPreamble;
1282 }
1283
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,
1293 SerializedDeclsCollector);
1294
1295 if (BuiltPreamble) {
1296 return std::make_shared<PreambleData>(
1297 std::move(*BuiltPreamble),
1298 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1299 std::move(PreambleDiags));
1300 } else {
1301 return nullptr;
1302 }
1303 };
1304
1305 // Compute updated Preamble.
1306 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1307 // Publish the new Preamble.
1308 {
1309 std::lock_guard<std::mutex> Lock(That->Mutex);
1310 // We always set LatestAvailablePreamble to the new value, hoping that it
1311 // will still be usable in the further requests.
1312 That->LatestAvailablePreamble = NewPreamble;
1313 if (RequestRebuildCounter != That->RebuildCounter)
1314 return llvm::None; // Our rebuild request was cancelled, do nothing.
1315 That->PreamblePromise.set_value(NewPreamble);
1316 } // unlock Mutex
1317
1318 // Prepare the Preamble and supplementary data for rebuilding AST.
1319 const PrecompiledPreamble *PreambleForAST = nullptr;
1320 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1321 std::vector<DiagWithFixIts> Diagnostics;
1322 if (NewPreamble) {
1323 PreambleForAST = &NewPreamble->Preamble;
1324 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1325 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1326 NewPreamble->Diags.end());
1327 }
1328
1329 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +00001330 llvm::Optional<ParsedAST> NewAST;
1331 {
1332 trace::Span Tracer(llvm::Twine("Build: ") + That->FileName);
1333 NewAST = ParsedAST::Build(
1334 std::move(CI), PreambleForAST, SerializedPreambleDecls,
1335 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
1336 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001337
1338 if (NewAST) {
1339 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1340 NewAST->getDiagnostics().end());
1341 } else {
1342 // Don't report even Preamble diagnostics if we coulnd't build AST.
1343 Diagnostics.clear();
1344 }
1345
1346 // Publish the new AST.
1347 {
1348 std::lock_guard<std::mutex> Lock(That->Mutex);
1349 if (RequestRebuildCounter != That->RebuildCounter)
1350 return Diagnostics; // Our rebuild request was cancelled, don't set
1351 // ASTPromise.
1352
Ilya Biryukov574b7532017-08-02 09:08:39 +00001353 That->ASTPromise.set_value(
1354 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001355 } // unlock Mutex
1356
1357 return Diagnostics;
1358 };
1359
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001360 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001361}
1362
1363std::shared_future<std::shared_ptr<const PreambleData>>
1364CppFile::getPreamble() const {
1365 std::lock_guard<std::mutex> Lock(Mutex);
1366 return PreambleFuture;
1367}
1368
1369std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1370 std::lock_guard<std::mutex> Lock(Mutex);
1371 return LatestAvailablePreamble;
1372}
1373
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001374std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001375 std::lock_guard<std::mutex> Lock(Mutex);
1376 return ASTFuture;
1377}
1378
1379tooling::CompileCommand const &CppFile::getCompileCommand() const {
1380 return Command;
1381}
1382
1383CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1384 unsigned RequestRebuildCounter)
1385 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1386 std::unique_lock<std::mutex> Lock(File.Mutex);
1387 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1388 if (WasCancelledBeforeConstruction)
1389 return;
1390
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001391 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1392 return !File.RebuildInProgress ||
1393 File.RebuildCounter != RequestRebuildCounter;
1394 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001395
1396 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1397 if (WasCancelledBeforeConstruction)
1398 return;
1399
1400 File.RebuildInProgress = true;
1401}
1402
1403bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1404 return WasCancelledBeforeConstruction;
1405}
1406
1407CppFile::RebuildGuard::~RebuildGuard() {
1408 if (WasCancelledBeforeConstruction)
1409 return;
1410
1411 std::unique_lock<std::mutex> Lock(File.Mutex);
1412 assert(File.RebuildInProgress);
1413 File.RebuildInProgress = false;
1414
1415 if (File.RebuildCounter == RequestRebuildCounter) {
1416 // Our rebuild request was successful.
1417 assert(futureIsReady(File.ASTFuture));
1418 assert(futureIsReady(File.PreambleFuture));
1419 } else {
1420 // Our rebuild request was cancelled, because further reparse was requested.
1421 assert(!futureIsReady(File.ASTFuture));
1422 assert(!futureIsReady(File.PreambleFuture));
1423 }
1424
1425 Lock.unlock();
1426 File.RebuildCond.notify_all();
1427}
Haojian Wu345099c2017-11-09 11:30:04 +00001428
1429SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
1430 const Position &Pos,
1431 const FileEntry *FE) {
1432 // The language server protocol uses zero-based line and column numbers.
1433 // Clang uses one-based numbers.
1434
1435 const ASTContext &AST = Unit.getASTContext();
1436 const SourceManager &SourceMgr = AST.getSourceManager();
1437
1438 SourceLocation InputLocation =
1439 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
1440 if (Pos.character == 0) {
1441 return InputLocation;
1442 }
1443
1444 // This handle cases where the position is in the middle of a token or right
1445 // after the end of a token. In theory we could just use GetBeginningOfToken
1446 // to find the start of the token at the input position, but this doesn't
1447 // work when right after the end, i.e. foo|.
1448 // So try to go back by one and see if we're still inside the an identifier
1449 // token. If so, Take the beginning of this token.
1450 // (It should be the same identifier because you can't have two adjacent
1451 // identifiers without another token in between.)
1452 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
1453 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
1454 Token Result;
1455 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
1456 AST.getLangOpts(), false)) {
1457 // getRawToken failed, just use InputLocation.
1458 return InputLocation;
1459 }
1460
1461 if (Result.is(tok::raw_identifier)) {
1462 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
1463 AST.getLangOpts());
1464 }
1465
1466 return InputLocation;
1467}