blob: 14eac6c2e41a579c65336a270a51da1919bec97e [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
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000271CompletionItemKind getKindOfDecl(CXCursorKind CursorKind) {
272 switch (CursorKind) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000273 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 Biryukov01e3bf82017-10-23 06:06:21 +0000314CompletionItemKind getKind(CodeCompletionResult::ResultKind ResKind,
315 CXCursorKind CursorKind) {
316 switch (ResKind) {
317 case CodeCompletionResult::RK_Declaration:
318 return getKindOfDecl(CursorKind);
319 case CodeCompletionResult::RK_Keyword:
320 return CompletionItemKind::Keyword;
321 case CodeCompletionResult::RK_Macro:
322 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
323 // completion items in LSP.
324 case CodeCompletionResult::RK_Pattern:
325 return CompletionItemKind::Snippet;
326 }
327 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
328}
329
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000330std::string escapeSnippet(const llvm::StringRef Text) {
331 std::string Result;
332 Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
333 for (const auto Character : Text) {
334 if (Character == '$' || Character == '}' || Character == '\\')
335 Result.push_back('\\');
336 Result.push_back(Character);
337 }
338 return Result;
339}
340
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000341std::string getDocumentation(const CodeCompletionString &CCS) {
342 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
343 // information in the documentation field.
344 std::string Result;
345 const unsigned AnnotationCount = CCS.getAnnotationCount();
346 if (AnnotationCount > 0) {
347 Result += "Annotation";
348 if (AnnotationCount == 1) {
349 Result += ": ";
350 } else /* AnnotationCount > 1 */ {
351 Result += "s: ";
352 }
353 for (unsigned I = 0; I < AnnotationCount; ++I) {
354 Result += CCS.getAnnotation(I);
355 Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
356 }
357 }
358 // Add brief documentation (if there is any).
359 if (CCS.getBriefComment() != nullptr) {
360 if (!Result.empty()) {
361 // This means we previously added annotations. Add an extra newline
362 // character to make the annotations stand out.
363 Result.push_back('\n');
364 }
365 Result += CCS.getBriefComment();
366 }
367 return Result;
368}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000369
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000370class CompletionItemsCollector : public CodeCompleteConsumer {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000371public:
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000372 CompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
373 std::vector<CompletionItem> &Items)
Ilya Biryukov38d79772017-05-16 09:38:59 +0000374 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
375 Items(Items),
376 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
377 CCTUInfo(Allocator) {}
378
379 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
380 CodeCompletionResult *Results,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000381 unsigned NumResults) override final {
382 Items.reserve(NumResults);
383 for (unsigned I = 0; I < NumResults; ++I) {
384 auto &Result = Results[I];
385 const auto *CCS = Result.CreateCodeCompletionString(
Ilya Biryukov38d79772017-05-16 09:38:59 +0000386 S, Context, *Allocator, CCTUInfo,
387 CodeCompleteOpts.IncludeBriefComments);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000388 assert(CCS && "Expected the CodeCompletionString to be non-null");
389 Items.push_back(ProcessCodeCompleteResult(Result, *CCS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000390 }
391 }
392
393 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
394
395 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000396
397private:
398 CompletionItem
399 ProcessCodeCompleteResult(const CodeCompletionResult &Result,
400 const CodeCompletionString &CCS) const {
401
402 // Adjust this to InsertTextFormat::Snippet iff we encounter a
403 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
404 CompletionItem Item;
405 Item.insertTextFormat = InsertTextFormat::PlainText;
406
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000407 Item.documentation = getDocumentation(CCS);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000408
409 // Fill in the label, detail, insertText and filterText fields of the
410 // CompletionItem.
411 ProcessChunks(CCS, Item);
412
413 // Fill in the kind field of the CompletionItem.
Ilya Biryukov01e3bf82017-10-23 06:06:21 +0000414 Item.kind = getKind(Result.Kind, Result.CursorKind);
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000415
416 FillSortText(CCS, Item);
417
418 return Item;
419 }
420
421 virtual void ProcessChunks(const CodeCompletionString &CCS,
422 CompletionItem &Item) const = 0;
423
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000424 static int GetSortPriority(const CodeCompletionString &CCS) {
425 int Score = CCS.getPriority();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000426 // Fill in the sortText of the CompletionItem.
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000427 assert(Score <= 99999 && "Expecting code completion result "
428 "priority to have at most 5-digits");
429
430 const int Penalty = 100000;
431 switch (static_cast<CXAvailabilityKind>(CCS.getAvailability())) {
432 case CXAvailability_Available:
433 // No penalty.
434 break;
435 case CXAvailability_Deprecated:
436 Score += Penalty;
437 break;
438 case CXAvailability_NotAccessible:
439 Score += 2 * Penalty;
440 break;
441 case CXAvailability_NotAvailable:
442 Score += 3 * Penalty;
443 break;
444 }
445
446 return Score;
447 }
448
449 static void FillSortText(const CodeCompletionString &CCS,
450 CompletionItem &Item) {
451 int Priority = GetSortPriority(CCS);
452 // Fill in the sortText of the CompletionItem.
453 assert(Priority <= 999999 &&
454 "Expecting sort priority to have at most 6-digits");
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000455 llvm::raw_string_ostream(Item.sortText)
Ilya Biryukov77f61ba2017-09-20 15:09:14 +0000456 << llvm::format("%06d%s", Priority, Item.filterText.c_str());
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000457 }
458
459 std::vector<CompletionItem> &Items;
460 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
461 CodeCompletionTUInfo CCTUInfo;
462
463}; // CompletionItemsCollector
464
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000465bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
466 return Chunk.Kind == CodeCompletionString::CK_Informative &&
467 StringRef(Chunk.Text).endswith("::");
468}
469
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000470class PlainTextCompletionItemsCollector final
471 : public CompletionItemsCollector {
472
473public:
474 PlainTextCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
475 std::vector<CompletionItem> &Items)
476 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
477
478private:
479 void ProcessChunks(const CodeCompletionString &CCS,
480 CompletionItem &Item) const override {
481 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000482 // Informative qualifier chunks only clutter completion results, skip
483 // them.
484 if (isInformativeQualifierChunk(Chunk))
485 continue;
486
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000487 switch (Chunk.Kind) {
488 case CodeCompletionString::CK_TypedText:
489 // There's always exactly one CK_TypedText chunk.
490 Item.insertText = Item.filterText = Chunk.Text;
491 Item.label += Chunk.Text;
492 break;
493 case CodeCompletionString::CK_ResultType:
494 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
495 Item.detail = Chunk.Text;
496 break;
497 case CodeCompletionString::CK_Optional:
498 break;
499 default:
500 Item.label += Chunk.Text;
501 break;
502 }
503 }
504 }
505}; // PlainTextCompletionItemsCollector
506
507class SnippetCompletionItemsCollector final : public CompletionItemsCollector {
508
509public:
510 SnippetCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts,
511 std::vector<CompletionItem> &Items)
512 : CompletionItemsCollector(CodeCompleteOpts, Items) {}
513
514private:
515 void ProcessChunks(const CodeCompletionString &CCS,
516 CompletionItem &Item) const override {
517 unsigned ArgCount = 0;
518 for (const auto &Chunk : CCS) {
Ilya Biryukov686ff9a2017-09-28 18:39:59 +0000519 // Informative qualifier chunks only clutter completion results, skip
520 // them.
521 if (isInformativeQualifierChunk(Chunk))
522 continue;
523
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000524 switch (Chunk.Kind) {
525 case CodeCompletionString::CK_TypedText:
526 // The piece of text that the user is expected to type to match
527 // the code-completion string, typically a keyword or the name of
528 // a declarator or macro.
529 Item.filterText = Chunk.Text;
530 // Note intentional fallthrough here.
531 case CodeCompletionString::CK_Text:
532 // A piece of text that should be placed in the buffer,
533 // e.g., parentheses or a comma in a function call.
534 Item.label += Chunk.Text;
535 Item.insertText += Chunk.Text;
536 break;
537 case CodeCompletionString::CK_Optional:
538 // A code completion string that is entirely optional.
539 // For example, an optional code completion string that
540 // describes the default arguments in a function call.
541
542 // FIXME: Maybe add an option to allow presenting the optional chunks?
543 break;
544 case CodeCompletionString::CK_Placeholder:
545 // A string that acts as a placeholder for, e.g., a function call
546 // argument.
547 ++ArgCount;
548 Item.insertText += "${" + std::to_string(ArgCount) + ':' +
549 escapeSnippet(Chunk.Text) + '}';
550 Item.label += Chunk.Text;
551 Item.insertTextFormat = InsertTextFormat::Snippet;
552 break;
553 case CodeCompletionString::CK_Informative:
554 // A piece of text that describes something about the result
555 // but should not be inserted into the buffer.
556 // For example, the word "const" for a const method, or the name of
557 // the base class for methods that are part of the base class.
558 Item.label += Chunk.Text;
559 // Don't put the informative chunks in the insertText.
560 break;
561 case CodeCompletionString::CK_ResultType:
562 // A piece of text that describes the type of an entity or,
563 // for functions and methods, the return type.
564 assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType");
565 Item.detail = Chunk.Text;
566 break;
567 case CodeCompletionString::CK_CurrentParameter:
568 // A piece of text that describes the parameter that corresponds to
569 // the code-completion location within a function call, message send,
570 // macro invocation, etc.
571 //
572 // This should never be present while collecting completion items,
573 // only while collecting overload candidates.
574 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
575 "CompletionItems");
576 break;
577 case CodeCompletionString::CK_LeftParen:
578 // A left parenthesis ('(').
579 case CodeCompletionString::CK_RightParen:
580 // A right parenthesis (')').
581 case CodeCompletionString::CK_LeftBracket:
582 // A left bracket ('[').
583 case CodeCompletionString::CK_RightBracket:
584 // A right bracket (']').
585 case CodeCompletionString::CK_LeftBrace:
586 // A left brace ('{').
587 case CodeCompletionString::CK_RightBrace:
588 // A right brace ('}').
589 case CodeCompletionString::CK_LeftAngle:
590 // A left angle bracket ('<').
591 case CodeCompletionString::CK_RightAngle:
592 // A right angle bracket ('>').
593 case CodeCompletionString::CK_Comma:
594 // A comma separator (',').
595 case CodeCompletionString::CK_Colon:
596 // A colon (':').
597 case CodeCompletionString::CK_SemiColon:
598 // A semicolon (';').
599 case CodeCompletionString::CK_Equal:
600 // An '=' sign.
601 case CodeCompletionString::CK_HorizontalSpace:
602 // Horizontal whitespace (' ').
603 Item.insertText += Chunk.Text;
604 Item.label += Chunk.Text;
605 break;
606 case CodeCompletionString::CK_VerticalSpace:
607 // Vertical whitespace ('\n' or '\r\n', depending on the
608 // platform).
609 Item.insertText += Chunk.Text;
610 // Don't even add a space to the label.
611 break;
612 }
613 }
614 }
615}; // SnippetCompletionItemsCollector
Ilya Biryukov38d79772017-05-16 09:38:59 +0000616
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000617class SignatureHelpCollector final : public CodeCompleteConsumer {
618
619public:
620 SignatureHelpCollector(const CodeCompleteOptions &CodeCompleteOpts,
621 SignatureHelp &SigHelp)
622 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
623 SigHelp(SigHelp),
624 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
625 CCTUInfo(Allocator) {}
626
627 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
628 OverloadCandidate *Candidates,
629 unsigned NumCandidates) override {
630 SigHelp.signatures.reserve(NumCandidates);
631 // FIXME(rwols): How can we determine the "active overload candidate"?
632 // Right now the overloaded candidates seem to be provided in a "best fit"
633 // order, so I'm not too worried about this.
634 SigHelp.activeSignature = 0;
Simon Pilgrima3aa7242017-10-07 12:24:10 +0000635 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000636 "too many arguments");
637 SigHelp.activeParameter = static_cast<int>(CurrentArg);
638 for (unsigned I = 0; I < NumCandidates; ++I) {
639 const auto &Candidate = Candidates[I];
640 const auto *CCS = Candidate.CreateSignatureString(
641 CurrentArg, S, *Allocator, CCTUInfo, true);
642 assert(CCS && "Expected the CodeCompletionString to be non-null");
643 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
644 }
645 }
646
647 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
648
649 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
650
651private:
652 SignatureInformation
653 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
654 const CodeCompletionString &CCS) const {
655 SignatureInformation Result;
656 const char *ReturnType = nullptr;
657
658 Result.documentation = getDocumentation(CCS);
659
660 for (const auto &Chunk : CCS) {
661 switch (Chunk.Kind) {
662 case CodeCompletionString::CK_ResultType:
663 // A piece of text that describes the type of an entity or,
664 // for functions and methods, the return type.
665 assert(!ReturnType && "Unexpected CK_ResultType");
666 ReturnType = Chunk.Text;
667 break;
668 case CodeCompletionString::CK_Placeholder:
669 // A string that acts as a placeholder for, e.g., a function call
670 // argument.
671 // Intentional fallthrough here.
672 case CodeCompletionString::CK_CurrentParameter: {
673 // A piece of text that describes the parameter that corresponds to
674 // the code-completion location within a function call, message send,
675 // macro invocation, etc.
676 Result.label += Chunk.Text;
677 ParameterInformation Info;
678 Info.label = Chunk.Text;
679 Result.parameters.push_back(std::move(Info));
680 break;
681 }
682 case CodeCompletionString::CK_Optional: {
683 // The rest of the parameters are defaulted/optional.
684 assert(Chunk.Optional &&
685 "Expected the optional code completion string to be non-null.");
686 Result.label +=
687 getOptionalParameters(*Chunk.Optional, Result.parameters);
688 break;
689 }
690 case CodeCompletionString::CK_VerticalSpace:
691 break;
692 default:
693 Result.label += Chunk.Text;
694 break;
695 }
696 }
697 if (ReturnType) {
698 Result.label += " -> ";
699 Result.label += ReturnType;
700 }
701 return Result;
702 }
703
704 SignatureHelp &SigHelp;
705 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
706 CodeCompletionTUInfo CCTUInfo;
707
708}; // SignatureHelpCollector
709
710bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
711 const CodeCompleteOptions &Options, PathRef FileName,
712 const tooling::CompileCommand &Command,
713 PrecompiledPreamble const *Preamble, StringRef Contents,
714 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
715 std::shared_ptr<PCHContainerOperations> PCHs,
716 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000717 std::vector<const char *> ArgStrs;
718 for (const auto &S : Command.CommandLine)
719 ArgStrs.push_back(S.c_str());
720
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000721 VFS->setCurrentWorkingDirectory(Command.Directory);
722
Ilya Biryukov04db3682017-07-21 13:29:29 +0000723 std::unique_ptr<CompilerInvocation> CI;
724 EmptyDiagsConsumer DummyDiagsConsumer;
725 {
726 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
727 CompilerInstance::createDiagnostics(new DiagnosticOptions,
728 &DummyDiagsConsumer, false);
729 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
730 }
731 assert(CI && "Couldn't create CompilerInvocation");
732
733 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
734 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
735
736 // Attempt to reuse the PCH from precompiled preamble, if it was built.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000737 if (Preamble) {
738 auto Bounds =
739 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000740 if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get()))
741 Preamble = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000742 }
743
Ilya Biryukov02d58702017-08-01 15:51:38 +0000744 auto Clang = prepareCompilerInstance(std::move(CI), Preamble,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000745 std::move(ContentsBuffer), PCHs, VFS,
746 DummyDiagsConsumer);
747 auto &DiagOpts = Clang->getDiagnosticOpts();
748 DiagOpts.IgnoreWarnings = true;
749
750 auto &FrontendOpts = Clang->getFrontendOpts();
751 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000752 FrontendOpts.CodeCompleteOpts = Options;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000753 FrontendOpts.CodeCompletionAt.FileName = FileName;
754 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
755 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
756
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000757 Clang->setCodeCompletionConsumer(Consumer.release());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000758
Ilya Biryukov04db3682017-07-21 13:29:29 +0000759 SyntaxOnlyAction Action;
760 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000761 Logger.log("BeginSourceFile() failed when running codeComplete for " +
762 FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000763 return false;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000764 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000765 if (!Action.Execute()) {
Ilya Biryukove5128f72017-09-20 07:24:15 +0000766 Logger.log("Execute() failed when running codeComplete for " + FileName);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000767 return false;
768 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000769
Ilya Biryukov04db3682017-07-21 13:29:29 +0000770 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000771
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000772 return true;
773}
774
775} // namespace
776
777std::vector<CompletionItem>
778clangd::codeComplete(PathRef FileName, tooling::CompileCommand Command,
779 PrecompiledPreamble const *Preamble, StringRef Contents,
780 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
781 std::shared_ptr<PCHContainerOperations> PCHs,
782 bool SnippetCompletions, clangd::Logger &Logger) {
783 std::vector<CompletionItem> Results;
784 CodeCompleteOptions Options;
785 std::unique_ptr<CodeCompleteConsumer> Consumer;
786 Options.IncludeGlobals = true;
787 Options.IncludeMacros = true;
788 Options.IncludeBriefComments = true;
789 if (SnippetCompletions) {
790 Options.IncludeCodePatterns = true;
791 Consumer =
792 llvm::make_unique<SnippetCompletionItemsCollector>(Options, Results);
793 } else {
794 Options.IncludeCodePatterns = false;
795 Consumer =
796 llvm::make_unique<PlainTextCompletionItemsCollector>(Options, Results);
797 }
798 invokeCodeComplete(std::move(Consumer), Options, FileName, Command, Preamble,
799 Contents, Pos, std::move(VFS), std::move(PCHs), Logger);
800 return Results;
801}
802
803SignatureHelp
804clangd::signatureHelp(PathRef FileName, tooling::CompileCommand Command,
805 PrecompiledPreamble const *Preamble, StringRef Contents,
806 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
807 std::shared_ptr<PCHContainerOperations> PCHs,
808 clangd::Logger &Logger) {
809 SignatureHelp Result;
810 CodeCompleteOptions Options;
811 Options.IncludeGlobals = false;
812 Options.IncludeMacros = false;
813 Options.IncludeCodePatterns = false;
814 Options.IncludeBriefComments = true;
815 invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
816 Options, FileName, Command, Preamble, Contents, Pos,
817 std::move(VFS), std::move(PCHs), Logger);
818 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000819}
820
Ilya Biryukov02d58702017-08-01 15:51:38 +0000821void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
822 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000823}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000824
Ilya Biryukov02d58702017-08-01 15:51:38 +0000825llvm::Optional<ParsedAST>
826ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
827 const PrecompiledPreamble *Preamble,
828 ArrayRef<serialization::DeclID> PreambleDeclIDs,
829 std::unique_ptr<llvm::MemoryBuffer> Buffer,
830 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000831 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
832 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000833
834 std::vector<DiagWithFixIts> ASTDiags;
835 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
836
837 auto Clang =
838 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
839 VFS, /*ref*/ UnitDiagsConsumer);
840
841 // Recover resources if we crash before exiting this method.
842 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
843 Clang.get());
844
845 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000846 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
847 if (!Action->BeginSourceFile(*Clang, MainInput)) {
848 Logger.log("BeginSourceFile() failed when building AST for " +
849 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000850 return llvm::None;
851 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000852 if (!Action->Execute())
853 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000854
855 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
856 // has a longer lifetime.
857 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
858
859 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
860 std::vector<serialization::DeclID> PendingDecls;
861 if (Preamble) {
862 PendingDecls.reserve(PreambleDeclIDs.size());
863 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
864 PreambleDeclIDs.end());
865 }
866
867 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
868 std::move(PendingDecls), std::move(ASTDiags));
869}
870
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000871namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000872
873SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
874 const FileEntry *FE,
875 unsigned Offset) {
876 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
877 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
878}
879
880SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
881 const FileEntry *FE, Position Pos) {
882 SourceLocation InputLoc =
883 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
884 return Mgr.getMacroArgExpandedLocation(InputLoc);
885}
886
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000887/// Finds declarations locations that a given source location refers to.
888class DeclarationLocationsFinder : public index::IndexDataConsumer {
889 std::vector<Location> DeclarationLocations;
890 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000891 const ASTContext &AST;
892 Preprocessor &PP;
893
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000894public:
895 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000896 const SourceLocation &SearchedLocation,
897 ASTContext &AST, Preprocessor &PP)
898 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000899
900 std::vector<Location> takeLocations() {
901 // Don't keep the same location multiple times.
902 // This can happen when nodes in the AST are visited twice.
903 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000904 auto last =
905 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000906 DeclarationLocations.erase(last, DeclarationLocations.end());
907 return std::move(DeclarationLocations);
908 }
909
Ilya Biryukov02d58702017-08-01 15:51:38 +0000910 bool
911 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
912 ArrayRef<index::SymbolRelation> Relations, FileID FID,
913 unsigned Offset,
914 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000915 if (isSearchedLocation(FID, Offset)) {
916 addDeclarationLocation(D->getSourceRange());
917 }
918 return true;
919 }
920
921private:
922 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000923 const SourceManager &SourceMgr = AST.getSourceManager();
924 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
925 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000926 }
927
Ilya Biryukov04db3682017-07-21 13:29:29 +0000928 void addDeclarationLocation(const SourceRange &ValSourceRange) {
929 const SourceManager &SourceMgr = AST.getSourceManager();
930 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000931 SourceLocation LocStart = ValSourceRange.getBegin();
932 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000933 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000934 Position Begin;
935 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
936 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
937 Position End;
938 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
939 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
940 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000941 Location L;
942 L.uri = URI::fromFile(
943 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
944 L.range = R;
945 DeclarationLocations.push_back(L);
946 }
947
Kirill Bobyrev46213872017-06-28 20:57:28 +0000948 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000949 // Also handle possible macro at the searched location.
950 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000951 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
952 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000953 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000954 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000955 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000956 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000957 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
958 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000959 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000960 // Get the definition just before the searched location so that a macro
961 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000962 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
963 AST.getSourceManager(),
964 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000965 DecLoc.second - 1);
966 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000967 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
968 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000969 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000970 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
971 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000972 }
973 }
974 }
975 }
976};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000977
Ilya Biryukov02d58702017-08-01 15:51:38 +0000978SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
979 const FileEntry *FE) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000980 // The language server protocol uses zero-based line and column numbers.
981 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000982
Ilya Biryukov02d58702017-08-01 15:51:38 +0000983 const ASTContext &AST = Unit.getASTContext();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000984 const SourceManager &SourceMgr = AST.getSourceManager();
985
986 SourceLocation InputLocation =
987 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000988 if (Pos.character == 0) {
989 return InputLocation;
990 }
991
992 // This handle cases where the position is in the middle of a token or right
993 // after the end of a token. In theory we could just use GetBeginningOfToken
994 // to find the start of the token at the input position, but this doesn't
995 // work when right after the end, i.e. foo|.
996 // So try to go back by one and see if we're still inside the an identifier
997 // token. If so, Take the beginning of this token.
998 // (It should be the same identifier because you can't have two adjacent
999 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001000 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
1001 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001002 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +00001003 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +00001004 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +00001005 // getRawToken failed, just use InputLocation.
1006 return InputLocation;
1007 }
1008
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001009 if (Result.is(tok::raw_identifier)) {
1010 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov02d58702017-08-01 15:51:38 +00001011 AST.getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001012 }
1013
1014 return InputLocation;
1015}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001016} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +00001017
Ilya Biryukove5128f72017-09-20 07:24:15 +00001018std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
1019 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001020 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
1021 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1022 if (!FE)
1023 return {};
1024
1025 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
1026
1027 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
1028 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
1029 AST.getPreprocessor());
1030 index::IndexingOptions IndexOpts;
1031 IndexOpts.SystemSymbolFilter =
1032 index::IndexingOptions::SystemSymbolFilterKind::All;
1033 IndexOpts.IndexFunctionLocals = true;
1034
1035 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
1036 DeclLocationsFinder, IndexOpts);
1037
1038 return DeclLocationsFinder->takeLocations();
1039}
1040
1041void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001042 if (PendingTopLevelDecls.empty())
1043 return;
1044
1045 std::vector<const Decl *> Resolved;
1046 Resolved.reserve(PendingTopLevelDecls.size());
1047
1048 ExternalASTSource &Source = *getASTContext().getExternalSource();
1049 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
1050 // Resolve the declaration ID to an actual declaration, possibly
1051 // deserializing the declaration in the process.
1052 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1053 Resolved.push_back(D);
1054 }
1055
1056 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
1057 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1058
1059 PendingTopLevelDecls.clear();
1060}
1061
Ilya Biryukov02d58702017-08-01 15:51:38 +00001062ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001063
Ilya Biryukov02d58702017-08-01 15:51:38 +00001064ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +00001065
Ilya Biryukov02d58702017-08-01 15:51:38 +00001066ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001067 if (Action) {
1068 Action->EndSourceFile();
1069 }
1070}
1071
Ilya Biryukov02d58702017-08-01 15:51:38 +00001072ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
1073
1074const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001075 return Clang->getASTContext();
1076}
1077
Ilya Biryukov02d58702017-08-01 15:51:38 +00001078Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +00001079
Ilya Biryukov02d58702017-08-01 15:51:38 +00001080const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001081 return Clang->getPreprocessor();
1082}
1083
Ilya Biryukov02d58702017-08-01 15:51:38 +00001084ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001085 ensurePreambleDeclsDeserialized();
1086 return TopLevelDecls;
1087}
1088
Ilya Biryukov02d58702017-08-01 15:51:38 +00001089const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +00001090 return Diags;
1091}
1092
Ilya Biryukov02d58702017-08-01 15:51:38 +00001093ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang,
1094 std::unique_ptr<FrontendAction> Action,
1095 std::vector<const Decl *> TopLevelDecls,
1096 std::vector<serialization::DeclID> PendingTopLevelDecls,
1097 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001098 : Clang(std::move(Clang)), Action(std::move(Action)),
1099 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
1100 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
1101 assert(this->Clang);
1102 assert(this->Action);
1103}
1104
Ilya Biryukov02d58702017-08-01 15:51:38 +00001105ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
1106 : AST(std::move(Wrapper.AST)) {}
1107
1108ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
1109 : AST(std::move(AST)) {}
1110
1111PreambleData::PreambleData(PrecompiledPreamble Preamble,
1112 std::vector<serialization::DeclID> TopLevelDeclIDs,
1113 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov04db3682017-07-21 13:29:29 +00001114 : Preamble(std::move(Preamble)),
1115 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
Ilya Biryukov02d58702017-08-01 15:51:38 +00001116
1117std::shared_ptr<CppFile>
1118CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +00001119 std::shared_ptr<PCHContainerOperations> PCHs,
1120 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001121 return std::shared_ptr<CppFile>(
Ilya Biryukove5128f72017-09-20 07:24:15 +00001122 new CppFile(FileName, std::move(Command), std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001123}
1124
1125CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001126 std::shared_ptr<PCHContainerOperations> PCHs,
1127 clangd::Logger &Logger)
Ilya Biryukov02d58702017-08-01 15:51:38 +00001128 : FileName(FileName), Command(std::move(Command)), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +00001129 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001130
1131 std::lock_guard<std::mutex> Lock(Mutex);
1132 LatestAvailablePreamble = nullptr;
1133 PreamblePromise.set_value(nullptr);
1134 PreambleFuture = PreamblePromise.get_future();
1135
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001136 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001137 ASTFuture = ASTPromise.get_future();
1138}
1139
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001140void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001141
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001142UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001143 std::unique_lock<std::mutex> Lock(Mutex);
1144 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001145 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +00001146 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
1147 // We want to keep this invariant.
1148 if (futureIsReady(PreambleFuture)) {
1149 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
1150 PreambleFuture = PreamblePromise.get_future();
1151 }
1152 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001153 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001154 ASTFuture = ASTPromise.get_future();
1155 }
Ilya Biryukov02d58702017-08-01 15:51:38 +00001156
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001157 Lock.unlock();
1158 // Notify about changes to RebuildCounter.
1159 RebuildCond.notify_all();
1160
1161 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001162 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001163 std::unique_lock<std::mutex> Lock(That->Mutex);
1164 CppFile *This = &*That;
1165 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
1166 return !This->RebuildInProgress ||
1167 This->RebuildCounter != RequestRebuildCounter;
1168 });
1169
1170 // This computation got cancelled itself, do nothing.
1171 if (This->RebuildCounter != RequestRebuildCounter)
1172 return;
1173
1174 // Set empty results for Promises.
1175 That->PreamblePromise.set_value(nullptr);
1176 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001177 };
Ilya Biryukov02d58702017-08-01 15:51:38 +00001178}
1179
1180llvm::Optional<std::vector<DiagWithFixIts>>
1181CppFile::rebuild(StringRef NewContents,
1182 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001183 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001184}
1185
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001186UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +00001187CppFile::deferRebuild(StringRef NewContents,
1188 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1189 std::shared_ptr<const PreambleData> OldPreamble;
1190 std::shared_ptr<PCHContainerOperations> PCHs;
1191 unsigned RequestRebuildCounter;
1192 {
1193 std::unique_lock<std::mutex> Lock(Mutex);
1194 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
1195 // They will try to exit as early as possible and won't call set_value on
1196 // our promises.
1197 RequestRebuildCounter = ++this->RebuildCounter;
1198 PCHs = this->PCHs;
1199
1200 // Remember the preamble to be used during rebuild.
1201 OldPreamble = this->LatestAvailablePreamble;
1202 // Setup std::promises and std::futures for Preamble and AST. Corresponding
1203 // futures will wait until the rebuild process is finished.
1204 if (futureIsReady(this->PreambleFuture)) {
1205 this->PreamblePromise =
1206 std::promise<std::shared_ptr<const PreambleData>>();
1207 this->PreambleFuture = this->PreamblePromise.get_future();
1208 }
1209 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001210 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001211 this->ASTFuture = this->ASTPromise.get_future();
1212 }
1213 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001214 // Notify about changes to RebuildCounter.
1215 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +00001216
1217 // A helper to function to finish the rebuild. May be run on a different
1218 // thread.
1219
1220 // Don't let this CppFile die before rebuild is finished.
1221 std::shared_ptr<CppFile> That = shared_from_this();
1222 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
1223 That](std::string NewContents)
1224 -> llvm::Optional<std::vector<DiagWithFixIts>> {
1225 // Only one execution of this method is possible at a time.
1226 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
1227 // into a state for doing a rebuild.
1228 RebuildGuard Rebuild(*That, RequestRebuildCounter);
1229 if (Rebuild.wasCancelledBeforeConstruction())
1230 return llvm::None;
1231
1232 std::vector<const char *> ArgStrs;
1233 for (const auto &S : That->Command.CommandLine)
1234 ArgStrs.push_back(S.c_str());
1235
1236 VFS->setCurrentWorkingDirectory(That->Command.Directory);
1237
1238 std::unique_ptr<CompilerInvocation> CI;
1239 {
1240 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
1241 // reporting them.
1242 EmptyDiagsConsumer CommandLineDiagsConsumer;
1243 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
1244 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1245 &CommandLineDiagsConsumer, false);
1246 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
1247 }
1248 assert(CI && "Couldn't create CompilerInvocation");
1249
1250 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1251 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
1252
1253 // A helper function to rebuild the preamble or reuse the existing one. Does
1254 // not mutate any fields, only does the actual computation.
1255 auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> {
1256 auto Bounds =
1257 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
1258 if (OldPreamble && OldPreamble->Preamble.CanReuse(
1259 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
1260 return OldPreamble;
1261 }
1262
1263 std::vector<DiagWithFixIts> PreambleDiags;
1264 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
1265 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
1266 CompilerInstance::createDiagnostics(
1267 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
1268 CppFilePreambleCallbacks SerializedDeclsCollector;
1269 auto BuiltPreamble = PrecompiledPreamble::Build(
1270 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
1271 SerializedDeclsCollector);
1272
1273 if (BuiltPreamble) {
1274 return std::make_shared<PreambleData>(
1275 std::move(*BuiltPreamble),
1276 SerializedDeclsCollector.takeTopLevelDeclIDs(),
1277 std::move(PreambleDiags));
1278 } else {
1279 return nullptr;
1280 }
1281 };
1282
1283 // Compute updated Preamble.
1284 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
1285 // Publish the new Preamble.
1286 {
1287 std::lock_guard<std::mutex> Lock(That->Mutex);
1288 // We always set LatestAvailablePreamble to the new value, hoping that it
1289 // will still be usable in the further requests.
1290 That->LatestAvailablePreamble = NewPreamble;
1291 if (RequestRebuildCounter != That->RebuildCounter)
1292 return llvm::None; // Our rebuild request was cancelled, do nothing.
1293 That->PreamblePromise.set_value(NewPreamble);
1294 } // unlock Mutex
1295
1296 // Prepare the Preamble and supplementary data for rebuilding AST.
1297 const PrecompiledPreamble *PreambleForAST = nullptr;
1298 ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None;
1299 std::vector<DiagWithFixIts> Diagnostics;
1300 if (NewPreamble) {
1301 PreambleForAST = &NewPreamble->Preamble;
1302 SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs;
1303 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
1304 NewPreamble->Diags.end());
1305 }
1306
1307 // Compute updated AST.
1308 llvm::Optional<ParsedAST> NewAST =
1309 ParsedAST::Build(std::move(CI), PreambleForAST, SerializedPreambleDecls,
Ilya Biryukove5128f72017-09-20 07:24:15 +00001310 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +00001311
1312 if (NewAST) {
1313 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
1314 NewAST->getDiagnostics().end());
1315 } else {
1316 // Don't report even Preamble diagnostics if we coulnd't build AST.
1317 Diagnostics.clear();
1318 }
1319
1320 // Publish the new AST.
1321 {
1322 std::lock_guard<std::mutex> Lock(That->Mutex);
1323 if (RequestRebuildCounter != That->RebuildCounter)
1324 return Diagnostics; // Our rebuild request was cancelled, don't set
1325 // ASTPromise.
1326
Ilya Biryukov574b7532017-08-02 09:08:39 +00001327 That->ASTPromise.set_value(
1328 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +00001329 } // unlock Mutex
1330
1331 return Diagnostics;
1332 };
1333
Ilya Biryukov98a1fd72017-10-10 16:12:54 +00001334 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +00001335}
1336
1337std::shared_future<std::shared_ptr<const PreambleData>>
1338CppFile::getPreamble() const {
1339 std::lock_guard<std::mutex> Lock(Mutex);
1340 return PreambleFuture;
1341}
1342
1343std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
1344 std::lock_guard<std::mutex> Lock(Mutex);
1345 return LatestAvailablePreamble;
1346}
1347
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +00001348std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +00001349 std::lock_guard<std::mutex> Lock(Mutex);
1350 return ASTFuture;
1351}
1352
1353tooling::CompileCommand const &CppFile::getCompileCommand() const {
1354 return Command;
1355}
1356
1357CppFile::RebuildGuard::RebuildGuard(CppFile &File,
1358 unsigned RequestRebuildCounter)
1359 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
1360 std::unique_lock<std::mutex> Lock(File.Mutex);
1361 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1362 if (WasCancelledBeforeConstruction)
1363 return;
1364
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +00001365 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
1366 return !File.RebuildInProgress ||
1367 File.RebuildCounter != RequestRebuildCounter;
1368 });
Ilya Biryukov02d58702017-08-01 15:51:38 +00001369
1370 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
1371 if (WasCancelledBeforeConstruction)
1372 return;
1373
1374 File.RebuildInProgress = true;
1375}
1376
1377bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
1378 return WasCancelledBeforeConstruction;
1379}
1380
1381CppFile::RebuildGuard::~RebuildGuard() {
1382 if (WasCancelledBeforeConstruction)
1383 return;
1384
1385 std::unique_lock<std::mutex> Lock(File.Mutex);
1386 assert(File.RebuildInProgress);
1387 File.RebuildInProgress = false;
1388
1389 if (File.RebuildCounter == RequestRebuildCounter) {
1390 // Our rebuild request was successful.
1391 assert(futureIsReady(File.ASTFuture));
1392 assert(futureIsReady(File.PreambleFuture));
1393 } else {
1394 // Our rebuild request was cancelled, because further reparse was requested.
1395 assert(!futureIsReady(File.ASTFuture));
1396 assert(!futureIsReady(File.PreambleFuture));
1397 }
1398
1399 Lock.unlock();
1400 File.RebuildCond.notify_all();
1401}