blob: a476eeb72e283c9cef69730f2b019aecf7cfe3e4 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9
10#include "ClangdUnit.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000011
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000015#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000016#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000017#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000018#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000019#include "clang/Lex/Lexer.h"
20#include "clang/Lex/MacroInfo.h"
21#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000022#include "clang/Lex/PreprocessorOptions.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000029#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000030
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000031#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000032#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000033
Ilya Biryukov38d79772017-05-16 09:38:59 +000034using namespace clang::clangd;
35using namespace clang;
36
Ilya Biryukov04db3682017-07-21 13:29:29 +000037namespace {
38
39class DeclTrackingASTConsumer : public ASTConsumer {
40public:
41 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
42 : TopLevelDecls(TopLevelDecls) {}
43
44 bool HandleTopLevelDecl(DeclGroupRef DG) override {
45 for (const Decl *D : DG) {
46 // ObjCMethodDecl are not actually top-level decls.
47 if (isa<ObjCMethodDecl>(D))
48 continue;
49
50 TopLevelDecls.push_back(D);
51 }
52 return true;
53 }
54
55private:
56 std::vector<const Decl *> &TopLevelDecls;
57};
58
59class ClangdFrontendAction : public SyntaxOnlyAction {
60public:
61 std::vector<const Decl *> takeTopLevelDecls() {
62 return std::move(TopLevelDecls);
63 }
64
65protected:
66 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
67 StringRef InFile) override {
68 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
69 }
70
71private:
72 std::vector<const Decl *> TopLevelDecls;
73};
74
Ilya Biryukov02d58702017-08-01 15:51:38 +000075class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000076public:
77 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
78 return std::move(TopLevelDeclIDs);
79 }
80
81 void AfterPCHEmitted(ASTWriter &Writer) override {
82 TopLevelDeclIDs.reserve(TopLevelDecls.size());
83 for (Decl *D : TopLevelDecls) {
84 // Invalid top-level decls may not have been serialized.
85 if (D->isInvalidDecl())
86 continue;
87 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
88 }
89 }
90
91 void HandleTopLevelDecl(DeclGroupRef DG) override {
92 for (Decl *D : DG) {
93 if (isa<ObjCMethodDecl>(D))
94 continue;
95 TopLevelDecls.push_back(D);
96 }
97 }
98
99private:
100 std::vector<Decl *> TopLevelDecls;
101 std::vector<serialization::DeclID> TopLevelDeclIDs;
102};
103
104/// Convert from clang diagnostic level to LSP severity.
105static int getSeverity(DiagnosticsEngine::Level L) {
106 switch (L) {
107 case DiagnosticsEngine::Remark:
108 return 4;
109 case DiagnosticsEngine::Note:
110 return 3;
111 case DiagnosticsEngine::Warning:
112 return 2;
113 case DiagnosticsEngine::Fatal:
114 case DiagnosticsEngine::Error:
115 return 1;
116 case DiagnosticsEngine::Ignored:
117 return 0;
118 }
119 llvm_unreachable("Unknown diagnostic level!");
120}
121
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000122/// Get the optional chunk as a string. This function is possibly recursive.
123///
124/// The parameter info for each parameter is appended to the Parameters.
125std::string
126getOptionalParameters(const CodeCompletionString &CCS,
127 std::vector<ParameterInformation> &Parameters) {
128 std::string Result;
129 for (const auto &Chunk : CCS) {
130 switch (Chunk.Kind) {
131 case CodeCompletionString::CK_Optional:
132 assert(Chunk.Optional &&
133 "Expected the optional code completion string to be non-null.");
134 Result += getOptionalParameters(*Chunk.Optional, Parameters);
135 break;
136 case CodeCompletionString::CK_VerticalSpace:
137 break;
138 case CodeCompletionString::CK_Placeholder:
139 // A string that acts as a placeholder for, e.g., a function call
140 // argument.
141 // Intentional fallthrough here.
142 case CodeCompletionString::CK_CurrentParameter: {
143 // A piece of text that describes the parameter that corresponds to
144 // the code-completion location within a function call, message send,
145 // macro invocation, etc.
146 Result += Chunk.Text;
147 ParameterInformation Info;
148 Info.label = Chunk.Text;
149 Parameters.push_back(std::move(Info));
150 break;
151 }
152 default:
153 Result += Chunk.Text;
154 break;
155 }
156 }
157 return Result;
158}
159
Ilya Biryukov04db3682017-07-21 13:29:29 +0000160llvm::Optional<DiagWithFixIts> toClangdDiag(StoredDiagnostic D) {
161 auto Location = D.getLocation();
162 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
163 return llvm::None;
164
165 Position P;
166 P.line = Location.getSpellingLineNumber() - 1;
167 P.character = Location.getSpellingColumnNumber();
168 Range R = {P, P};
169 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
170
171 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
172 for (const FixItHint &Fix : D.getFixIts()) {
173 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
174 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
175 }
176 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
177}
178
179class StoreDiagsConsumer : public DiagnosticConsumer {
180public:
181 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
182
183 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
184 const clang::Diagnostic &Info) override {
185 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
186
187 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
188 Output.push_back(std::move(*convertedDiag));
189 }
190
191private:
192 std::vector<DiagWithFixIts> &Output;
193};
194
195class EmptyDiagsConsumer : public DiagnosticConsumer {
196public:
197 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
198 const clang::Diagnostic &Info) override {}
199};
200
201std::unique_ptr<CompilerInvocation>
202createCompilerInvocation(ArrayRef<const char *> ArgList,
203 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
204 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
205 auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags),
206 std::move(VFS));
207 // We rely on CompilerInstance to manage the resource (i.e. free them on
208 // EndSourceFile), but that won't happen if DisableFree is set to true.
209 // Since createInvocationFromCommandLine sets it to true, we have to override
210 // it.
211 CI->getFrontendOpts().DisableFree = false;
212 return CI;
213}
214
215/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
216/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
217/// null. Note that vfs::FileSystem inside returned instance may differ from \p
218/// VFS if additional file remapping were set in command-line arguments.
219/// On some errors, returns null. When non-null value is returned, it's expected
220/// to be consumed by the FrontendAction as it will have a pointer to the \p
221/// Buffer that will only be deleted if BeginSourceFile is called.
222std::unique_ptr<CompilerInstance>
223prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
224 const PrecompiledPreamble *Preamble,
225 std::unique_ptr<llvm::MemoryBuffer> Buffer,
226 std::shared_ptr<PCHContainerOperations> PCHs,
227 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
228 DiagnosticConsumer &DiagsClient) {
229 assert(VFS && "VFS is null");
230 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
231 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
232 "of ContentsBuffer");
233
234 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
235 // sure it will be released if no error is emitted.
236 if (Preamble) {
237 Preamble->AddImplicitPreamble(*CI, Buffer.get());
238 } else {
239 CI->getPreprocessorOpts().addRemappedFile(
240 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
241 }
242
243 auto Clang = llvm::make_unique<CompilerInstance>(PCHs);
244 Clang->setInvocation(std::move(CI));
245 Clang->createDiagnostics(&DiagsClient, false);
246
247 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
248 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
249 VFS = VFSWithRemapping;
250 Clang->setVirtualFileSystem(VFS);
251
252 Clang->setTarget(TargetInfo::CreateTargetInfo(
253 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
254 if (!Clang->hasTarget())
255 return nullptr;
256
257 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
258 // release it.
259 Buffer.release();
260 return Clang;
261}
262
Ilya Biryukov02d58702017-08-01 15:51:38 +0000263template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
264 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
265}
266
Ilya Biryukov04db3682017-07-21 13:29:29 +0000267} // namespace
268
Ilya Biryukov38d79772017-05-16 09:38:59 +0000269namespace {
270
271CompletionItemKind getKind(CXCursorKind K) {
272 switch (K) {
273 case CXCursor_MacroInstantiation:
274 case CXCursor_MacroDefinition:
275 return CompletionItemKind::Text;
276 case CXCursor_CXXMethod:
277 return CompletionItemKind::Method;
278 case CXCursor_FunctionDecl:
279 case CXCursor_FunctionTemplate:
280 return CompletionItemKind::Function;
281 case CXCursor_Constructor:
282 case CXCursor_Destructor:
283 return CompletionItemKind::Constructor;
284 case CXCursor_FieldDecl:
285 return CompletionItemKind::Field;
286 case CXCursor_VarDecl:
287 case CXCursor_ParmDecl:
288 return CompletionItemKind::Variable;
289 case CXCursor_ClassDecl:
290 case CXCursor_StructDecl:
291 case CXCursor_UnionDecl:
292 case CXCursor_ClassTemplate:
293 case CXCursor_ClassTemplatePartialSpecialization:
294 return CompletionItemKind::Class;
295 case CXCursor_Namespace:
296 case CXCursor_NamespaceAlias:
297 case CXCursor_NamespaceRef:
298 return CompletionItemKind::Module;
299 case CXCursor_EnumConstantDecl:
300 return CompletionItemKind::Value;
301 case CXCursor_EnumDecl:
302 return CompletionItemKind::Enum;
303 case CXCursor_TypeAliasDecl:
304 case CXCursor_TypeAliasTemplateDecl:
305 case CXCursor_TypedefDecl:
306 case CXCursor_MemberRef:
307 case CXCursor_TypeRef:
308 return CompletionItemKind::Reference;
309 default:
310 return CompletionItemKind::Missing;
311 }
312}
313
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000314std::string escapeSnippet(const llvm::StringRef Text) {
315 std::string Result;
316 Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
317 for (const auto Character : Text) {
318 if (Character == '$' || Character == '}' || Character == '\\')
319 Result.push_back('\\');
320 Result.push_back(Character);
321 }
322 return Result;
323}
324
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000325std::string getDocumentation(const CodeCompletionString &CCS) {
326 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
327 // information in the documentation field.
328 std::string Result;
329 const unsigned AnnotationCount = CCS.getAnnotationCount();
330 if (AnnotationCount > 0) {
331 Result += "Annotation";
332 if (AnnotationCount == 1) {
333 Result += ": ";
334 } else /* AnnotationCount > 1 */ {
335 Result += "s: ";
336 }
337 for (unsigned I = 0; I < AnnotationCount; ++I) {
338 Result += CCS.getAnnotation(I);
339 Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
340 }
341 }
342 // Add brief documentation (if there is any).
343 if (CCS.getBriefComment() != nullptr) {
344 if (!Result.empty()) {
345 // This means we previously added annotations. Add an extra newline
346 // character to make the annotations stand out.
347 Result.push_back('\n');
348 }
349 Result += CCS.getBriefComment();
350 }
351 return Result;
352}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000353
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000354class CompletionItemsCollector : public CodeCompleteConsumer {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000355public:
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000356 CompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
357 std::vector<CompletionItem> &Items)
Ilya Biryukov38d79772017-05-16 09:38:59 +0000358 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
359 Items(Items),
360 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
361 CCTUInfo(Allocator) {}
362
363 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
364 CodeCompletionResult *Results,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000365 unsigned NumResults) override final {
366 Items.reserve(NumResults);
367 for (unsigned I = 0; I < NumResults; ++I) {
368 auto &Result = Results[I];
369 const auto *CCS = Result.CreateCodeCompletionString(
Ilya Biryukov38d79772017-05-16 09:38:59 +0000370 S, Context, *Allocator, CCTUInfo,
371 CodeCompleteOpts.IncludeBriefComments);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000372 assert(CCS && "Expected the CodeCompletionString to be non-null");
373 Items.push_back(ProcessCodeCompleteResult(Result, *CCS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000374 }
375 }
376
377 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
378
379 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000380
381private:
382 CompletionItem
383 ProcessCodeCompleteResult(const CodeCompletionResult &Result,
384 const CodeCompletionString &CCS) const {
385
386 // Adjust this to InsertTextFormat::Snippet iff we encounter a
387 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
388 CompletionItem Item;
389 Item.insertTextFormat = InsertTextFormat::PlainText;
390
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000391 Item.documentation = getDocumentation(CCS);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000392
393 // Fill in the label, detail, insertText and filterText fields of the
394 // CompletionItem.
395 ProcessChunks(CCS, Item);
396
397 // Fill in the kind field of the CompletionItem.
398 Item.kind = getKind(Result.CursorKind);
399
400 FillSortText(CCS, Item);
401
402 return Item;
403 }
404
405 virtual void ProcessChunks(const CodeCompletionString &CCS,
406 CompletionItem &Item) const = 0;
407
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000408 static int GetSortPriority(const CodeCompletionString &CCS) {
409 int Score = CCS.getPriority();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000410 // Fill in the sortText of the CompletionItem.
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000411 assert(Score <= 99999 && "Expecting code completion result "
412 "priority to have at most 5-digits");
413
414 const int Penalty = 100000;
415 switch (static_cast<CXAvailabilityKind>(CCS.getAvailability())) {
416 case CXAvailability_Available:
417 // No penalty.
418 break;
419 case CXAvailability_Deprecated:
420 Score += Penalty;
421 break;
422 case CXAvailability_NotAccessible:
423 Score += 2 * Penalty;
424 break;
425 case CXAvailability_NotAvailable:
426 Score += 3 * Penalty;
427 break;
428 }
429
430 return Score;
431 }
432
433 static void FillSortText(const CodeCompletionString &CCS,
434 CompletionItem &Item) {
435 int Priority = GetSortPriority(CCS);
436 // Fill in the sortText of the CompletionItem.
437 assert(Priority <= 999999 &&
438 "Expecting sort priority to have at most 6-digits");
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000439 llvm::raw_string_ostream(Item.sortText)
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000440 << llvm::format("%06d%s", Priority, Item.filterText.c_str());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000441 }
442
443 std::vector<CompletionItem> &Items;
444 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
445 CodeCompletionTUInfo CCTUInfo;
446
447}; // CompletionItemsCollector
448
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000449bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
450 return Chunk.Kind == CodeCompletionString::CK_Informative &&
451 StringRef(Chunk.Text).endswith("::");
452}
453
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000454class PlainTextCompletionItemsCollector final
455 : public CompletionItemsCollector {
456
457public:
458 PlainTextCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
459 std::vector<CompletionItem> &Items)
460 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
461
462private:
463 void ProcessChunks(const CodeCompletionString &CCS,
464 CompletionItem &Item) const override {
465 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000466 // Informative qualifier chunks only clutter completion results, skip
467 // them.
468 if (isInformativeQualifierChunk(Chunk))
469 continue;
470
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000471 switch (Chunk.Kind) {
472 case CodeCompletionString::CK_TypedText:
473 // There's always exactly one CK_TypedText chunk.
474 Item.insertText = Item.filterText = Chunk.Text;
475 Item.label += Chunk.Text;
476 break;
477 case CodeCompletionString::CK_ResultType:
478 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
479 Item.detail = Chunk.Text;
480 break;
481 case CodeCompletionString::CK_Optional:
482 break;
483 default:
484 Item.label += Chunk.Text;
485 break;
486 }
487 }
488 }
489}; // PlainTextCompletionItemsCollector
490
491class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
492
493public:
494 SnippetCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
495 std::vector<CompletionItem> &Items)
496 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
497
498private:
499 void ProcessChunks(const CodeCompletionString &CCS,
500 CompletionItem &Item) const override {
501 unsigned ArgCount = 0;
502 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000503 // Informative qualifier chunks only clutter completion results, skip
504 // them.
505 if (isInformativeQualifierChunk(Chunk))
506 continue;
507
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000508 switch (Chunk.Kind) {
509 case CodeCompletionString::CK_TypedText:
510 // The piece of text that the user is expected to type to match
511 // the code-completion string, typically a keyword or the name of
512 // a declarator or macro.
513 Item.filterText = Chunk.Text;
514 // Note intentional fallthrough here.
515 case CodeCompletionString::CK_Text:
516 // A piece of text that should be placed in the buffer,
517 // e.g., parentheses or a comma in a function call.
518 Item.label += Chunk.Text;
519 Item.insertText += Chunk.Text;
520 break;
521 case CodeCompletionString::CK_Optional:
522 // A code completion string that is entirely optional.
523 // For example, an optional code completion string that
524 // describes the default arguments in a function call.
525
526 // FIXME: Maybe add an option to allow presenting the optional chunks?
527 break;
528 case CodeCompletionString::CK_Placeholder:
529 // A string that acts as a placeholder for, e.g., a function call
530 // argument.
531 ++ArgCount;
532 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
533 escapeSnippet(Chunk.Text) + '}';
534 Item.label += Chunk.Text;
535 Item.insertTextFormat = InsertTextFormat::Snippet;
536 break;
537 case CodeCompletionString::CK_Informative:
538 // A piece of text that describes something about the result
539 // but should not be inserted into the buffer.
540 // For example, the word "const" for a const method, or the name of
541 // the base class for methods that are part of the base class.
542 Item.label += Chunk.Text;
543 // Don't put the informative chunks in the insertText.
544 break;
545 case CodeCompletionString::CK_ResultType:
546 // A piece of text that describes the type of an entity or,
547 // for functions and methods, the return type.
548 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
549 Item.detail = Chunk.Text;
550 break;
551 case CodeCompletionString::CK_CurrentParameter:
552 // A piece of text that describes the parameter that corresponds to
553 // the code-completion location within a function call, message send,
554 // macro invocation, etc.
555 //
556 // This should never be present while collecting completion items,
557 // only while collecting overload candidates.
558 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
559 "CompletionItems");
560 break;
561 case CodeCompletionString::CK_LeftParen:
562 // A left parenthesis ('(').
563 case CodeCompletionString::CK_RightParen:
564 // A right parenthesis (')').
565 case CodeCompletionString::CK_LeftBracket:
566 // A left bracket ('[').
567 case CodeCompletionString::CK_RightBracket:
568 // A right bracket (']').
569 case CodeCompletionString::CK_LeftBrace:
570 // A left brace ('{').
571 case CodeCompletionString::CK_RightBrace:
572 // A right brace ('}').
573 case CodeCompletionString::CK_LeftAngle:
574 // A left angle bracket ('<').
575 case CodeCompletionString::CK_RightAngle:
576 // A right angle bracket ('>').
577 case CodeCompletionString::CK_Comma:
578 // A comma separator (',').
579 case CodeCompletionString::CK_Colon:
580 // A colon (':').
581 case CodeCompletionString::CK_SemiColon:
582 // A semicolon (';').
583 case CodeCompletionString::CK_Equal:
584 // An '=' sign.
585 case CodeCompletionString::CK_HorizontalSpace:
586 // Horizontal whitespace (' ').
587 Item.insertText += Chunk.Text;
588 Item.label += Chunk.Text;
589 break;
590 case CodeCompletionString::CK_VerticalSpace:
591 // Vertical whitespace ('\n' or '\r\n', depending on the
592 // platform).
593 Item.insertText += Chunk.Text;
594 // Don't even add a space to the label.
595 break;
596 }
597 }
598 }
599}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000600
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000601class SignatureHelpCollector final : public CodeCompleteConsumer {
602
603public:
604 SignatureHelpCollector(const CodeCompleteOptions &CodeCompleteOpts,
605 SignatureHelp &SigHelp)
606 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
607 SigHelp(SigHelp),
608 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
609 CCTUInfo(Allocator) {}
610
611 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
612 OverloadCandidate *Candidates,
613 unsigned NumCandidates) override {
614 SigHelp.signatures.reserve(NumCandidates);
615 // FIXME(rwols): How can we determine the "active overload candidate"?
616 // Right now the overloaded candidates seem to be provided in a "best fit"
617 // order, so I'm not too worried about this.
618 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000619 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000620 "too many arguments");
621 SigHelp.activeParameter = static_cast<int>(CurrentArg);
622 for (unsigned I = 0; I < NumCandidates; ++I) {
623 const auto &Candidate = Candidates[I];
624 const auto *CCS = Candidate.CreateSignatureString(
625 CurrentArg, S, *Allocator, CCTUInfo, true);
626 assert(CCS && "Expected the CodeCompletionString to be non-null");
627 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
628 }
629 }
630
631 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
632
633 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
634
635private:
636 SignatureInformation
637 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
638 const CodeCompletionString &CCS) const {
639 SignatureInformation Result;
640 const char *ReturnType = nullptr;
641
642 Result.documentation = getDocumentation(CCS);
643
644 for (const auto &Chunk : CCS) {
645 switch (Chunk.Kind) {
646 case CodeCompletionString::CK_ResultType:
647 // A piece of text that describes the type of an entity or,
648 // for functions and methods, the return type.
649 assert(!ReturnType && "Unexpected CK_ResultType");
650 ReturnType = Chunk.Text;
651 break;
652 case CodeCompletionString::CK_Placeholder:
653 // A string that acts as a placeholder for, e.g., a function call
654 // argument.
655 // Intentional fallthrough here.
656 case CodeCompletionString::CK_CurrentParameter: {
657 // A piece of text that describes the parameter that corresponds to
658 // the code-completion location within a function call, message send,
659 // macro invocation, etc.
660 Result.label += Chunk.Text;
661 ParameterInformation Info;
662 Info.label = Chunk.Text;
663 Result.parameters.push_back(std::move(Info));
664 break;
665 }
666 case CodeCompletionString::CK_Optional: {
667 // The rest of the parameters are defaulted/optional.
668 assert(Chunk.Optional &&
669 "Expected the optional code completion string to be non-null.");
670 Result.label +=
671 getOptionalParameters(*Chunk.Optional, Result.parameters);
672 break;
673 }
674 case CodeCompletionString::CK_VerticalSpace:
675 break;
676 default:
677 Result.label += Chunk.Text;
678 break;
679 }
680 }
681 if (ReturnType) {
682 Result.label += " -> ";
683 Result.label += ReturnType;
684 }
685 return Result;
686 }
687
688 SignatureHelp &SigHelp;
689 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
690 CodeCompletionTUInfo CCTUInfo;
691
692}; // SignatureHelpCollector
693
694bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
695 const CodeCompleteOptions &Options, PathRef FileName,
696 const tooling::CompileCommand &Command,
697 PrecompiledPreamble const *Preamble, StringRef Contents,
698 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
699 std::shared_ptr<PCHContainerOperations> PCHs,
700 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000701 std::vector<const char *> ArgStrs;
702 for (const auto &S : Command.CommandLine)
703 ArgStrs.push_back(S.c_str());
704
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000705 VFS->setCurrentWorkingDirectory(Command.Directory);
706
Ilya Biryukov04db3682017-07-21 13:29:29 +0000707 std::unique_ptr<CompilerInvocation> CI;
708 EmptyDiagsConsumer DummyDiagsConsumer;
709 {
710 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
711 CompilerInstance::createDiagnostics(new DiagnosticOptions,
712 &DummyDiagsConsumer, false);
713 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
714 }
715 assert(CI && "Couldn't create CompilerInvocation");
716
717 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
718 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
719
720 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000721 if (Preamble) {
722 auto Bounds =
723 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000724 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
725 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000726 }
727
Ilya Biryukov02d58702017-08-01 15:51:38 +0000728 auto Clang = prepareCompilerInstance(std::move(CI), Preamble,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000729 std::move(ContentsBuffer), PCHs, VFS,
730 DummyDiagsConsumer);
731 auto &DiagOpts = Clang->getDiagnosticOpts();
732 DiagOpts.IgnoreWarnings = true;
733
734 auto &FrontendOpts = Clang->getFrontendOpts();
735 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000736 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000737 FrontendOpts.CodeCompletionAt.FileName = FileName;
738 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
739 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
740
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000741 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000742
Ilya Biryukov04db3682017-07-21 13:29:29 +0000743 SyntaxOnlyAction Action;
744 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000745 Logger.log("BeginSourceFile() failed when running codeComplete for " +
746 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000747 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000748 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000749 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000750 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000751 return false;
752 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000753
Ilya Biryukov04db3682017-07-21 13:29:29 +0000754 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000755
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000756 return true;
757}
758
759} // namespace
760
761std::vector<CompletionItem>
762clangd::codeComplete(PathRef FileName, tooling::CompileCommand Command,
763 PrecompiledPreamble const *Preamble, StringRef Contents,
764 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
765 std::shared_ptr<PCHContainerOperations> PCHs,
766 bool SnippetCompletions, clangd::Logger &Logger) {
767 std::vector<CompletionItem> Results;
768 CodeCompleteOptions Options;
769 std::unique_ptr<CodeCompleteConsumer> Consumer;
770 Options.IncludeGlobals = true;
771 Options.IncludeMacros = true;
772 Options.IncludeBriefComments = true;
773 if (SnippetCompletions) {
774 Options.IncludeCodePatterns = true;
775 Consumer =
776 llvm::make_unique<SnippetCompletionItemsCollector>(Options, Results);
777 } else {
778 Options.IncludeCodePatterns = false;
779 Consumer =
780 llvm::make_unique<PlainTextCompletionItemsCollector>(Options, Results);
781 }
782 invokeCodeComplete(std::move(Consumer), Options, FileName, Command, Preamble,
783 Contents, Pos, std::move(VFS), std::move(PCHs), Logger);
784 return Results;
785}
786
787SignatureHelp
788clangd::signatureHelp(PathRef FileName, tooling::CompileCommand Command,
789 PrecompiledPreamble const *Preamble, StringRef Contents,
790 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
791 std::shared_ptr<PCHContainerOperations> PCHs,
792 clangd::Logger &Logger) {
793 SignatureHelp Result;
794 CodeCompleteOptions Options;
795 Options.IncludeGlobals = false;
796 Options.IncludeMacros = false;
797 Options.IncludeCodePatterns = false;
798 Options.IncludeBriefComments = true;
799 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
800 Options, FileName, Command, Preamble, Contents, Pos,
801 std::move(VFS), std::move(PCHs), Logger);
802 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000803}
804
Ilya Biryukov02d58702017-08-01 15:51:38 +0000805void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
806 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000807}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000808
Ilya Biryukov02d58702017-08-01 15:51:38 +0000809llvm::Optional<ParsedAST>
810ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
811 const PrecompiledPreamble *Preamble,
812 ArrayRef<serialization::DeclID> PreambleDeclIDs,
813 std::unique_ptr<llvm::MemoryBuffer> Buffer,
814 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000815 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
816 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000817
818 std::vector<DiagWithFixIts> ASTDiags;
819 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
820
821 auto Clang =
822 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
823 VFS, /*ref*/ UnitDiagsConsumer);
824
825 // Recover resources if we crash before exiting this method.
826 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
827 Clang.get());
828
829 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000830 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
831 if (!Action->BeginSourceFile(*Clang, MainInput)) {
832 Logger.log("BeginSourceFile() failed when building AST for " +
833 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000834 return llvm::None;
835 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000836 if (!Action->Execute())
837 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000838
839 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
840 // has a longer lifetime.
841 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
842
843 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
844 std::vector<serialization::DeclID> PendingDecls;
845 if (Preamble) {
846 PendingDecls.reserve(PreambleDeclIDs.size());
847 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
848 PreambleDeclIDs.end());
849 }
850
851 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
852 std::move(PendingDecls), std::move(ASTDiags));
853}
854
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000855namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000856
857SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
858 const FileEntry *FE,
859 unsigned Offset) {
860 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
861 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
862}
863
864SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
865 const FileEntry *FE, Position Pos) {
866 SourceLocation InputLoc =
867 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
868 return Mgr.getMacroArgExpandedLocation(InputLoc);
869}
870
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000871/// Finds declarations locations that a given source location refers to.
872class DeclarationLocationsFinder : public index::IndexDataConsumer {
873 std::vector<Location> DeclarationLocations;
874 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000875 const ASTContext &AST;
876 Preprocessor &PP;
877
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000878public:
879 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000880 const SourceLocation &SearchedLocation,
881 ASTContext &AST, Preprocessor &PP)
882 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000883
884 std::vector<Location> takeLocations() {
885 // Don't keep the same location multiple times.
886 // This can happen when nodes in the AST are visited twice.
887 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000888 auto last =
889 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000890 DeclarationLocations.erase(last, DeclarationLocations.end());
891 return std::move(DeclarationLocations);
892 }
893
Ilya Biryukov02d58702017-08-01 15:51:38 +0000894 bool
895 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
896 ArrayRef<index::SymbolRelation> Relations, FileID FID,
897 unsigned Offset,
898 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000899 if (isSearchedLocation(FID, Offset)) {
900 addDeclarationLocation(D->getSourceRange());
901 }
902 return true;
903 }
904
905private:
906 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000907 const SourceManager &SourceMgr = AST.getSourceManager();
908 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
909 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000910 }
911
Ilya Biryukov04db3682017-07-21 13:29:29 +0000912 void addDeclarationLocation(const SourceRange &ValSourceRange) {
913 const SourceManager &SourceMgr = AST.getSourceManager();
914 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000915 SourceLocation LocStart = ValSourceRange.getBegin();
916 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000917 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000918 Position Begin;
919 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
920 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
921 Position End;
922 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
923 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
924 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000925 Location L;
926 L.uri = URI::fromFile(
927 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
928 L.range = R;
929 DeclarationLocations.push_back(L);
930 }
931
Kirill Bobyrev46213872017-06-28 20:57:28 +0000932 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000933 // Also handle possible macro at the searched location.
934 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000935 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
936 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000937 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000938 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000939 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000940 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000941 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
942 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000943 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000944 // Get the definition just before the searched location so that a macro
945 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000946 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
947 AST.getSourceManager(),
948 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000949 DecLoc.second - 1);
950 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000951 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
952 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000953 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000954 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
955 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000956 }
957 }
958 }
959 }
960};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000961
Ilya Biryukov02d58702017-08-01 15:51:38 +0000962SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
963 const FileEntry *FE) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000964 // The language server protocol uses zero-based line and column numbers.
965 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000966
Ilya Biryukov02d58702017-08-01 15:51:38 +0000967 const ASTContext &AST = Unit.getASTContext();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000968 const SourceManager &SourceMgr = AST.getSourceManager();
969
970 SourceLocation InputLocation =
971 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000972 if (Pos.character == 0) {
973 return InputLocation;
974 }
975
976 // This handle cases where the position is in the middle of a token or right
977 // after the end of a token. In theory we could just use GetBeginningOfToken
978 // to find the start of the token at the input position, but this doesn't
979 // work when right after the end, i.e. foo|.
980 // So try to go back by one and see if we're still inside the an identifier
981 // token. If so, Take the beginning of this token.
982 // (It should be the same identifier because you can't have two adjacent
983 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000984 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
985 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000986 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000987 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000988 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000989 // getRawToken failed, just use InputLocation.
990 return InputLocation;
991 }
992
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000993 if (Result.is(tok::raw_identifier)) {
994 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000995 AST.getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000996 }
997
998 return InputLocation;
999}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001000} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001001
Ilya Biryukove5128f72017-09-20 07:24:15 +00001002std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1003 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001004 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1005 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1006 if (!FE)
1007 return {};
1008
1009 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1010
1011 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1012 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1013 AST.getPreprocessor());
1014 index::IndexingOptions IndexOpts;
1015 IndexOpts.SystemSymbolFilter =
1016 index::IndexingOptions::SystemSymbolFilterKind::All;
1017 IndexOpts.IndexFunctionLocals = true;
1018
1019 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1020 DeclLocationsFinder, IndexOpts);
1021
1022 return DeclLocationsFinder->takeLocations();
1023}
1024
1025void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001026 if (PendingTopLevelDecls.empty())
1027 return;
1028
1029 std::vector<const Decl *> Resolved;
1030 Resolved.reserve(PendingTopLevelDecls.size());
1031
1032 ExternalASTSource &Source = *getASTContext().getExternalSource();
1033 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
1034 // Resolve the declaration ID to an actual declaration, possibly
1035 // deserializing the declaration in the process.
1036 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1037 Resolved.push_back(D);
1038 }
1039
1040 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
1041 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1042
1043 PendingTopLevelDecls.clear();
1044}
1045
Ilya Biryukov02d58702017-08-01 15:51:38 +00001046ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001047
Ilya Biryukov02d58702017-08-01 15:51:38 +00001048ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001049
Ilya Biryukov02d58702017-08-01 15:51:38 +00001050ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001051 if (Action) {
1052 Action->EndSourceFile();
1053 }
1054}
1055
Ilya Biryukov02d58702017-08-01 15:51:38 +00001056ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1057
1058const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001059 return Clang->getASTContext();
1060}
1061
Ilya Biryukov02d58702017-08-01 15:51:38 +00001062Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001063
Ilya Biryukov02d58702017-08-01 15:51:38 +00001064const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001065 return Clang->getPreprocessor();
1066}
1067
Ilya Biryukov02d58702017-08-01 15:51:38 +00001068ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001069 ensurePreambleDeclsDeserialized();
1070 return TopLevelDecls;
1071}
1072
Ilya Biryukov02d58702017-08-01 15:51:38 +00001073const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001074 return Diags;
1075}
1076
Ilya Biryukov02d58702017-08-01 15:51:38 +00001077ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
1078 std::unique_ptr<FrontendAction> Action,
1079 std::vector<const Decl *> TopLevelDecls,
1080 std::vector<serialization::DeclID> PendingTopLevelDecls,
1081 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001082 : Clang(std::move(Clang)), Action(std::move(Action)),
1083 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
1084 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
1085 assert(this->Clang);
1086 assert(this->Action);
1087}
1088
Ilya Biryukov02d58702017-08-01 15:51:38 +00001089ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1090 : AST(std::move(Wrapper.AST)) {}
1091
1092ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1093 : AST(std::move(AST)) {}
1094
1095PreambleData::PreambleData(PrecompiledPreamble Preamble,
1096 std::vector<serialization::DeclID> TopLevelDeclIDs,
1097 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001098 : Preamble(std::move(Preamble)),
1099 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001100
1101std::shared_ptr<CppFile>
1102CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001103 std::shared_ptr<PCHContainerOperations> PCHs,
1104 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001105 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +00001106 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001107}
1108
1109CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001110 std::shared_ptr<PCHContainerOperations> PCHs,
1111 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +00001112 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001113 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001114
1115 std::lock_guard<std::mutex> Lock(Mutex);
1116 LatestAvailablePreamble = nullptr;
1117 PreamblePromise.set_value(nullptr);
1118 PreambleFuture = PreamblePromise.get_future();
1119
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001120 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001121 ASTFuture = ASTPromise.get_future();
1122}
1123
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001124void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001125
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001126UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001127 std::unique_lock<std::mutex> Lock(Mutex);
1128 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001129 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001130 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1131 // We want to keep this invariant.
1132 if (futureIsReady(PreambleFuture)) {
1133 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1134 PreambleFuture = PreamblePromise.get_future();
1135 }
1136 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001137 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001138 ASTFuture = ASTPromise.get_future();
1139 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001140
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001141 Lock.unlock();
1142 // Notify about changes to RebuildCounter.
1143 RebuildCond.notify_all();
1144
1145 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001146 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001147 std::unique_lock<std::mutex> Lock(That->Mutex);
1148 CppFile *This = &*That;
1149 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1150 return !This->RebuildInProgress ||
1151 This->RebuildCounter != RequestRebuildCounter;
1152 });
1153
1154 // This computation got cancelled itself, do nothing.
1155 if (This->RebuildCounter != RequestRebuildCounter)
1156 return;
1157
1158 // Set empty results for Promises.
1159 That->PreamblePromise.set_value(nullptr);
1160 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001161 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001162}
1163
1164llvm::Optional<std::vector<DiagWithFixIts>>
1165CppFile::rebuild(StringRef NewContents,
1166 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001167 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001168}
1169
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001170UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001171CppFile::deferRebuild(StringRef NewContents,
1172 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1173 std::shared_ptr<const PreambleData> OldPreamble;
1174 std::shared_ptr<PCHContainerOperations> PCHs;
1175 unsigned RequestRebuildCounter;
1176 {
1177 std::unique_lock<std::mutex> Lock(Mutex);
1178 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1179 // They will try to exit as early as possible and won't call set_value on
1180 // our promises.
1181 RequestRebuildCounter = ++this->RebuildCounter;
1182 PCHs = this->PCHs;
1183
1184 // Remember the preamble to be used during rebuild.
1185 OldPreamble = this->LatestAvailablePreamble;
1186 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1187 // futures will wait until the rebuild process is finished.
1188 if (futureIsReady(this->PreambleFuture)) {
1189 this->PreamblePromise =
1190 std::promise<std::shared_ptr<const PreambleData>>();
1191 this->PreambleFuture = this->PreamblePromise.get_future();
1192 }
1193 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001194 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001195 this->ASTFuture = this->ASTPromise.get_future();
1196 }
1197 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001198 // Notify about changes to RebuildCounter.
1199 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001200
1201 // A helper to function to finish the rebuild. May be run on a different
1202 // thread.
1203
1204 // Don't let this CppFile die before rebuild is finished.
1205 std::shared_ptr<CppFile> That = shared_from_this();
1206 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1207 That](std::string NewContents)
1208 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1209 // Only one execution of this method is possible at a time.
1210 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1211 // into a state for doing a rebuild.
1212 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1213 if (Rebuild.wasCancelledBeforeConstruction())
1214 return llvm::None;
1215
1216 std::vector<const char *> ArgStrs;
1217 for (const auto &S : That->Command.CommandLine)
1218 ArgStrs.push_back(S.c_str());
1219
1220 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1221
1222 std::unique_ptr<CompilerInvocation> CI;
1223 {
1224 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1225 // reporting them.
1226 EmptyDiagsConsumer CommandLineDiagsConsumer;
1227 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1228 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1229 &CommandLineDiagsConsumer, false);
1230 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1231 }
1232 assert(CI && "Couldn't create CompilerInvocation");
1233
1234 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1235 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1236
1237 // A helper function to rebuild the preamble or reuse the existing one. Does
1238 // not mutate any fields, only does the actual computation.
1239 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1240 auto Bounds =
1241 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1242 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1243 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1244 return OldPreamble;
1245 }
1246
1247 std::vector<DiagWithFixIts> PreambleDiags;
1248 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1249 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1250 CompilerInstance::createDiagnostics(
1251 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1252 CppFilePreambleCallbacks SerializedDeclsCollector;
1253 auto BuiltPreamble = PrecompiledPreamble::Build(
1254 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
1255 SerializedDeclsCollector);
1256
1257 if (BuiltPreamble) {
1258 return std::make_shared<PreambleData>(
1259 std::move(*BuiltPreamble),
1260 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1261 std::move(PreambleDiags));
1262 } else {
1263 return nullptr;
1264 }
1265 };
1266
1267 // Compute updated Preamble.
1268 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1269 // Publish the new Preamble.
1270 {
1271 std::lock_guard<std::mutex> Lock(That->Mutex);
1272 // We always set LatestAvailablePreamble to the new value, hoping that it
1273 // will still be usable in the further requests.
1274 That->LatestAvailablePreamble = NewPreamble;
1275 if (RequestRebuildCounter != That->RebuildCounter)
1276 return llvm::None; // Our rebuild request was cancelled, do nothing.
1277 That->PreamblePromise.set_value(NewPreamble);
1278 } // unlock Mutex
1279
1280 // Prepare the Preamble and supplementary data for rebuilding AST.
1281 const PrecompiledPreamble *PreambleForAST = nullptr;
1282 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1283 std::vector<DiagWithFixIts> Diagnostics;
1284 if (NewPreamble) {
1285 PreambleForAST = &NewPreamble->Preamble;
1286 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1287 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1288 NewPreamble->Diags.end());
1289 }
1290
1291 // Compute updated AST.
1292 llvm::Optional<ParsedAST> NewAST =
1293 ParsedAST::Build(std::move(CI), PreambleForAST, SerializedPreambleDecls,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001294 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001295
1296 if (NewAST) {
1297 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1298 NewAST->getDiagnostics().end());
1299 } else {
1300 // Don't report even Preamble diagnostics if we coulnd't build AST.
1301 Diagnostics.clear();
1302 }
1303
1304 // Publish the new AST.
1305 {
1306 std::lock_guard<std::mutex> Lock(That->Mutex);
1307 if (RequestRebuildCounter != That->RebuildCounter)
1308 return Diagnostics; // Our rebuild request was cancelled, don't set
1309 // ASTPromise.
1310
Ilya Biryukov574b7532017-08-02 09:08:39 +00001311 That->ASTPromise.set_value(
1312 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001313 } // unlock Mutex
1314
1315 return Diagnostics;
1316 };
1317
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001318 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001319}
1320
1321std::shared_future<std::shared_ptr<const PreambleData>>
1322CppFile::getPreamble() const {
1323 std::lock_guard<std::mutex> Lock(Mutex);
1324 return PreambleFuture;
1325}
1326
1327std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1328 std::lock_guard<std::mutex> Lock(Mutex);
1329 return LatestAvailablePreamble;
1330}
1331
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001332std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001333 std::lock_guard<std::mutex> Lock(Mutex);
1334 return ASTFuture;
1335}
1336
1337tooling::CompileCommand const &CppFile::getCompileCommand() const {
1338 return Command;
1339}
1340
1341CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1342 unsigned RequestRebuildCounter)
1343 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1344 std::unique_lock<std::mutex> Lock(File.Mutex);
1345 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1346 if (WasCancelledBeforeConstruction)
1347 return;
1348
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001349 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1350 return !File.RebuildInProgress ||
1351 File.RebuildCounter != RequestRebuildCounter;
1352 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001353
1354 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1355 if (WasCancelledBeforeConstruction)
1356 return;
1357
1358 File.RebuildInProgress = true;
1359}
1360
1361bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1362 return WasCancelledBeforeConstruction;
1363}
1364
1365CppFile::RebuildGuard::~RebuildGuard() {
1366 if (WasCancelledBeforeConstruction)
1367 return;
1368
1369 std::unique_lock<std::mutex> Lock(File.Mutex);
1370 assert(File.RebuildInProgress);
1371 File.RebuildInProgress = false;
1372
1373 if (File.RebuildCounter == RequestRebuildCounter) {
1374 // Our rebuild request was successful.
1375 assert(futureIsReady(File.ASTFuture));
1376 assert(futureIsReady(File.PreambleFuture));
1377 } else {
1378 // Our rebuild request was cancelled, because further reparse was requested.
1379 assert(!futureIsReady(File.ASTFuture));
1380 assert(!futureIsReady(File.PreambleFuture));
1381 }
1382
1383 Lock.unlock();
1384 File.RebuildCond.notify_all();
1385}