blob: 0a8661c301a3c5390c5a1f1c4749d63095e8fc8a [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
Sam McCall98775c52017-12-04 13:49:59 +000012#include "Compiler.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000013#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000014#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000015#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000017#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000018#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000019#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000020#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000021#include "clang/Lex/Lexer.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000024#include "clang/Sema/Sema.h"
25#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000027#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000030#include "llvm/Support/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000031
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000033#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000034
Ilya Biryukov38d79772017-05-16 09:38:59 +000035using namespace clang::clangd;
36using namespace clang;
37
Ilya Biryukov04db3682017-07-21 13:29:29 +000038namespace {
39
40class DeclTrackingASTConsumer : public ASTConsumer {
41public:
42 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
43 : TopLevelDecls(TopLevelDecls) {}
44
45 bool HandleTopLevelDecl(DeclGroupRef DG) override {
46 for (const Decl *D : DG) {
47 // ObjCMethodDecl are not actually top-level decls.
48 if (isa<ObjCMethodDecl>(D))
49 continue;
50
51 TopLevelDecls.push_back(D);
52 }
53 return true;
54 }
55
56private:
57 std::vector<const Decl *> &TopLevelDecls;
58};
59
60class ClangdFrontendAction : public SyntaxOnlyAction {
61public:
62 std::vector<const Decl *> takeTopLevelDecls() {
63 return std::move(TopLevelDecls);
64 }
65
66protected:
67 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
68 StringRef InFile) override {
69 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
70 }
71
72private:
73 std::vector<const Decl *> TopLevelDecls;
74};
75
Ilya Biryukov02d58702017-08-01 15:51:38 +000076class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000077public:
78 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
79 return std::move(TopLevelDeclIDs);
80 }
81
82 void AfterPCHEmitted(ASTWriter &Writer) override {
83 TopLevelDeclIDs.reserve(TopLevelDecls.size());
84 for (Decl *D : TopLevelDecls) {
85 // Invalid top-level decls may not have been serialized.
86 if (D->isInvalidDecl())
87 continue;
88 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
89 }
90 }
91
92 void HandleTopLevelDecl(DeclGroupRef DG) override {
93 for (Decl *D : DG) {
94 if (isa<ObjCMethodDecl>(D))
95 continue;
96 TopLevelDecls.push_back(D);
97 }
98 }
99
100private:
101 std::vector<Decl *> TopLevelDecls;
102 std::vector<serialization::DeclID> TopLevelDeclIDs;
103};
104
105/// Convert from clang diagnostic level to LSP severity.
106static int getSeverity(DiagnosticsEngine::Level L) {
107 switch (L) {
108 case DiagnosticsEngine::Remark:
109 return 4;
110 case DiagnosticsEngine::Note:
111 return 3;
112 case DiagnosticsEngine::Warning:
113 return 2;
114 case DiagnosticsEngine::Fatal:
115 case DiagnosticsEngine::Error:
116 return 1;
117 case DiagnosticsEngine::Ignored:
118 return 0;
119 }
120 llvm_unreachable("Unknown diagnostic level!");
121}
122
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000123llvm::Optional<DiagWithFixIts> toClangdDiag(const StoredDiagnostic &D) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000124 auto Location = D.getLocation();
125 if (!Location.isValid() || !Location.getManager().isInMainFile(Location))
126 return llvm::None;
127
128 Position P;
129 P.line = Location.getSpellingLineNumber() - 1;
130 P.character = Location.getSpellingColumnNumber();
131 Range R = {P, P};
132 clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()};
133
134 llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic;
135 for (const FixItHint &Fix : D.getFixIts()) {
136 FixItsForDiagnostic.push_back(clang::tooling::Replacement(
137 Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert));
138 }
139 return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)};
140}
141
142class StoreDiagsConsumer : public DiagnosticConsumer {
143public:
144 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
145
146 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
147 const clang::Diagnostic &Info) override {
148 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
149
150 if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info)))
151 Output.push_back(std::move(*convertedDiag));
152 }
153
154private:
155 std::vector<DiagWithFixIts> &Output;
156};
157
Ilya Biryukov02d58702017-08-01 15:51:38 +0000158template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
159 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
160}
161
Ilya Biryukov04db3682017-07-21 13:29:29 +0000162} // namespace
163
Ilya Biryukov02d58702017-08-01 15:51:38 +0000164void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
165 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000166}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000167
Ilya Biryukov02d58702017-08-01 15:51:38 +0000168llvm::Optional<ParsedAST>
169ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000170 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000171 std::unique_ptr<llvm::MemoryBuffer> Buffer,
172 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000173 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
174 clangd::Logger &Logger) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000175
176 std::vector<DiagWithFixIts> ASTDiags;
177 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
178
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000179 const PrecompiledPreamble *PreamblePCH =
180 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000181 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000182 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000183 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000184
185 // Recover resources if we crash before exiting this method.
186 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
187 Clang.get());
188
189 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000190 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
191 if (!Action->BeginSourceFile(*Clang, MainInput)) {
192 Logger.log("BeginSourceFile() failed when building AST for " +
193 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000194 return llvm::None;
195 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000196 if (!Action->Execute())
197 Logger.log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000198
199 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
200 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000201 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000202
203 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000204 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
205 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000206}
207
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000208namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000209
210SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
211 const FileEntry *FE,
212 unsigned Offset) {
213 SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1);
214 return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
215}
216
217SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
218 const FileEntry *FE, Position Pos) {
219 SourceLocation InputLoc =
220 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
221 return Mgr.getMacroArgExpandedLocation(InputLoc);
222}
223
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000224/// Finds declarations locations that a given source location refers to.
225class DeclarationLocationsFinder : public index::IndexDataConsumer {
226 std::vector<Location> DeclarationLocations;
227 const SourceLocation &SearchedLocation;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000228 const ASTContext &AST;
229 Preprocessor &PP;
230
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000231public:
232 DeclarationLocationsFinder(raw_ostream &OS,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000233 const SourceLocation &SearchedLocation,
234 ASTContext &AST, Preprocessor &PP)
235 : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000236
237 std::vector<Location> takeLocations() {
238 // Don't keep the same location multiple times.
239 // This can happen when nodes in the AST are visited twice.
240 std::sort(DeclarationLocations.begin(), DeclarationLocations.end());
Kirill Bobyrev46213872017-06-28 20:57:28 +0000241 auto last =
242 std::unique(DeclarationLocations.begin(), DeclarationLocations.end());
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000243 DeclarationLocations.erase(last, DeclarationLocations.end());
244 return std::move(DeclarationLocations);
245 }
246
Ilya Biryukov02d58702017-08-01 15:51:38 +0000247 bool
248 handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
249 ArrayRef<index::SymbolRelation> Relations, FileID FID,
250 unsigned Offset,
251 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000252 if (isSearchedLocation(FID, Offset)) {
253 addDeclarationLocation(D->getSourceRange());
254 }
255 return true;
256 }
257
258private:
259 bool isSearchedLocation(FileID FID, unsigned Offset) const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000260 const SourceManager &SourceMgr = AST.getSourceManager();
261 return SourceMgr.getFileOffset(SearchedLocation) == Offset &&
262 SourceMgr.getFileID(SearchedLocation) == FID;
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000263 }
264
Ilya Biryukov04db3682017-07-21 13:29:29 +0000265 void addDeclarationLocation(const SourceRange &ValSourceRange) {
266 const SourceManager &SourceMgr = AST.getSourceManager();
267 const LangOptions &LangOpts = AST.getLangOpts();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000268 SourceLocation LocStart = ValSourceRange.getBegin();
269 SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(),
Ilya Biryukov04db3682017-07-21 13:29:29 +0000270 0, SourceMgr, LangOpts);
Kirill Bobyrev46213872017-06-28 20:57:28 +0000271 Position Begin;
272 Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1;
273 Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1;
274 Position End;
275 End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1;
276 End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1;
277 Range R = {Begin, End};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000278 Location L;
Marc-Andre Laperleba070102017-11-07 16:16:45 +0000279 if (const FileEntry *F =
280 SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) {
281 StringRef FilePath = F->tryGetRealPathName();
282 if (FilePath.empty())
283 FilePath = F->getName();
284 L.uri = URI::fromFile(FilePath);
285 L.range = R;
286 DeclarationLocations.push_back(L);
287 }
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000288 }
289
Kirill Bobyrev46213872017-06-28 20:57:28 +0000290 void finish() override {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000291 // Also handle possible macro at the searched location.
292 Token Result;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000293 if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(),
294 AST.getLangOpts(), false)) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000295 if (Result.is(tok::raw_identifier)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000296 PP.LookUpIdentifierInfo(Result);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000297 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000298 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000299 if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
300 std::pair<FileID, unsigned int> DecLoc =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000301 AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000302 // Get the definition just before the searched location so that a macro
303 // referenced in a '#undef MACRO' can still be found.
Ilya Biryukov04db3682017-07-21 13:29:29 +0000304 SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation(
305 AST.getSourceManager(),
306 AST.getSourceManager().getFileEntryForID(DecLoc.first),
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000307 DecLoc.second - 1);
308 MacroDefinition MacroDef =
Ilya Biryukov04db3682017-07-21 13:29:29 +0000309 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
310 MacroInfo *MacroInf = MacroDef.getMacroInfo();
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000311 if (MacroInf) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000312 addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(),
313 MacroInf->getDefinitionEndLoc()));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000314 }
315 }
316 }
317 }
318};
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000319
Ilya Biryukov02d58702017-08-01 15:51:38 +0000320} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000321
Ilya Biryukove5128f72017-09-20 07:24:15 +0000322std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos,
323 clangd::Logger &Logger) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000324 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
325 const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
326 if (!FE)
327 return {};
328
329 SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE);
330
331 auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>(
332 llvm::errs(), SourceLocationBeg, AST.getASTContext(),
333 AST.getPreprocessor());
334 index::IndexingOptions IndexOpts;
335 IndexOpts.SystemSymbolFilter =
336 index::IndexingOptions::SystemSymbolFilterKind::All;
337 IndexOpts.IndexFunctionLocals = true;
338
339 indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(),
340 DeclLocationsFinder, IndexOpts);
341
342 return DeclLocationsFinder->takeLocations();
343}
344
345void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000346 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000347 return;
348
349 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000350 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000351
352 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000353 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000354 // Resolve the declaration ID to an actual declaration, possibly
355 // deserializing the declaration in the process.
356 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
357 Resolved.push_back(D);
358 }
359
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000360 TopLevelDecls.reserve(TopLevelDecls.size() +
361 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000362 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
363
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000364 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000365}
366
Ilya Biryukov02d58702017-08-01 15:51:38 +0000367ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000368
Ilya Biryukov02d58702017-08-01 15:51:38 +0000369ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000370
Ilya Biryukov02d58702017-08-01 15:51:38 +0000371ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000372 if (Action) {
373 Action->EndSourceFile();
374 }
375}
376
Ilya Biryukov02d58702017-08-01 15:51:38 +0000377ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
378
379const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000380 return Clang->getASTContext();
381}
382
Ilya Biryukov02d58702017-08-01 15:51:38 +0000383Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000384
Ilya Biryukov02d58702017-08-01 15:51:38 +0000385const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000386 return Clang->getPreprocessor();
387}
388
Ilya Biryukov02d58702017-08-01 15:51:38 +0000389ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000390 ensurePreambleDeclsDeserialized();
391 return TopLevelDecls;
392}
393
Ilya Biryukov02d58702017-08-01 15:51:38 +0000394const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000395 return Diags;
396}
397
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000398PreambleData::PreambleData(PrecompiledPreamble Preamble,
399 std::vector<serialization::DeclID> TopLevelDeclIDs,
400 std::vector<DiagWithFixIts> Diags)
401 : Preamble(std::move(Preamble)),
402 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
403
404ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
405 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000406 std::unique_ptr<FrontendAction> Action,
407 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000408 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000409 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
410 Action(std::move(Action)), Diags(std::move(Diags)),
411 TopLevelDecls(std::move(TopLevelDecls)),
412 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000413 assert(this->Clang);
414 assert(this->Action);
415}
416
Ilya Biryukov02d58702017-08-01 15:51:38 +0000417ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
418 : AST(std::move(Wrapper.AST)) {}
419
420ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
421 : AST(std::move(AST)) {}
422
Ilya Biryukov02d58702017-08-01 15:51:38 +0000423std::shared_ptr<CppFile>
424CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000425 bool StorePreamblesInMemory,
Ilya Biryukov83ca8a22017-09-20 10:46:58 +0000426 std::shared_ptr<PCHContainerOperations> PCHs,
427 clangd::Logger &Logger) {
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000428 return std::shared_ptr<CppFile>(new CppFile(FileName, std::move(Command),
429 StorePreamblesInMemory,
430 std::move(PCHs), Logger));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000431}
432
433CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000434 bool StorePreamblesInMemory,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000435 std::shared_ptr<PCHContainerOperations> PCHs,
436 clangd::Logger &Logger)
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000437 : FileName(FileName), Command(std::move(Command)),
438 StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
Ilya Biryukove5128f72017-09-20 07:24:15 +0000439 RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) {
Sam McCallfae3b022017-11-30 23:16:23 +0000440 Logger.log("Opened file " + FileName + " with command [" +
441 this->Command.Directory + "] " +
Sam McCall318fbeb2017-11-30 23:21:34 +0000442 llvm::join(this->Command.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000443
444 std::lock_guard<std::mutex> Lock(Mutex);
445 LatestAvailablePreamble = nullptr;
446 PreamblePromise.set_value(nullptr);
447 PreambleFuture = PreamblePromise.get_future();
448
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000449 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000450 ASTFuture = ASTPromise.get_future();
451}
452
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000453void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000454
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000455UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000456 std::unique_lock<std::mutex> Lock(Mutex);
457 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000458 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000459 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
460 // We want to keep this invariant.
461 if (futureIsReady(PreambleFuture)) {
462 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
463 PreambleFuture = PreamblePromise.get_future();
464 }
465 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000466 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000467 ASTFuture = ASTPromise.get_future();
468 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000469
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000470 Lock.unlock();
471 // Notify about changes to RebuildCounter.
472 RebuildCond.notify_all();
473
474 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000475 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000476 std::unique_lock<std::mutex> Lock(That->Mutex);
477 CppFile *This = &*That;
478 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
479 return !This->RebuildInProgress ||
480 This->RebuildCounter != RequestRebuildCounter;
481 });
482
483 // This computation got cancelled itself, do nothing.
484 if (This->RebuildCounter != RequestRebuildCounter)
485 return;
486
487 // Set empty results for Promises.
488 That->PreamblePromise.set_value(nullptr);
489 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000490 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000491}
492
493llvm::Optional<std::vector<DiagWithFixIts>>
494CppFile::rebuild(StringRef NewContents,
495 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000496 return deferRebuild(NewContents, std::move(VFS))();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000497}
498
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000499UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov02d58702017-08-01 15:51:38 +0000500CppFile::deferRebuild(StringRef NewContents,
501 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
502 std::shared_ptr<const PreambleData> OldPreamble;
503 std::shared_ptr<PCHContainerOperations> PCHs;
504 unsigned RequestRebuildCounter;
505 {
506 std::unique_lock<std::mutex> Lock(Mutex);
507 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
508 // They will try to exit as early as possible and won't call set_value on
509 // our promises.
510 RequestRebuildCounter = ++this->RebuildCounter;
511 PCHs = this->PCHs;
512
513 // Remember the preamble to be used during rebuild.
514 OldPreamble = this->LatestAvailablePreamble;
515 // Setup std::promises and std::futures for Preamble and AST. Corresponding
516 // futures will wait until the rebuild process is finished.
517 if (futureIsReady(this->PreambleFuture)) {
518 this->PreamblePromise =
519 std::promise<std::shared_ptr<const PreambleData>>();
520 this->PreambleFuture = this->PreamblePromise.get_future();
521 }
522 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000523 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000524 this->ASTFuture = this->ASTPromise.get_future();
525 }
526 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000527 // Notify about changes to RebuildCounter.
528 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000529
530 // A helper to function to finish the rebuild. May be run on a different
531 // thread.
532
533 // Don't let this CppFile die before rebuild is finished.
534 std::shared_ptr<CppFile> That = shared_from_this();
535 auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs,
Ilya Biryukov11a02522017-11-17 19:05:56 +0000536 That](std::string NewContents) mutable // 'mutable' to
537 // allow changing
538 // OldPreamble.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000539 -> llvm::Optional<std::vector<DiagWithFixIts>> {
540 // Only one execution of this method is possible at a time.
541 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
542 // into a state for doing a rebuild.
543 RebuildGuard Rebuild(*That, RequestRebuildCounter);
544 if (Rebuild.wasCancelledBeforeConstruction())
545 return llvm::None;
546
547 std::vector<const char *> ArgStrs;
548 for (const auto &S : That->Command.CommandLine)
549 ArgStrs.push_back(S.c_str());
550
551 VFS->setCurrentWorkingDirectory(That->Command.Directory);
552
553 std::unique_ptr<CompilerInvocation> CI;
554 {
555 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
556 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000557 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000558 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
559 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000560 &IgnoreDiagnostics, false);
561 CI =
562 createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine, VFS);
563 // createInvocationFromCommandLine sets DisableFree.
564 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000565 }
566 assert(CI && "Couldn't create CompilerInvocation");
567
568 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
569 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
570
571 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000572 // not mutate any fields of CppFile, only does the actual computation.
573 // Lamdba is marked mutable to call reset() on OldPreamble.
574 auto DoRebuildPreamble =
575 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000576 auto Bounds =
577 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
578 if (OldPreamble && OldPreamble->Preamble.CanReuse(
579 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
580 return OldPreamble;
581 }
Ilya Biryukov11a02522017-11-17 19:05:56 +0000582 // We won't need the OldPreamble anymore, release it so it can be deleted
583 // (if there are no other references to it).
584 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000585
Sam McCall9cfd9c92017-11-23 17:12:04 +0000586 trace::Span Tracer("Preamble");
587 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000588 std::vector<DiagWithFixIts> PreambleDiags;
589 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
590 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
591 CompilerInstance::createDiagnostics(
592 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
593 CppFilePreambleCallbacks SerializedDeclsCollector;
594 auto BuiltPreamble = PrecompiledPreamble::Build(
595 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000596 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000597 SerializedDeclsCollector);
598
599 if (BuiltPreamble) {
600 return std::make_shared<PreambleData>(
601 std::move(*BuiltPreamble),
602 SerializedDeclsCollector.takeTopLevelDeclIDs(),
603 std::move(PreambleDiags));
604 } else {
605 return nullptr;
606 }
607 };
608
609 // Compute updated Preamble.
610 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
611 // Publish the new Preamble.
612 {
613 std::lock_guard<std::mutex> Lock(That->Mutex);
614 // We always set LatestAvailablePreamble to the new value, hoping that it
615 // will still be usable in the further requests.
616 That->LatestAvailablePreamble = NewPreamble;
617 if (RequestRebuildCounter != That->RebuildCounter)
618 return llvm::None; // Our rebuild request was cancelled, do nothing.
619 That->PreamblePromise.set_value(NewPreamble);
620 } // unlock Mutex
621
622 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000623 std::vector<DiagWithFixIts> Diagnostics;
624 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000625 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
626 NewPreamble->Diags.end());
627 }
628
629 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000630 llvm::Optional<ParsedAST> NewAST;
631 {
Sam McCall9cfd9c92017-11-23 17:12:04 +0000632 trace::Span Tracer("Build");
633 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000634 NewAST =
635 ParsedAST::Build(std::move(CI), std::move(NewPreamble),
636 std::move(ContentsBuffer), PCHs, VFS, That->Logger);
Sam McCall8567cb32017-11-02 09:21:51 +0000637 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000638
639 if (NewAST) {
640 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
641 NewAST->getDiagnostics().end());
642 } else {
643 // Don't report even Preamble diagnostics if we coulnd't build AST.
644 Diagnostics.clear();
645 }
646
647 // Publish the new AST.
648 {
649 std::lock_guard<std::mutex> Lock(That->Mutex);
650 if (RequestRebuildCounter != That->RebuildCounter)
651 return Diagnostics; // Our rebuild request was cancelled, don't set
652 // ASTPromise.
653
Ilya Biryukov574b7532017-08-02 09:08:39 +0000654 That->ASTPromise.set_value(
655 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000656 } // unlock Mutex
657
658 return Diagnostics;
659 };
660
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000661 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000662}
663
664std::shared_future<std::shared_ptr<const PreambleData>>
665CppFile::getPreamble() const {
666 std::lock_guard<std::mutex> Lock(Mutex);
667 return PreambleFuture;
668}
669
670std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
671 std::lock_guard<std::mutex> Lock(Mutex);
672 return LatestAvailablePreamble;
673}
674
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000675std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000676 std::lock_guard<std::mutex> Lock(Mutex);
677 return ASTFuture;
678}
679
680tooling::CompileCommand const &CppFile::getCompileCommand() const {
681 return Command;
682}
683
684CppFile::RebuildGuard::RebuildGuard(CppFile &File,
685 unsigned RequestRebuildCounter)
686 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
687 std::unique_lock<std::mutex> Lock(File.Mutex);
688 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
689 if (WasCancelledBeforeConstruction)
690 return;
691
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000692 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
693 return !File.RebuildInProgress ||
694 File.RebuildCounter != RequestRebuildCounter;
695 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000696
697 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
698 if (WasCancelledBeforeConstruction)
699 return;
700
701 File.RebuildInProgress = true;
702}
703
704bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
705 return WasCancelledBeforeConstruction;
706}
707
708CppFile::RebuildGuard::~RebuildGuard() {
709 if (WasCancelledBeforeConstruction)
710 return;
711
712 std::unique_lock<std::mutex> Lock(File.Mutex);
713 assert(File.RebuildInProgress);
714 File.RebuildInProgress = false;
715
716 if (File.RebuildCounter == RequestRebuildCounter) {
717 // Our rebuild request was successful.
718 assert(futureIsReady(File.ASTFuture));
719 assert(futureIsReady(File.PreambleFuture));
720 } else {
721 // Our rebuild request was cancelled, because further reparse was requested.
722 assert(!futureIsReady(File.ASTFuture));
723 assert(!futureIsReady(File.PreambleFuture));
724 }
725
726 Lock.unlock();
727 File.RebuildCond.notify_all();
728}
Haojian Wu345099c2017-11-09 11:30:04 +0000729
730SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
731 const Position &Pos,
732 const FileEntry *FE) {
733 // The language server protocol uses zero-based line and column numbers.
734 // Clang uses one-based numbers.
735
736 const ASTContext &AST = Unit.getASTContext();
737 const SourceManager &SourceMgr = AST.getSourceManager();
738
739 SourceLocation InputLocation =
740 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
741 if (Pos.character == 0) {
742 return InputLocation;
743 }
744
745 // This handle cases where the position is in the middle of a token or right
746 // after the end of a token. In theory we could just use GetBeginningOfToken
747 // to find the start of the token at the input position, but this doesn't
748 // work when right after the end, i.e. foo|.
749 // So try to go back by one and see if we're still inside the an identifier
750 // token. If so, Take the beginning of this token.
751 // (It should be the same identifier because you can't have two adjacent
752 // identifiers without another token in between.)
753 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
754 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
755 Token Result;
756 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
757 AST.getLangOpts(), false)) {
758 // getRawToken failed, just use InputLocation.
759 return InputLocation;
760 }
761
762 if (Result.is(tok::raw_identifier)) {
763 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
764 AST.getLangOpts());
765 }
766
767 return InputLocation;
768}