blob: 61bfe0bc25fbad018d1a82717151d34688eabd9a [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/ASTUnit.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.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/IndexingAction.h"
17#include "clang/Index/IndexDataConsumer.h"
18#include "clang/Lex/Lexer.h"
19#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000021#include "clang/Tooling/CompilationDatabase.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000022#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000023
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000024#include <algorithm>
25
Ilya Biryukov38d79772017-05-16 09:38:59 +000026using namespace clang::clangd;
27using namespace clang;
28
29ClangdUnit::ClangdUnit(PathRef FileName, StringRef Contents,
Ilya Biryukova46f7a92017-06-28 10:34:50 +000030 StringRef ResourceDir,
Ilya Biryukov38d79772017-05-16 09:38:59 +000031 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000032 std::vector<tooling::CompileCommand> Commands,
33 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Ilya Biryukov38d79772017-05-16 09:38:59 +000034 : FileName(FileName), PCHs(PCHs) {
35 assert(!Commands.empty() && "No compile commands provided");
36
37 // Inject the resource dir.
38 // FIXME: Don't overwrite it if it's already there.
Ilya Biryukova46f7a92017-06-28 10:34:50 +000039 Commands.front().CommandLine.push_back("-resource-dir=" + std::string(ResourceDir));
Ilya Biryukov38d79772017-05-16 09:38:59 +000040
41 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
42 CompilerInstance::createDiagnostics(new DiagnosticOptions);
43
44 std::vector<const char *> ArgStrs;
45 for (const auto &S : Commands.front().CommandLine)
46 ArgStrs.push_back(S.c_str());
47
48 ASTUnit::RemappedFile RemappedSource(
49 FileName,
50 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName).release());
51
52 auto ArgP = &*ArgStrs.begin();
53 Unit = std::unique_ptr<ASTUnit>(ASTUnit::LoadFromCommandLine(
54 ArgP, ArgP + ArgStrs.size(), PCHs, Diags, ResourceDir,
55 /*OnlyLocalDecls=*/false, /*CaptureDiagnostics=*/true, RemappedSource,
56 /*RemappedFilesKeepOriginalName=*/true,
Krasimir Georgievd8145332017-05-22 12:49:08 +000057 /*PrecompilePreambleAfterNParses=*/1, /*TUKind=*/TU_Prefix,
Ilya Biryukov38d79772017-05-16 09:38:59 +000058 /*CacheCodeCompletionResults=*/true,
59 /*IncludeBriefCommentsInCodeCompletion=*/true,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000060 /*AllowPCHWithCompilerErrors=*/true,
61 /*SkipFunctionBodies=*/false,
Argyrios Kyrtzidis783e4c22017-06-09 02:04:19 +000062 /*SingleFileParse=*/false,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000063 /*UserFilesAreVolatile=*/false, /*ForSerialization=*/false,
64 /*ModuleFormat=*/llvm::None,
65 /*ErrAST=*/nullptr, VFS));
66 assert(Unit && "Unit wasn't created");
Ilya Biryukov38d79772017-05-16 09:38:59 +000067}
68
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000069void ClangdUnit::reparse(StringRef Contents,
70 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000071 // Do a reparse if this wasn't the first parse.
72 // FIXME: This might have the wrong working directory if it changed in the
73 // meantime.
74 ASTUnit::RemappedFile RemappedSource(
75 FileName,
76 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName).release());
77
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000078 Unit->Reparse(PCHs, RemappedSource, VFS);
Ilya Biryukov38d79772017-05-16 09:38:59 +000079}
80
81namespace {
82
83CompletionItemKind getKind(CXCursorKind K) {
84 switch (K) {
85 case CXCursor_MacroInstantiation:
86 case CXCursor_MacroDefinition:
87 return CompletionItemKind::Text;
88 case CXCursor_CXXMethod:
89 return CompletionItemKind::Method;
90 case CXCursor_FunctionDecl:
91 case CXCursor_FunctionTemplate:
92 return CompletionItemKind::Function;
93 case CXCursor_Constructor:
94 case CXCursor_Destructor:
95 return CompletionItemKind::Constructor;
96 case CXCursor_FieldDecl:
97 return CompletionItemKind::Field;
98 case CXCursor_VarDecl:
99 case CXCursor_ParmDecl:
100 return CompletionItemKind::Variable;
101 case CXCursor_ClassDecl:
102 case CXCursor_StructDecl:
103 case CXCursor_UnionDecl:
104 case CXCursor_ClassTemplate:
105 case CXCursor_ClassTemplatePartialSpecialization:
106 return CompletionItemKind::Class;
107 case CXCursor_Namespace:
108 case CXCursor_NamespaceAlias:
109 case CXCursor_NamespaceRef:
110 return CompletionItemKind::Module;
111 case CXCursor_EnumConstantDecl:
112 return CompletionItemKind::Value;
113 case CXCursor_EnumDecl:
114 return CompletionItemKind::Enum;
115 case CXCursor_TypeAliasDecl:
116 case CXCursor_TypeAliasTemplateDecl:
117 case CXCursor_TypedefDecl:
118 case CXCursor_MemberRef:
119 case CXCursor_TypeRef:
120 return CompletionItemKind::Reference;
121 default:
122 return CompletionItemKind::Missing;
123 }
124}
125
126class CompletionItemsCollector : public CodeCompleteConsumer {
127 std::vector<CompletionItem> *Items;
128 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
129 CodeCompletionTUInfo CCTUInfo;
130
131public:
132 CompletionItemsCollector(std::vector<CompletionItem> *Items,
133 const CodeCompleteOptions &CodeCompleteOpts)
134 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
135 Items(Items),
136 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
137 CCTUInfo(Allocator) {}
138
139 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
140 CodeCompletionResult *Results,
141 unsigned NumResults) override {
142 for (unsigned I = 0; I != NumResults; ++I) {
143 CodeCompletionResult &Result = Results[I];
144 CodeCompletionString *CCS = Result.CreateCodeCompletionString(
145 S, Context, *Allocator, CCTUInfo,
146 CodeCompleteOpts.IncludeBriefComments);
147 if (CCS) {
148 CompletionItem Item;
Krasimir Georgieve6035a52017-06-08 15:11:51 +0000149 for (CodeCompletionString::Chunk C : *CCS) {
150 switch (C.Kind) {
151 case CodeCompletionString::CK_ResultType:
152 Item.detail = C.Text;
153 break;
154 case CodeCompletionString::CK_Optional:
155 break;
156 default:
157 Item.label += C.Text;
158 break;
159 }
160 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000161 assert(CCS->getTypedText());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000162 Item.kind = getKind(Result.CursorKind);
Krasimir Georgieva1de3c92017-06-15 09:11:57 +0000163 // Priority is a 16-bit integer, hence at most 5 digits.
164 // Since identifiers with higher priority need to come first,
165 // we subtract the priority from 99999.
166 // For example, the sort text of the identifier 'a' with priority 35
167 // is 99964a.
168 assert(CCS->getPriority() < 99999 && "Expecting code completion result "
169 "priority to have at most "
170 "5-digits");
171 llvm::raw_string_ostream(Item.sortText) << llvm::format(
172 "%05d%s", 99999 - CCS->getPriority(), CCS->getTypedText());
173 Item.insertText = Item.filterText = CCS->getTypedText();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000174 if (CCS->getBriefComment())
175 Item.documentation = CCS->getBriefComment();
176 Items->push_back(std::move(Item));
177 }
178 }
179 }
180
181 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
182
183 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
184};
185} // namespace
186
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000187std::vector<CompletionItem>
188ClangdUnit::codeComplete(StringRef Contents, Position Pos,
189 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000190 CodeCompleteOptions CCO;
191 CCO.IncludeBriefComments = 1;
192 // This is where code completion stores dirty buffers. Need to free after
193 // completion.
194 SmallVector<const llvm::MemoryBuffer *, 4> OwnedBuffers;
195 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
196 IntrusiveRefCntPtr<DiagnosticsEngine> DiagEngine(
197 new DiagnosticsEngine(new DiagnosticIDs, new DiagnosticOptions));
198 std::vector<CompletionItem> Items;
199 CompletionItemsCollector Collector(&Items, CCO);
200
201 ASTUnit::RemappedFile RemappedSource(
202 FileName,
203 llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName).release());
204
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000205 IntrusiveRefCntPtr<FileManager> FileMgr(
206 new FileManager(Unit->getFileSystemOpts(), VFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000207 IntrusiveRefCntPtr<SourceManager> SourceMgr(
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000208 new SourceManager(*DiagEngine, *FileMgr));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000209 // CodeComplete seems to require fresh LangOptions.
210 LangOptions LangOpts = Unit->getLangOpts();
211 // The language server protocol uses zero-based line and column numbers.
212 // The clang code completion uses one-based numbers.
213 Unit->CodeComplete(FileName, Pos.line + 1, Pos.character + 1, RemappedSource,
214 CCO.IncludeMacros, CCO.IncludeCodePatterns,
215 CCO.IncludeBriefComments, Collector, PCHs, *DiagEngine,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000216 LangOpts, *SourceMgr, *FileMgr, StoredDiagnostics,
217 OwnedBuffers);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000218 for (const llvm::MemoryBuffer *Buffer : OwnedBuffers)
219 delete Buffer;
220 return Items;
221}
222
223namespace {
224/// Convert from clang diagnostic level to LSP severity.
225static int getSeverity(DiagnosticsEngine::Level L) {
226 switch (L) {
227 case DiagnosticsEngine::Remark:
228 return 4;
229 case DiagnosticsEngine::Note:
230 return 3;
231 case DiagnosticsEngine::Warning:
232 return 2;
233 case DiagnosticsEngine::Fatal:
234 case DiagnosticsEngine::Error:
235 return 1;
236 case DiagnosticsEngine::Ignored:
237 return 0;
238 }
239 llvm_unreachable("Unknown diagnostic level!");
240}
241} // namespace
242
243std::vector<DiagWithFixIts> ClangdUnit::getLocalDiagnostics() const {
244 std::vector<DiagWithFixIts> Result;
245 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
246 DEnd = Unit->stored_diag_end();
247 D != DEnd; ++D) {
248 if (!D->getLocation().isValid() ||
249 !D->getLocation().getManager().isInMainFile(D->getLocation()))
250 continue;
251 Position P;
252 P.line = D->getLocation().getSpellingLineNumber() - 1;
253 P.character = D->getLocation().getSpellingColumnNumber();
254 Range R = {P, P};
255 clangd::Diagnostic Diag = {R, getSeverity(D->getLevel()), D->getMessage()};
256
257 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
258 for (const FixItHint &Fix : D->getFixIts()) {
259 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
260 Unit->getSourceManager(), Fix.RemoveRange, Fix.CodeToInsert));
261 }
262 Result.push_back({Diag, std::move(FixItsForDiagnostic)});
263 }
264 return Result;
265}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000266
267void ClangdUnit::dumpAST(llvm::raw_ostream &OS) const {
268 Unit->getASTContext().getTranslationUnitDecl()->dump(OS, true);
269}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000270
271namespace {
272/// Finds declarations locations that a given source location refers to.
273class DeclarationLocationsFinder : public index::IndexDataConsumer {
274 std::vector<Location> DeclarationLocations;
275 const SourceLocation &SearchedLocation;
276 ASTUnit &Unit;
277public:
278 DeclarationLocationsFinder(raw_ostream &OS,
279 const SourceLocation &SearchedLocation, ASTUnit &Unit) :
280 SearchedLocation(SearchedLocation), Unit(Unit) {
281 }
282
283 std::vector<Location> takeLocations() {
284 // Don't keep the same location multiple times.
285 // This can happen when nodes in the AST are visited twice.
286 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
287 auto last = std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
288 DeclarationLocations.erase(last, DeclarationLocations.end());
289 return std::move(DeclarationLocations);
290 }
291
292 bool handleDeclOccurence(const Decl* D, index::SymbolRoleSet Roles,
293 ArrayRef<index::SymbolRelation> Relations, FileID FID, unsigned Offset,
294 index::IndexDataConsumer::ASTNodeInfo ASTNode) override
295 {
296 if (isSearchedLocation(FID, Offset)) {
297 addDeclarationLocation(D->getSourceRange());
298 }
299 return true;
300 }
301
302private:
303 bool isSearchedLocation(FileID FID, unsigned Offset) const {
304 const SourceManager &SourceMgr = Unit.getSourceManager();
305 return SourceMgr.getFileOffset(SearchedLocation) == Offset
306 && SourceMgr.getFileID(SearchedLocation) == FID;
307 }
308
309 void addDeclarationLocation(const SourceRange& ValSourceRange) {
310 const SourceManager& SourceMgr = Unit.getSourceManager();
311 const LangOptions& LangOpts = Unit.getLangOpts();
312 SourceLocation LocStart = ValSourceRange.getBegin();
313 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
314 0, SourceMgr, LangOpts);
315 Position P1;
316 P1.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
317 P1.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
318 Position P2;
319 P2.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
320 P2.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
321 Range R = { P1, P2 };
322 Location L;
323 L.uri = URI::fromFile(
324 SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart)));
325 L.range = R;
326 DeclarationLocations.push_back(L);
327 }
328
329 void finish() override
330 {
331 // Also handle possible macro at the searched location.
332 Token Result;
333 if (!Lexer::getRawToken(SearchedLocation, Result, Unit.getSourceManager(),
334 Unit.getASTContext().getLangOpts(), false)) {
335 if (Result.is(tok::raw_identifier)) {
336 Unit.getPreprocessor().LookUpIdentifierInfo(Result);
337 }
338 IdentifierInfo* IdentifierInfo = Result.getIdentifierInfo();
339 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
340 std::pair<FileID, unsigned int> DecLoc =
341 Unit.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
342 // Get the definition just before the searched location so that a macro
343 // referenced in a '#undef MACRO' can still be found.
344 SourceLocation BeforeSearchedLocation = Unit.getLocation(
345 Unit.getSourceManager().getFileEntryForID(DecLoc.first),
346 DecLoc.second - 1);
347 MacroDefinition MacroDef =
348 Unit.getPreprocessor().getMacroDefinitionAtLoc(IdentifierInfo,
349 BeforeSearchedLocation);
350 MacroInfo* MacroInf = MacroDef.getMacroInfo();
351 if (MacroInf) {
352 addDeclarationLocation(
353 SourceRange(MacroInf->getDefinitionLoc(),
354 MacroInf->getDefinitionEndLoc()));
355 }
356 }
357 }
358 }
359};
360} // namespace
361
362std::vector<Location> ClangdUnit::findDefinitions(Position Pos) {
363 const FileEntry *FE = Unit->getFileManager().getFile(Unit->getMainFileName());
364 if (!FE)
365 return {};
366
367 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(Pos, FE);
368
369 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(llvm::errs(),
370 SourceLocationBeg, *Unit);
371 index::IndexingOptions IndexOpts;
372 IndexOpts.SystemSymbolFilter =
373 index::IndexingOptions::SystemSymbolFilterKind::All;
374 IndexOpts.IndexFunctionLocals = true;
375 index::indexASTUnit(*Unit, DeclLocationsFinder, IndexOpts);
376
377 return DeclLocationsFinder->takeLocations();
378}
379
380SourceLocation ClangdUnit::getBeginningOfIdentifier(const Position &Pos,
381 const FileEntry *FE) const {
382 // The language server protocol uses zero-based line and column numbers.
383 // Clang uses one-based numbers.
384 SourceLocation InputLocation = Unit->getLocation(FE, Pos.line + 1,
385 Pos.character + 1);
386
387 if (Pos.character == 0) {
388 return InputLocation;
389 }
390
391 // This handle cases where the position is in the middle of a token or right
392 // after the end of a token. In theory we could just use GetBeginningOfToken
393 // to find the start of the token at the input position, but this doesn't
394 // work when right after the end, i.e. foo|.
395 // So try to go back by one and see if we're still inside the an identifier
396 // token. If so, Take the beginning of this token.
397 // (It should be the same identifier because you can't have two adjacent
398 // identifiers without another token in between.)
399 SourceLocation PeekBeforeLocation = Unit->getLocation(FE, Pos.line + 1,
400 Pos.character);
401 const SourceManager &SourceMgr = Unit->getSourceManager();
402 Token Result;
403 Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
404 Unit->getASTContext().getLangOpts(), false);
405 if (Result.is(tok::raw_identifier)) {
406 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
407 Unit->getASTContext().getLangOpts());
408 }
409
410 return InputLocation;
411}