blob: 35765b7823ba44b274de916275bc2ebf7759cac3 [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
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000248 VFS->setCurrentWorkingDirectory(Command.Directory);
249
Ilya Biryukov04db3682017-07-21 13:29:29 +0000250 std::unique_ptr<CompilerInvocation> CI;
251 {
252 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
253 // reporting them.
254 EmptyDiagsConsumer CommandLineDiagsConsumer;
255 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
256 CompilerInstance::createDiagnostics(new DiagnosticOptions,
257 &CommandLineDiagsConsumer, false);
258 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
259 }
260 assert(CI && "Couldn't create CompilerInvocation");
261
262 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
263 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
264
265 // Rebuild the preamble if it is missing or can not be reused.
266 auto Bounds =
267 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
268 if (!Preamble || !Preamble->Preamble.CanReuse(*CI, ContentsBuffer.get(),
269 Bounds, VFS.get())) {
270 std::vector<DiagWithFixIts> PreambleDiags;
271 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
272 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
273 CompilerInstance::createDiagnostics(
274 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
275 ClangdUnitPreambleCallbacks SerializedDeclsCollector;
276 auto BuiltPreamble = PrecompiledPreamble::Build(
277 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
278 SerializedDeclsCollector);
279 if (BuiltPreamble)
280 Preamble = PreambleData(std::move(*BuiltPreamble),
281 SerializedDeclsCollector.takeTopLevelDeclIDs(),
282 std::move(PreambleDiags));
283 }
284 Unit = ParsedAST::Build(
285 std::move(CI), Preamble ? &Preamble->Preamble : nullptr,
286 Preamble ? llvm::makeArrayRef(Preamble->TopLevelDeclIDs) : llvm::None,
287 std::move(ContentsBuffer), PCHs, VFS);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000288}
289
290namespace {
291
292CompletionItemKind getKind(CXCursorKind K) {
293 switch (K) {
294 case CXCursor_MacroInstantiation:
295 case CXCursor_MacroDefinition:
296 return CompletionItemKind::Text;
297 case CXCursor_CXXMethod:
298 return CompletionItemKind::Method;
299 case CXCursor_FunctionDecl:
300 case CXCursor_FunctionTemplate:
301 return CompletionItemKind::Function;
302 case CXCursor_Constructor:
303 case CXCursor_Destructor:
304 return CompletionItemKind::Constructor;
305 case CXCursor_FieldDecl:
306 return CompletionItemKind::Field;
307 case CXCursor_VarDecl:
308 case CXCursor_ParmDecl:
309 return CompletionItemKind::Variable;
310 case CXCursor_ClassDecl:
311 case CXCursor_StructDecl:
312 case CXCursor_UnionDecl:
313 case CXCursor_ClassTemplate:
314 case CXCursor_ClassTemplatePartialSpecialization:
315 return CompletionItemKind::Class;
316 case CXCursor_Namespace:
317 case CXCursor_NamespaceAlias:
318 case CXCursor_NamespaceRef:
319 return CompletionItemKind::Module;
320 case CXCursor_EnumConstantDecl:
321 return CompletionItemKind::Value;
322 case CXCursor_EnumDecl:
323 return CompletionItemKind::Enum;
324 case CXCursor_TypeAliasDecl:
325 case CXCursor_TypeAliasTemplateDecl:
326 case CXCursor_TypedefDecl:
327 case CXCursor_MemberRef:
328 case CXCursor_TypeRef:
329 return CompletionItemKind::Reference;
330 default:
331 return CompletionItemKind::Missing;
332 }
333}
334
335class CompletionItemsCollector : public CodeCompleteConsumer {
336 std::vector<CompletionItem> *Items;
337 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
338 CodeCompletionTUInfo CCTUInfo;
339
340public:
341 CompletionItemsCollector(std::vector<CompletionItem> *Items,
342 const CodeCompleteOptions &CodeCompleteOpts)
343 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
344 Items(Items),
345 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
346 CCTUInfo(Allocator) {}
347
348 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
349 CodeCompletionResult *Results,
350 unsigned NumResults) override {
351 for (unsigned I = 0; I != NumResults; ++I) {
352 CodeCompletionResult &Result = Results[I];
353 CodeCompletionString *CCS = Result.CreateCodeCompletionString(
354 S, Context, *Allocator, CCTUInfo,
355 CodeCompleteOpts.IncludeBriefComments);
356 if (CCS) {
357 CompletionItem Item;
Krasimir Georgieve6035a52017-06-08 15:11:51 +0000358 for (CodeCompletionString::Chunk C : *CCS) {
359 switch (C.Kind) {
360 case CodeCompletionString::CK_ResultType:
361 Item.detail = C.Text;
362 break;
363 case CodeCompletionString::CK_Optional:
364 break;
365 default:
366 Item.label += C.Text;
367 break;
368 }
369 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000370 assert(CCS->getTypedText());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000371 Item.kind = getKind(Result.CursorKind);
Krasimir Georgieva1de3c92017-06-15 09:11:57 +0000372 // Priority is a 16-bit integer, hence at most 5 digits.
373 // Since identifiers with higher priority need to come first,
374 // we subtract the priority from 99999.
375 // For example, the sort text of the identifier 'a' with priority 35
376 // is 99964a.
377 assert(CCS->getPriority() < 99999 && "Expecting code completion result "
378 "priority to have at most "
379 "5-digits");
380 llvm::raw_string_ostream(Item.sortText) << llvm::format(
381 "%05d%s", 99999 - CCS->getPriority(), CCS->getTypedText());
382 Item.insertText = Item.filterText = CCS->getTypedText();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000383 if (CCS->getBriefComment())
384 Item.documentation = CCS->getBriefComment();
385 Items->push_back(std::move(Item));
386 }
387 }
388 }
389
390 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
391
392 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
393};
394} // namespace
395
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000396std::vector<CompletionItem>
397ClangdUnit::codeComplete(StringRef Contents, Position Pos,
398 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000399 std::vector<const char *> ArgStrs;
400 for (const auto &S : Command.CommandLine)
401 ArgStrs.push_back(S.c_str());
402
Krasimir Georgieve4130d52017-07-25 11:37:43 +0000403 VFS->setCurrentWorkingDirectory(Command.Directory);
404
Ilya Biryukov04db3682017-07-21 13:29:29 +0000405 std::unique_ptr<CompilerInvocation> CI;
406 EmptyDiagsConsumer DummyDiagsConsumer;
407 {
408 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
409 CompilerInstance::createDiagnostics(new DiagnosticOptions,
410 &DummyDiagsConsumer, false);
411 CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS);
412 }
413 assert(CI && "Couldn't create CompilerInvocation");
414
415 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
416 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName);
417
418 // Attempt to reuse the PCH from precompiled preamble, if it was built.
419 const PrecompiledPreamble *PreambleForCompletion = nullptr;
420 if (Preamble) {
421 auto Bounds =
422 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
423 if (Preamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
424 VFS.get()))
425 PreambleForCompletion = &Preamble->Preamble;
426 }
427
428 auto Clang = prepareCompilerInstance(std::move(CI), PreambleForCompletion,
429 std::move(ContentsBuffer), PCHs, VFS,
430 DummyDiagsConsumer);
431 auto &DiagOpts = Clang->getDiagnosticOpts();
432 DiagOpts.IgnoreWarnings = true;
433
434 auto &FrontendOpts = Clang->getFrontendOpts();
435 FrontendOpts.SkipFunctionBodies = true;
436
437 FrontendOpts.CodeCompleteOpts.IncludeGlobals = true;
438 // we don't handle code patterns properly yet, disable them.
439 FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = false;
440 FrontendOpts.CodeCompleteOpts.IncludeMacros = true;
441 FrontendOpts.CodeCompleteOpts.IncludeBriefComments = true;
442
443 FrontendOpts.CodeCompletionAt.FileName = FileName;
444 FrontendOpts.CodeCompletionAt.Line = Pos.line + 1;
445 FrontendOpts.CodeCompletionAt.Column = Pos.character + 1;
446
Ilya Biryukov38d79772017-05-16 09:38:59 +0000447 std::vector<CompletionItem> Items;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000448 Clang->setCodeCompletionConsumer(
449 new CompletionItemsCollector(&Items, FrontendOpts.CodeCompleteOpts));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000450
Ilya Biryukov04db3682017-07-21 13:29:29 +0000451 SyntaxOnlyAction Action;
452 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
453 // FIXME(ibiryukov): log errors
454 return Items;
455 }
456 if (!Action.Execute()) {
457 // FIXME(ibiryukov): log errors
458 }
459 Action.EndSourceFile();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000460
Ilya Biryukov38d79772017-05-16 09:38:59 +0000461 return Items;
462}
463
Ilya Biryukov38d79772017-05-16 09:38:59 +0000464std::vector<DiagWithFixIts> ClangdUnit::getLocalDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000465 if (!Unit)
466 return {}; // Parsing failed.
Ilya Biryukov38d79772017-05-16 09:38:59 +0000467
Ilya Biryukov04db3682017-07-21 13:29:29 +0000468 std::vector<DiagWithFixIts> Result;
469 auto PreambleDiagsSize = Preamble ? Preamble->Diags.size() : 0;
470 const auto &Diags = Unit->getDiagnostics();
471 Result.reserve(PreambleDiagsSize + Diags.size());
472
473 if (Preamble)
474 Result.insert(Result.end(), Preamble->Diags.begin(), Preamble->Diags.end());
475 Result.insert(Result.end(), Diags.begin(), Diags.end());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000476 return Result;
477}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000478
479void ClangdUnit::dumpAST(llvm::raw_ostream &OS) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000480 if (!Unit) {
481 OS << "<no-ast-in-clang>";
482 return; // Parsing failed.
483 }
Ilya Biryukovf01af682017-05-23 13:42:59 +0000484 Unit->getASTContext().getTranslationUnitDecl()->dump(OS, true);
485}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000486
Ilya Biryukov04db3682017-07-21 13:29:29 +0000487llvm::Optional<ClangdUnit::ParsedAST>
488ClangdUnit::ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
489 const PrecompiledPreamble *Preamble,
490 ArrayRef<serialization::DeclID> PreambleDeclIDs,
491 std::unique_ptr<llvm::MemoryBuffer> Buffer,
492 std::shared_ptr<PCHContainerOperations> PCHs,
493 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
494
495 std::vector<DiagWithFixIts> ASTDiags;
496 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
497
498 auto Clang =
499 prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs,
500 VFS, /*ref*/ UnitDiagsConsumer);
501
502 // Recover resources if we crash before exiting this method.
503 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
504 Clang.get());
505
506 auto Action = llvm::make_unique<ClangdFrontendAction>();
507 if (!Action->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
508 // FIXME(ibiryukov): log error
509 return llvm::None;
510 }
511 if (!Action->Execute()) {
512 // FIXME(ibiryukov): log error
513 }
514
515 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
516 // has a longer lifetime.
517 Clang->getDiagnostics().setClient(new EmptyDiagsConsumer);
518
519 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
520 std::vector<serialization::DeclID> PendingDecls;
521 if (Preamble) {
522 PendingDecls.reserve(PreambleDeclIDs.size());
523 PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(),
524 PreambleDeclIDs.end());
525 }
526
527 return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls),
528 std::move(PendingDecls), std::move(ASTDiags));
529}
530
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000531namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000532
533SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
534 const FileEntry *FE,
535 unsigned Offset) {
536 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
537 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
538}
539
540SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
541 const FileEntry *FE, Position Pos) {
542 SourceLocation InputLoc =
543 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
544 return Mgr.getMacroArgExpandedLocation(InputLoc);
545}
546
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000547/// Finds declarations locations that a given source location refers to.
548class DeclarationLocationsFinder : public index::IndexDataConsumer {
549 std::vector<Location> DeclarationLocations;
550 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000551 const ASTContext &AST;
552 Preprocessor &PP;
553
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000554public:
555 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000556 const SourceLocation &SearchedLocation,
557 ASTContext &AST, Preprocessor &PP)
558 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000559
560 std::vector<Location> takeLocations() {
561 // Don't keep the same location multiple times.
562 // This can happen when nodes in the AST are visited twice.
563 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000564 auto last =
565 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000566 DeclarationLocations.erase(last, DeclarationLocations.end());
567 return std::move(DeclarationLocations);
568 }
569
570 bool handleDeclOccurence(const Decl* D, index::SymbolRoleSet Roles,
571 ArrayRef<index::SymbolRelation> Relations, FileID FID, unsigned Offset,
572 index::IndexDataConsumer::ASTNodeInfo ASTNode) override
573 {
574 if (isSearchedLocation(FID, Offset)) {
575 addDeclarationLocation(D->getSourceRange());
576 }
577 return true;
578 }
579
580private:
581 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000582 const SourceManager &SourceMgr = AST.getSourceManager();
583 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
584 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000585 }
586
Ilya Biryukov04db3682017-07-21 13:29:29 +0000587 void addDeclarationLocation(const SourceRange &ValSourceRange) {
588 const SourceManager &SourceMgr = AST.getSourceManager();
589 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000590 SourceLocation LocStart = ValSourceRange.getBegin();
591 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000592 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000593 Position Begin;
594 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
595 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
596 Position End;
597 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
598 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
599 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000600 Location L;
601 L.uri = URI::fromFile(
602 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
603 L.range = R;
604 DeclarationLocations.push_back(L);
605 }
606
Kirill Bobyrev46213872017-06-28 20:57:28 +0000607 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000608 // Also handle possible macro at the searched location.
609 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000610 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
611 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000612 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000613 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000614 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000615 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000616 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
617 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000618 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000619 // Get the definition just before the searched location so that a macro
620 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000621 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
622 AST.getSourceManager(),
623 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000624 DecLoc.second - 1);
625 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000626 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
627 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000628 if (MacroInf) {
629 addDeclarationLocation(
630 SourceRange(MacroInf->getDefinitionLoc(),
631 MacroInf->getDefinitionEndLoc()));
632 }
633 }
634 }
635 }
636};
637} // namespace
638
639std::vector<Location> ClangdUnit::findDefinitions(Position Pos) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000640 if (!Unit)
641 return {}; // Parsing failed.
642
643 const SourceManager &SourceMgr = Unit->getASTContext().getSourceManager();
644 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000645 if (!FE)
646 return {};
647
648 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(Pos, FE);
649
Kirill Bobyrev46213872017-06-28 20:57:28 +0000650 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
Ilya Biryukov04db3682017-07-21 13:29:29 +0000651 llvm::errs(), SourceLocationBeg, Unit->getASTContext(),
652 Unit->getPreprocessor());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000653 index::IndexingOptions IndexOpts;
654 IndexOpts.SystemSymbolFilter =
655 index::IndexingOptions::SystemSymbolFilterKind::All;
656 IndexOpts.IndexFunctionLocals = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000657
658 indexTopLevelDecls(Unit->getASTContext(), Unit->getTopLevelDecls(),
659 DeclLocationsFinder, IndexOpts);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000660
661 return DeclLocationsFinder->takeLocations();
662}
663
664SourceLocation ClangdUnit::getBeginningOfIdentifier(const Position &Pos,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000665 const FileEntry *FE) const {
666
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000667 // The language server protocol uses zero-based line and column numbers.
668 // Clang uses one-based numbers.
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000669
Ilya Biryukov04db3682017-07-21 13:29:29 +0000670 const ASTContext &AST = Unit->getASTContext();
671 const SourceManager &SourceMgr = AST.getSourceManager();
672
673 SourceLocation InputLocation =
674 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000675 if (Pos.character == 0) {
676 return InputLocation;
677 }
678
679 // This handle cases where the position is in the middle of a token or right
680 // after the end of a token. In theory we could just use GetBeginningOfToken
681 // to find the start of the token at the input position, but this doesn't
682 // work when right after the end, i.e. foo|.
683 // So try to go back by one and see if we're still inside the an identifier
684 // token. If so, Take the beginning of this token.
685 // (It should be the same identifier because you can't have two adjacent
686 // identifiers without another token in between.)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000687 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
688 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000689 Token Result;
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000690 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000691 AST.getLangOpts(), false)) {
Ilya Biryukov4203d2a2017-06-29 17:11:32 +0000692 // getRawToken failed, just use InputLocation.
693 return InputLocation;
694 }
695
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000696 if (Result.is(tok::raw_identifier)) {
697 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000698 Unit->getASTContext().getLangOpts());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000699 }
700
701 return InputLocation;
702}
Ilya Biryukov04db3682017-07-21 13:29:29 +0000703
704void ClangdUnit::ParsedAST::ensurePreambleDeclsDeserialized() {
705 if (PendingTopLevelDecls.empty())
706 return;
707
708 std::vector<const Decl *> Resolved;
709 Resolved.reserve(PendingTopLevelDecls.size());
710
711 ExternalASTSource &Source = *getASTContext().getExternalSource();
712 for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) {
713 // Resolve the declaration ID to an actual declaration, possibly
714 // deserializing the declaration in the process.
715 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
716 Resolved.push_back(D);
717 }
718
719 TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size());
720 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
721
722 PendingTopLevelDecls.clear();
723}
724
725ClangdUnit::ParsedAST::ParsedAST(ParsedAST &&Other) = default;
726
727ClangdUnit::ParsedAST &ClangdUnit::ParsedAST::
728operator=(ParsedAST &&Other) = default;
729
730ClangdUnit::ParsedAST::~ParsedAST() {
731 if (Action) {
732 Action->EndSourceFile();
733 }
734}
735
736ASTContext &ClangdUnit::ParsedAST::getASTContext() {
737 return Clang->getASTContext();
738}
739
740const ASTContext &ClangdUnit::ParsedAST::getASTContext() const {
741 return Clang->getASTContext();
742}
743
744Preprocessor &ClangdUnit::ParsedAST::getPreprocessor() {
745 return Clang->getPreprocessor();
746}
747
748const Preprocessor &ClangdUnit::ParsedAST::getPreprocessor() const {
749 return Clang->getPreprocessor();
750}
751
752ArrayRef<const Decl *> ClangdUnit::ParsedAST::getTopLevelDecls() {
753 ensurePreambleDeclsDeserialized();
754 return TopLevelDecls;
755}
756
757const std::vector<DiagWithFixIts> &
758ClangdUnit::ParsedAST::getDiagnostics() const {
759 return Diags;
760}
761
762ClangdUnit::ParsedAST::ParsedAST(
763 std::unique_ptr<CompilerInstance> Clang,
764 std::unique_ptr<FrontendAction> Action,
765 std::vector<const Decl *> TopLevelDecls,
766 std::vector<serialization::DeclID> PendingTopLevelDecls,
767 std::vector<DiagWithFixIts> Diags)
768 : Clang(std::move(Clang)), Action(std::move(Action)),
769 Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)),
770 PendingTopLevelDecls(std::move(PendingTopLevelDecls)) {
771 assert(this->Clang);
772 assert(this->Action);
773}
774
775ClangdUnit::PreambleData::PreambleData(
776 PrecompiledPreamble Preamble,
777 std::vector<serialization::DeclID> TopLevelDeclIDs,
778 std::vector<DiagWithFixIts> Diags)
779 : Preamble(std::move(Preamble)),
780 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}