blob: 43b5b7dd7dd5192f5ca660ddd062c71aa8820ee5 [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 Biryukov38d79772017-05-16 09:38:59 +000012#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000014#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000015#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000016#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000017#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Lex/Lexer.h"
19#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000021#include "clang/Lex/PreprocessorOptions.h"
22#include "clang/Sema/Sema.h"
23#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000024#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000025#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000028#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000029
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
31
Ilya Biryukov38d79772017-05-16 09:38:59 +000032using namespace clang::clangd;
33using namespace clang;
34
Ilya Biryukov04db3682017-07-21 13:29:29 +000035namespace {
36
37class DeclTrackingASTConsumer : public ASTConsumer {
38public:
39 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
40 : TopLevelDecls(TopLevelDecls) {}
41
42 bool HandleTopLevelDecl(DeclGroupRef DG) override {
43 for (const Decl *D : DG) {
44 // ObjCMethodDecl are not actually top-level decls.
45 if (isa<ObjCMethodDecl>(D))
46 continue;
47
48 TopLevelDecls.push_back(D);
49 }
50 return true;
51 }
52
53private:
54 std::vector<const Decl *> &TopLevelDecls;
55};
56
57class ClangdFrontendAction : public SyntaxOnlyAction {
58public:
59 std::vector<const Decl *> takeTopLevelDecls() {
60 return std::move(TopLevelDecls);
61 }
62
63protected:
64 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
65 StringRef InFile) override {
66 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
67 }
68
69private:
70 std::vector<const Decl *> TopLevelDecls;
71};
72
73class ClangdUnitPreambleCallbacks : public PreambleCallbacks {
74public:
75 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
76 return std::move(TopLevelDeclIDs);
77 }
78
79 void AfterPCHEmitted(ASTWriter &Writer) override {
80 TopLevelDeclIDs.reserve(TopLevelDecls.size());
81 for (Decl *D : TopLevelDecls) {
82 // Invalid top-level decls may not have been serialized.
83 if (D->isInvalidDecl())
84 continue;
85 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
86 }
87 }
88
89 void HandleTopLevelDecl(DeclGroupRef DG) override {
90 for (Decl *D : DG) {
91 if (isa<ObjCMethodDecl>(D))
92 continue;
93 TopLevelDecls.push_back(D);
94 }
95 }
96
97private:
98 std::vector<Decl *> TopLevelDecls;
99 std::vector<serialization::DeclID> TopLevelDeclIDs;
100};
101
102/// Convert from clang diagnostic level to LSP severity.
103static int getSeverity(DiagnosticsEngine::Level L) {
104 switch (L) {
105 case DiagnosticsEngine::Remark:
106 return 4;
107 case DiagnosticsEngine::Note:
108 return 3;
109 case DiagnosticsEngine::Warning:
110 return 2;
111 case DiagnosticsEngine::Fatal:
112 case DiagnosticsEngine::Error:
113 return 1;
114 case DiagnosticsEngine::Ignored:
115 return 0;
116 }
117 llvm_unreachable("Unknown diagnostic level!");
118}
119
120llvm::Optional<DiagWithFixIts> toClangdDiag(StoredDiagnostic D) {
121 auto Location = D.getLocation();
122 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
123 return llvm::None;
124
125 Position P;
126 P.line = Location.getSpellingLineNumber() - 1;
127 P.character = Location.getSpellingColumnNumber();
128 Range R = {P, P};
129 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
130
131 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
132 for (const FixItHint &Fix : D.getFixIts()) {
133 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
134 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
135 }
136 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
137}
138
139class StoreDiagsConsumer : public DiagnosticConsumer {
140public:
141 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
142
143 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
144 const clang::Diagnostic &Info) override {
145 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
146
147 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
148 Output.push_back(std::move(*convertedDiag));
149 }
150
151private:
152 std::vector<DiagWithFixIts> &Output;
153};
154
155class EmptyDiagsConsumer : public DiagnosticConsumer {
156public:
157 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
158 const clang::Diagnostic &Info) override {}
159};
160
161std::unique_ptr<CompilerInvocation>
162createCompilerInvocation(ArrayRef<const char *> ArgList,
163 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
164 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
165 auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags),
166 std::move(VFS));
167 // We rely on CompilerInstance to manage the resource (i.e. free them on
168 // EndSourceFile), but that won't happen if DisableFree is set to true.
169 // Since createInvocationFromCommandLine sets it to true, we have to override
170 // it.
171 CI->getFrontendOpts().DisableFree = false;
172 return CI;
173}
174
175/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
176/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
177/// null. Note that vfs::FileSystem inside returned instance may differ from \p
178/// VFS if additional file remapping were set in command-line arguments.
179/// On some errors, returns null. When non-null value is returned, it's expected
180/// to be consumed by the FrontendAction as it will have a pointer to the \p
181/// Buffer that will only be deleted if BeginSourceFile is called.
182std::unique_ptr<CompilerInstance>
183prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
184 const PrecompiledPreamble *Preamble,
185 std::unique_ptr<llvm::MemoryBuffer> Buffer,
186 std::shared_ptr<PCHContainerOperations> PCHs,
187 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
188 DiagnosticConsumer &DiagsClient) {
189 assert(VFS && "VFS is null");
190 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
191 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
192 "of ContentsBuffer");
193
194 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
195 // sure it will be released if no error is emitted.
196 if (Preamble) {
197 Preamble->AddImplicitPreamble(*CI, Buffer.get());
198 } else {
199 CI->getPreprocessorOpts().addRemappedFile(
200 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
201 }
202
203 auto Clang = llvm::make_unique<CompilerInstance>(PCHs);
204 Clang->setInvocation(std::move(CI));
205 Clang->createDiagnostics(&DiagsClient, false);
206
207 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
208 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
209 VFS = VFSWithRemapping;
210 Clang->setVirtualFileSystem(VFS);
211
212 Clang->setTarget(TargetInfo::CreateTargetInfo(
213 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
214 if (!Clang->hasTarget())
215 return nullptr;
216
217 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
218 // release it.
219 Buffer.release();
220 return Clang;
221}
222
223} // namespace
224
Ilya Biryukov38d79772017-05-16 09:38:59 +0000225ClangdUnit::ClangdUnit(PathRef FileName, StringRef Contents,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000226 StringRef ResourceDir,
Ilya Biryukov38d79772017-05-16 09:38:59 +0000227 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000228 std::vector<tooling::CompileCommand> Commands,
229 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Ilya Biryukov38d79772017-05-16 09:38:59 +0000230 : FileName(FileName), PCHs(PCHs) {
231 assert(!Commands.empty() && "No compile commands provided");
232
233 // Inject the resource dir.
234 // FIXME: Don't overwrite it if it's already there.
Kirill Bobyrev46213872017-06-28 20:57:28 +0000235 Commands.front().CommandLine.push_back("-resource-dir=" +
236 std::string(ResourceDir));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000237
Ilya Biryukov04db3682017-07-21 13:29:29 +0000238 Command = std::move(Commands.front());
239 reparse(Contents, VFS);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240}
241
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000242void ClangdUnit::reparse(StringRef Contents,
243 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000244 std::vector<const char *> ArgStrs;
245 for (const auto &S : Command.CommandLine)
246 ArgStrs.push_back(S.c_str());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000247
Ilya Biryukov04db3682017-07-21 13:29:29 +0000248 std::unique_ptr<CompilerInvocation> CI;
249 {
250 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
251 // reporting them.
252 EmptyDiagsConsumer CommandLineDiagsConsumer;
253 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
254 CompilerInstance::createDiagnostics(new DiagnosticOptions,
255 &CommandLineDiagsConsumer, false);
256 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
257 }
258 assert(CI && "Couldn't create CompilerInvocation");
259
260 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
261 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
262
263 // Rebuild the preamble if it is missing or can not be reused.
264 auto Bounds =
265 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
266 if (!Preamble || !Preamble->Preamble.CanReuse(*CI, ContentsBuffer.get(),
267 Bounds, VFS.get())) {
268 std::vector<DiagWithFixIts> PreambleDiags;
269 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
270 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
271 CompilerInstance::createDiagnostics(
272 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
273 ClangdUnitPreambleCallbacks SerializedDeclsCollector;
274 auto BuiltPreamble = PrecompiledPreamble::Build(
275 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
276 SerializedDeclsCollector);
277 if (BuiltPreamble)
278 Preamble = PreambleData(std::move(*BuiltPreamble),
279 SerializedDeclsCollector.takeTopLevelDeclIDs(),
280 std::move(PreambleDiags));
281 }
282 Unit = ParsedAST::Build(
283 std::move(CI), Preamble ? &Preamble->Preamble : nullptr,
284 Preamble ? llvm::makeArrayRef(Preamble->TopLevelDeclIDs) : llvm::None,
285 std::move(ContentsBuffer), PCHs, VFS);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000286}
287
288namespace {
289
290CompletionItemKind getKind(CXCursorKind K) {
291 switch (K) {
292 case CXCursor_MacroInstantiation:
293 case CXCursor_MacroDefinition:
294 return CompletionItemKind::Text;
295 case CXCursor_CXXMethod:
296 return CompletionItemKind::Method;
297 case CXCursor_FunctionDecl:
298 case CXCursor_FunctionTemplate:
299 return CompletionItemKind::Function;
300 case CXCursor_Constructor:
301 case CXCursor_Destructor:
302 return CompletionItemKind::Constructor;
303 case CXCursor_FieldDecl:
304 return CompletionItemKind::Field;
305 case CXCursor_VarDecl:
306 case CXCursor_ParmDecl:
307 return CompletionItemKind::Variable;
308 case CXCursor_ClassDecl:
309 case CXCursor_StructDecl:
310 case CXCursor_UnionDecl:
311 case CXCursor_ClassTemplate:
312 case CXCursor_ClassTemplatePartialSpecialization:
313 return CompletionItemKind::Class;
314 case CXCursor_Namespace:
315 case CXCursor_NamespaceAlias:
316 case CXCursor_NamespaceRef:
317 return CompletionItemKind::Module;
318 case CXCursor_EnumConstantDecl:
319 return CompletionItemKind::Value;
320 case CXCursor_EnumDecl:
321 return CompletionItemKind::Enum;
322 case CXCursor_TypeAliasDecl:
323 case CXCursor_TypeAliasTemplateDecl:
324 case CXCursor_TypedefDecl:
325 case CXCursor_MemberRef:
326 case CXCursor_TypeRef:
327 return CompletionItemKind::Reference;
328 default:
329 return CompletionItemKind::Missing;
330 }
331}
332
333class CompletionItemsCollector : public CodeCompleteConsumer {
334 std::vector<CompletionItem> *Items;
335 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
336 CodeCompletionTUInfo CCTUInfo;
337
338public:
339 CompletionItemsCollector(std::vector<CompletionItem> *Items,
340 const CodeCompleteOptions &CodeCompleteOpts)
341 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
342 Items(Items),
343 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
344 CCTUInfo(Allocator) {}
345
346 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
347 CodeCompletionResult *Results,
348 unsigned NumResults) override {
349 for (unsigned I = 0; I != NumResults; ++I) {
350 CodeCompletionResult &Result = Results[I];
351 CodeCompletionString *CCS = Result.CreateCodeCompletionString(
352 S, Context, *Allocator, CCTUInfo,
353 CodeCompleteOpts.IncludeBriefComments);
354 if (CCS) {
355 CompletionItem Item;
Krasimir Georgieve6035a52017-06-08 15:11:51 +0000356 for (CodeCompletionString::Chunk C : *CCS) {
357 switch (C.Kind) {
358 case CodeCompletionString::CK_ResultType:
359 Item.detail = C.Text;
360 break;
361 case CodeCompletionString::CK_Optional:
362 break;
363 default:
364 Item.label += C.Text;
365 break;
366 }
367 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000368 assert(CCS->getTypedText());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000369 Item.kind = getKind(Result.CursorKind);
Krasimir Georgieva1de3c92017-06-15 09:11:57 +0000370 // Priority is a 16-bit integer, hence at most 5 digits.
371 // Since identifiers with higher priority need to come first,
372 // we subtract the priority from 99999.
373 // For example, the sort text of the identifier 'a' with priority 35
374 // is 99964a.
375 assert(CCS->getPriority() < 99999 && "Expecting code completion result "
376 "priority to have at most "
377 "5-digits");
378 llvm::raw_string_ostream(Item.sortText) << llvm::format(
379 "%05d%s", 99999 - CCS->getPriority(), CCS->getTypedText());
380 Item.insertText = Item.filterText = CCS->getTypedText();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000381 if (CCS->getBriefComment())
382 Item.documentation = CCS->getBriefComment();
383 Items->push_back(std::move(Item));
384 }
385 }
386 }
387
388 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
389
390 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
391};
392} // namespace
393
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000394std::vector<CompletionItem>
395ClangdUnit::codeComplete(StringRef Contents, Position Pos,
396 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000397 std::vector<const char *> ArgStrs;
398 for (const auto &S : Command.CommandLine)
399 ArgStrs.push_back(S.c_str());
400
401 std::unique_ptr<CompilerInvocation> CI;
402 EmptyDiagsConsumer DummyDiagsConsumer;
403 {
404 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
405 CompilerInstance::createDiagnostics(new DiagnosticOptions,
406 &DummyDiagsConsumer, false);
407 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
408 }
409 assert(CI && "Couldn't create CompilerInvocation");
410
411 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
412 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
413
414 // Attempt to reuse the PCH from precompiled preamble, if it was built.
415 const PrecompiledPreamble *PreambleForCompletion = nullptr;
416 if (Preamble) {
417 auto Bounds =
418 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
419 if (Preamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
420 VFS.get()))
421 PreambleForCompletion = &Preamble->Preamble;
422 }
423
424 auto Clang = prepareCompilerInstance(std::move(CI), PreambleForCompletion,
425 std::move(ContentsBuffer), PCHs, VFS,
426 DummyDiagsConsumer);
427 auto &DiagOpts = Clang->getDiagnosticOpts();
428 DiagOpts.IgnoreWarnings = true;
429
430 auto &FrontendOpts = Clang->getFrontendOpts();
431 FrontendOpts.SkipFunctionBodies = true;
432
433 FrontendOpts.CodeCompleteOpts.IncludeGlobals = true;
434 // we don't handle code patterns properly yet, disable them.
435 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = false;
436 FrontendOpts.CodeCompleteOpts.IncludeMacros = true;
437 FrontendOpts.CodeCompleteOpts.IncludeBriefComments = true;
438
439 FrontendOpts.CodeCompletionAt.FileName = FileName;
440 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
441 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
442
Ilya Biryukov38d79772017-05-16 09:38:59 +0000443 std::vector<CompletionItem> Items;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000444 Clang->setCodeCompletionConsumer(
445 new CompletionItemsCollector(&Items, FrontendOpts.CodeCompleteOpts));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000446
Ilya Biryukov04db3682017-07-21 13:29:29 +0000447 SyntaxOnlyAction Action;
448 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
449 // FIXME(ibiryukov): log errors
450 return Items;
451 }
452 if (!Action.Execute()) {
453 // FIXME(ibiryukov): log errors
454 }
455 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000456
Ilya Biryukov38d79772017-05-16 09:38:59 +0000457 return Items;
458}
459
Ilya Biryukov38d79772017-05-16 09:38:59 +0000460std::vector<DiagWithFixIts> ClangdUnit::getLocalDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000461 if (!Unit)
462 return {}; // Parsing failed.
Ilya Biryukov38d79772017-05-16 09:38:59 +0000463
Ilya Biryukov04db3682017-07-21 13:29:29 +0000464 std::vector<DiagWithFixIts> Result;
465 auto PreambleDiagsSize = Preamble ? Preamble->Diags.size() : 0;
466 const auto &Diags = Unit->getDiagnostics();
467 Result.reserve(PreambleDiagsSize + Diags.size());
468
469 if (Preamble)
470 Result.insert(Result.end(), Preamble->Diags.begin(), Preamble->Diags.end());
471 Result.insert(Result.end(), Diags.begin(), Diags.end());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000472 return Result;
473}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000474
475void ClangdUnit::dumpAST(llvm::raw_ostream &OS) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000476 if (!Unit) {
477 OS << "<no-ast-in-clang>";
478 return; // Parsing failed.
479 }
Ilya Biryukovf01af682017-05-23 13:42:59 +0000480 Unit->getASTContext().getTranslationUnitDecl()->dump(OS, true);
481}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000482
Ilya Biryukov04db3682017-07-21 13:29:29 +0000483llvm::Optional<ClangdUnit::ParsedAST>
484ClangdUnit::ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
485 const PrecompiledPreamble *Preamble,
486 ArrayRef<serialization::DeclID> PreambleDeclIDs,
487 std::unique_ptr<llvm::MemoryBuffer> Buffer,
488 std::shared_ptr<PCHContainerOperations> PCHs,
489 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
490
491 std::vector<DiagWithFixIts> ASTDiags;
492 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
493
494 auto Clang =
495 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
496 VFS, /*ref*/ UnitDiagsConsumer);
497
498 // Recover resources if we crash before exiting this method.
499 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
500 Clang.get());
501
502 auto Action = llvm::make_unique<ClangdFrontendAction>();
503 if (!Action->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
504 // FIXME(ibiryukov): log error
505 return llvm::None;
506 }
507 if (!Action->Execute()) {
508 // FIXME(ibiryukov): log error
509 }
510
511 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
512 // has a longer lifetime.
513 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
514
515 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
516 std::vector<serialization::DeclID> PendingDecls;
517 if (Preamble) {
518 PendingDecls.reserve(PreambleDeclIDs.size());
519 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
520 PreambleDeclIDs.end());
521 }
522
523 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
524 std::move(PendingDecls), std::move(ASTDiags));
525}
526
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000527namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000528
529SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
530 const FileEntry *FE,
531 unsigned Offset) {
532 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
533 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
534}
535
536SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
537 const FileEntry *FE, Position Pos) {
538 SourceLocation InputLoc =
539 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
540 return Mgr.getMacroArgExpandedLocation(InputLoc);
541}
542
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000543/// Finds declarations locations that a given source location refers to.
544class DeclarationLocationsFinder : public index::IndexDataConsumer {
545 std::vector<Location> DeclarationLocations;
546 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000547 const ASTContext &AST;
548 Preprocessor &PP;
549
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000550public:
551 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000552 const SourceLocation &SearchedLocation,
553 ASTContext &AST, Preprocessor &PP)
554 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000555
556 std::vector<Location> takeLocations() {
557 // Don't keep the same location multiple times.
558 // This can happen when nodes in the AST are visited twice.
559 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000560 auto last =
561 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000562 DeclarationLocations.erase(last, DeclarationLocations.end());
563 return std::move(DeclarationLocations);
564 }
565
566 bool handleDeclOccurence(const Decl* D, index::SymbolRoleSet Roles,
567 ArrayRef<index::SymbolRelation> Relations, FileID FID, unsigned Offset,
568 index::IndexDataConsumer::ASTNodeInfo ASTNode) override
569 {
570 if (isSearchedLocation(FID, Offset)) {
571 addDeclarationLocation(D->getSourceRange());
572 }
573 return true;
574 }
575
576private:
577 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000578 const SourceManager &SourceMgr = AST.getSourceManager();
579 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
580 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000581 }
582
Ilya Biryukov04db3682017-07-21 13:29:29 +0000583 void addDeclarationLocation(const SourceRange &ValSourceRange) {
584 const SourceManager &SourceMgr = AST.getSourceManager();
585 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000586 SourceLocation LocStart = ValSourceRange.getBegin();
587 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000588 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000589 Position Begin;
590 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
591 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
592 Position End;
593 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
594 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
595 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000596 Location L;
597 L.uri = URI::fromFile(
598 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
599 L.range = R;
600 DeclarationLocations.push_back(L);
601 }
602
Kirill Bobyrev46213872017-06-28 20:57:28 +0000603 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000604 // Also handle possible macro at the searched location.
605 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000606 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
607 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000608 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000609 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000610 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000611 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000612 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
613 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000614 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000615 // Get the definition just before the searched location so that a macro
616 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000617 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
618 AST.getSourceManager(),
619 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000620 DecLoc.second - 1);
621 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000622 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
623 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000624 if (MacroInf) {
625 addDeclarationLocation(
626 SourceRange(MacroInf->getDefinitionLoc(),
627 MacroInf->getDefinitionEndLoc()));
628 }
629 }
630 }
631 }
632};
633} // namespace
634
635std::vector<Location> ClangdUnit::findDefinitions(Position Pos) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000636 if (!Unit)
637 return {}; // Parsing failed.
638
639 const SourceManager &SourceMgr = Unit->getASTContext().getSourceManager();
640 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000641 if (!FE)
642 return {};
643
644 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(Pos, FE);
645
Kirill Bobyrev46213872017-06-28 20:57:28 +0000646 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
Ilya Biryukov04db3682017-07-21 13:29:29 +0000647 llvm::errs(), SourceLocationBeg, Unit->getASTContext(),
648 Unit->getPreprocessor());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000649 index::IndexingOptions IndexOpts;
650 IndexOpts.SystemSymbolFilter =
651 index::IndexingOptions::SystemSymbolFilterKind::All;
652 IndexOpts.IndexFunctionLocals = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000653
654 indexTopLevelDecls(Unit->getASTContext(), Unit->getTopLevelDecls(),
655 DeclLocationsFinder, IndexOpts);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000656
657 return DeclLocationsFinder->takeLocations();
658}
659
660SourceLocation ClangdUnit::getBeginningOfIdentifier(const Position &Pos,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000661 const FileEntry *FE) const {
662
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000663 // The language server protocol uses zero-based line and column numbers.
664 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000665
Ilya Biryukov04db3682017-07-21 13:29:29 +0000666 const ASTContext &AST = Unit->getASTContext();
667 const SourceManager &SourceMgr = AST.getSourceManager();
668
669 SourceLocation InputLocation =
670 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000671 if (Pos.character == 0) {
672 return InputLocation;
673 }
674
675 // This handle cases where the position is in the middle of a token or right
676 // after the end of a token. In theory we could just use GetBeginningOfToken
677 // to find the start of the token at the input position, but this doesn't
678 // work when right after the end, i.e. foo|.
679 // So try to go back by one and see if we're still inside the an identifier
680 // token. If so, Take the beginning of this token.
681 // (It should be the same identifier because you can't have two adjacent
682 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000683 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
684 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000685 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000686 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000687 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000688 // getRawToken failed, just use InputLocation.
689 return InputLocation;
690 }
691
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000692 if (Result.is(tok::raw_identifier)) {
693 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000694 Unit->getASTContext().getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000695 }
696
697 return InputLocation;
698}
Ilya Biryukov04db3682017-07-21 13:29:29 +0000699
700void ClangdUnit::ParsedAST::ensurePreambleDeclsDeserialized() {
701 if (PendingTopLevelDecls.empty())
702 return;
703
704 std::vector<const Decl *> Resolved;
705 Resolved.reserve(PendingTopLevelDecls.size());
706
707 ExternalASTSource &Source = *getASTContext().getExternalSource();
708 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
709 // Resolve the declaration ID to an actual declaration, possibly
710 // deserializing the declaration in the process.
711 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
712 Resolved.push_back(D);
713 }
714
715 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
716 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
717
718 PendingTopLevelDecls.clear();
719}
720
721ClangdUnit::ParsedAST::ParsedAST(ParsedAST &&Other) = default;
722
723ClangdUnit::ParsedAST &ClangdUnit::ParsedAST::
724operator=(ParsedAST &&Other) = default;
725
726ClangdUnit::ParsedAST::~ParsedAST() {
727 if (Action) {
728 Action->EndSourceFile();
729 }
730}
731
732ASTContext &ClangdUnit::ParsedAST::getASTContext() {
733 return Clang->getASTContext();
734}
735
736const ASTContext &ClangdUnit::ParsedAST::getASTContext() const {
737 return Clang->getASTContext();
738}
739
740Preprocessor &ClangdUnit::ParsedAST::getPreprocessor() {
741 return Clang->getPreprocessor();
742}
743
744const Preprocessor &ClangdUnit::ParsedAST::getPreprocessor() const {
745 return Clang->getPreprocessor();
746}
747
748ArrayRef<const Decl *> ClangdUnit::ParsedAST::getTopLevelDecls() {
749 ensurePreambleDeclsDeserialized();
750 return TopLevelDecls;
751}
752
753const std::vector<DiagWithFixIts> &
754ClangdUnit::ParsedAST::getDiagnostics() const {
755 return Diags;
756}
757
758ClangdUnit::ParsedAST::ParsedAST(
759 std::unique_ptr<CompilerInstance> Clang,
760 std::unique_ptr<FrontendAction> Action,
761 std::vector<const Decl *> TopLevelDecls,
762 std::vector<serialization::DeclID> PendingTopLevelDecls,
763 std::vector<DiagWithFixIts> Diags)
764 : Clang(std::move(Clang)), Action(std::move(Action)),
765 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
766 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
767 assert(this->Clang);
768 assert(this->Action);
769}
770
771ClangdUnit::PreambleData::PreambleData(
772 PrecompiledPreamble Preamble,
773 std::vector<serialization::DeclID> TopLevelDeclIDs,
774 std::vector<DiagWithFixIts> Diags)
775 : Preamble(std::move(Preamble)),
776 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}