blob: 90dd221ec428f8d5836d7b1b9957e053a864a2ef [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"
Sam McCall98775c52017-12-04 13:49:59 +000011#include "Compiler.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000029#include "llvm/Support/Format.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000031#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032
Ilya Biryukov38d79772017-05-16 09:38:59 +000033using namespace clang::clangd;
34using namespace clang;
35
Ilya Biryukov04db3682017-07-21 13:29:29 +000036namespace {
37
38class DeclTrackingASTConsumer : public ASTConsumer {
39public:
40 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
41 : TopLevelDecls(TopLevelDecls) {}
42
43 bool HandleTopLevelDecl(DeclGroupRef DG) override {
44 for (const Decl *D : DG) {
45 // ObjCMethodDecl are not actually top-level decls.
46 if (isa<ObjCMethodDecl>(D))
47 continue;
48
49 TopLevelDecls.push_back(D);
50 }
51 return true;
52 }
53
54private:
55 std::vector<const Decl *> &TopLevelDecls;
56};
57
58class ClangdFrontendAction : public SyntaxOnlyAction {
59public:
60 std::vector<const Decl *> takeTopLevelDecls() {
61 return std::move(TopLevelDecls);
62 }
63
64protected:
65 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
66 StringRef InFile) override {
67 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
68 }
69
70private:
71 std::vector<const Decl *> TopLevelDecls;
72};
73
Ilya Biryukov02d58702017-08-01 15:51:38 +000074class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000075public:
76 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
77 return std::move(TopLevelDeclIDs);
78 }
79
80 void AfterPCHEmitted(ASTWriter &Writer) override {
81 TopLevelDeclIDs.reserve(TopLevelDecls.size());
82 for (Decl *D : TopLevelDecls) {
83 // Invalid top-level decls may not have been serialized.
84 if (D->isInvalidDecl())
85 continue;
86 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
87 }
88 }
89
90 void HandleTopLevelDecl(DeclGroupRef DG) override {
91 for (Decl *D : DG) {
92 if (isa<ObjCMethodDecl>(D))
93 continue;
94 TopLevelDecls.push_back(D);
95 }
96 }
97
98private:
99 std::vector<Decl *> TopLevelDecls;
100 std::vector<serialization::DeclID> TopLevelDeclIDs;
101};
102
103/// Convert from clang diagnostic level to LSP severity.
104static int getSeverity(DiagnosticsEngine::Level L) {
105 switch (L) {
106 case DiagnosticsEngine::Remark:
107 return 4;
108 case DiagnosticsEngine::Note:
109 return 3;
110 case DiagnosticsEngine::Warning:
111 return 2;
112 case DiagnosticsEngine::Fatal:
113 case DiagnosticsEngine::Error:
114 return 1;
115 case DiagnosticsEngine::Ignored:
116 return 0;
117 }
118 llvm_unreachable("Unknown diagnostic level!");
119}
120
Sam McCall8111d3b2017-12-13 08:48:42 +0000121// Checks whether a location is within a half-open range.
122// Note that clang also uses closed source ranges, which this can't handle!
123bool locationInRange(SourceLocation L, CharSourceRange R,
124 const SourceManager &M) {
125 assert(R.isCharRange());
126 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
127 M.getFileID(R.getBegin()) != M.getFileID(L))
128 return false;
129 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
130}
131
132// Converts a half-open clang source range to an LSP range.
133// Note that clang also uses closed source ranges, which this can't handle!
134Range toRange(CharSourceRange R, const SourceManager &M) {
135 // Clang is 1-based, LSP uses 0-based indexes.
136 return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
137 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
138 {static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
139 static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
140}
141
142// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
143// LSP needs a single range.
144Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
145 auto &M = D.getSourceManager();
146 auto Loc = M.getFileLoc(D.getLocation());
147 // Accept the first range that contains the location.
148 for (const auto &CR : D.getRanges()) {
149 auto R = Lexer::makeFileCharRange(CR, M, L);
150 if (locationInRange(Loc, R, M))
151 return toRange(R, M);
152 }
153 // The range may be given as a fixit hint instead.
154 for (const auto &F : D.getFixItHints()) {
155 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
156 if (locationInRange(Loc, R, M))
157 return toRange(R, M);
158 }
159 // If no suitable range is found, just use the token at the location.
160 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
161 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
162 R = CharSourceRange::getCharRange(Loc);
163 return toRange(R, M);
164}
165
166TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
167 const LangOptions &L) {
168 TextEdit Result;
169 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
170 Result.newText = FixIt.CodeToInsert;
171 return Result;
172}
173
174llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
175 DiagnosticsEngine::Level Level,
176 const LangOptions &LangOpts) {
177 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
178 !D.getSourceManager().isInMainFile(D.getLocation()))
Ilya Biryukov04db3682017-07-21 13:29:29 +0000179 return llvm::None;
180
Sam McCall8111d3b2017-12-13 08:48:42 +0000181 DiagWithFixIts Result;
182 Result.Diag.range = diagnosticRange(D, LangOpts);
183 Result.Diag.severity = getSeverity(Level);
184 SmallString<64> Message;
185 D.FormatDiagnostic(Message);
186 Result.Diag.message = Message.str();
187 for (const FixItHint &Fix : D.getFixItHints())
188 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
189 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000190}
191
192class StoreDiagsConsumer : public DiagnosticConsumer {
193public:
194 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
195
Sam McCall8111d3b2017-12-13 08:48:42 +0000196 // Track language options in case we need to expand token ranges.
197 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
198 LangOpts = Opts;
199 }
200
201 void EndSourceFile() override { LangOpts = llvm::None; }
202
Ilya Biryukov04db3682017-07-21 13:29:29 +0000203 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
204 const clang::Diagnostic &Info) override {
205 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
206
Sam McCall8111d3b2017-12-13 08:48:42 +0000207 if (LangOpts)
208 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
209 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000210 }
211
212private:
213 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000214 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000215};
216
Ilya Biryukov02d58702017-08-01 15:51:38 +0000217template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
218 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
219}
220
Ilya Biryukov04db3682017-07-21 13:29:29 +0000221} // namespace
222
Ilya Biryukov02d58702017-08-01 15:51:38 +0000223void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
224 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000225}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227llvm::Optional<ParsedAST>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000228ParsedAST::Build(const Context &Ctx,
229 std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000230 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000231 std::unique_ptr<llvm::MemoryBuffer> Buffer,
232 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000233 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000234
235 std::vector<DiagWithFixIts> ASTDiags;
236 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
237
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000238 const PrecompiledPreamble *PreamblePCH =
239 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000240 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000241 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000242 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000243
244 // Recover resources if we crash before exiting this method.
245 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
246 Clang.get());
247
248 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000249 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
250 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000251 log(Ctx, "BeginSourceFile() failed when building AST for " +
252 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000253 return llvm::None;
254 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000255 if (!Action->Execute())
Ilya Biryukov940901e2017-12-13 12:51:22 +0000256 log(Ctx, "Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000257
258 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
259 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000260 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000261
262 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000263 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
264 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000265}
266
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000267namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268
269SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000270 const FileEntry *FE, Position Pos) {
271 SourceLocation InputLoc =
272 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
273 return Mgr.getMacroArgExpandedLocation(InputLoc);
274}
275
Ilya Biryukov02d58702017-08-01 15:51:38 +0000276} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000277
Ilya Biryukov02d58702017-08-01 15:51:38 +0000278void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000279 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000280 return;
281
282 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000283 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000284
285 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000286 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000287 // Resolve the declaration ID to an actual declaration, possibly
288 // deserializing the declaration in the process.
289 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
290 Resolved.push_back(D);
291 }
292
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000293 TopLevelDecls.reserve(TopLevelDecls.size() +
294 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000295 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
296
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000297 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000298}
299
Ilya Biryukov02d58702017-08-01 15:51:38 +0000300ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000301
Ilya Biryukov02d58702017-08-01 15:51:38 +0000302ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000303
Ilya Biryukov02d58702017-08-01 15:51:38 +0000304ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000305 if (Action) {
306 Action->EndSourceFile();
307 }
308}
309
Ilya Biryukov02d58702017-08-01 15:51:38 +0000310ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
311
312const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000313 return Clang->getASTContext();
314}
315
Ilya Biryukov02d58702017-08-01 15:51:38 +0000316Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000317
Eric Liu76f6b442018-01-09 17:32:00 +0000318std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
319 return Clang->getPreprocessorPtr();
320}
321
Ilya Biryukov02d58702017-08-01 15:51:38 +0000322const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000323 return Clang->getPreprocessor();
324}
325
Ilya Biryukov02d58702017-08-01 15:51:38 +0000326ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000327 ensurePreambleDeclsDeserialized();
328 return TopLevelDecls;
329}
330
Ilya Biryukov02d58702017-08-01 15:51:38 +0000331const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000332 return Diags;
333}
334
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000335PreambleData::PreambleData(PrecompiledPreamble Preamble,
336 std::vector<serialization::DeclID> TopLevelDeclIDs,
337 std::vector<DiagWithFixIts> Diags)
338 : Preamble(std::move(Preamble)),
339 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
340
341ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
342 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000343 std::unique_ptr<FrontendAction> Action,
344 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000345 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000346 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
347 Action(std::move(Action)), Diags(std::move(Diags)),
348 TopLevelDecls(std::move(TopLevelDecls)),
349 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000350 assert(this->Clang);
351 assert(this->Action);
352}
353
Ilya Biryukov02d58702017-08-01 15:51:38 +0000354ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
355 : AST(std::move(Wrapper.AST)) {}
356
357ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
358 : AST(std::move(AST)) {}
359
Ilya Biryukov02d58702017-08-01 15:51:38 +0000360std::shared_ptr<CppFile>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000361CppFile::Create(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000362 std::shared_ptr<PCHContainerOperations> PCHs,
363 ASTParsedCallback ASTCallback) {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000364 return std::shared_ptr<CppFile>(new CppFile(FileName, StorePreamblesInMemory,
365 std::move(PCHs),
366 std::move(ASTCallback)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000367}
368
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000369CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000370 std::shared_ptr<PCHContainerOperations> PCHs,
371 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000372 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
373 RebuildCounter(0), RebuildInProgress(false), PCHs(std::move(PCHs)),
Eric Liubfac8f72017-12-19 18:00:37 +0000374 ASTCallback(std::move(ASTCallback)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000375 // FIXME(ibiryukov): we should pass a proper Context here.
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000376 log(Context::empty(), "Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000377
378 std::lock_guard<std::mutex> Lock(Mutex);
379 LatestAvailablePreamble = nullptr;
380 PreamblePromise.set_value(nullptr);
381 PreambleFuture = PreamblePromise.get_future();
382
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000383 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000384 ASTFuture = ASTPromise.get_future();
385}
386
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000387void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000388
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000389UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390 std::unique_lock<std::mutex> Lock(Mutex);
391 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000392 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000393 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
394 // We want to keep this invariant.
395 if (futureIsReady(PreambleFuture)) {
396 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
397 PreambleFuture = PreamblePromise.get_future();
398 }
399 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000400 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000401 ASTFuture = ASTPromise.get_future();
402 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000404 Lock.unlock();
405 // Notify about changes to RebuildCounter.
406 RebuildCond.notify_all();
407
408 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000409 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000410 std::unique_lock<std::mutex> Lock(That->Mutex);
411 CppFile *This = &*That;
412 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
413 return !This->RebuildInProgress ||
414 This->RebuildCounter != RequestRebuildCounter;
415 });
416
417 // This computation got cancelled itself, do nothing.
418 if (This->RebuildCounter != RequestRebuildCounter)
419 return;
420
421 // Set empty results for Promises.
422 That->PreamblePromise.set_value(nullptr);
423 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000424 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000425}
426
427llvm::Optional<std::vector<DiagWithFixIts>>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000428CppFile::rebuild(const Context &Ctx, ParseInputs &&Inputs) {
429 return deferRebuild(std::move(Inputs))(Ctx);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000430}
431
Ilya Biryukov940901e2017-12-13 12:51:22 +0000432UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000433CppFile::deferRebuild(ParseInputs &&Inputs) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000434 std::shared_ptr<const PreambleData> OldPreamble;
435 std::shared_ptr<PCHContainerOperations> PCHs;
436 unsigned RequestRebuildCounter;
437 {
438 std::unique_lock<std::mutex> Lock(Mutex);
439 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
440 // They will try to exit as early as possible and won't call set_value on
441 // our promises.
442 RequestRebuildCounter = ++this->RebuildCounter;
443 PCHs = this->PCHs;
444
445 // Remember the preamble to be used during rebuild.
446 OldPreamble = this->LatestAvailablePreamble;
447 // Setup std::promises and std::futures for Preamble and AST. Corresponding
448 // futures will wait until the rebuild process is finished.
449 if (futureIsReady(this->PreambleFuture)) {
450 this->PreamblePromise =
451 std::promise<std::shared_ptr<const PreambleData>>();
452 this->PreambleFuture = this->PreamblePromise.get_future();
453 }
454 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000455 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000456 this->ASTFuture = this->ASTPromise.get_future();
457 }
458 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000459 // Notify about changes to RebuildCounter.
460 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000461
462 // A helper to function to finish the rebuild. May be run on a different
463 // thread.
464
465 // Don't let this CppFile die before rebuild is finished.
466 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000467 auto FinishRebuild =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000468 [OldPreamble, RequestRebuildCounter, PCHs,
469 That](ParseInputs Inputs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000470 const Context &Ctx) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000471 -> llvm::Optional<std::vector<DiagWithFixIts>> {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000472 log(Context::empty(),
473 "Rebuilding file " + That->FileName + " with command [" +
474 Inputs.CompileCommand.Directory + "] " +
475 llvm::join(Inputs.CompileCommand.CommandLine, " "));
476
Ilya Biryukov02d58702017-08-01 15:51:38 +0000477 // Only one execution of this method is possible at a time.
478 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
479 // into a state for doing a rebuild.
480 RebuildGuard Rebuild(*That, RequestRebuildCounter);
481 if (Rebuild.wasCancelledBeforeConstruction())
482 return llvm::None;
483
484 std::vector<const char *> ArgStrs;
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000485 for (const auto &S : Inputs.CompileCommand.CommandLine)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000486 ArgStrs.push_back(S.c_str());
487
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000488 Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000489
490 std::unique_ptr<CompilerInvocation> CI;
491 {
492 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
493 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000494 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000495 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
496 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000497 &IgnoreDiagnostics, false);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000498 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
499 Inputs.FS);
Sam McCall98775c52017-12-04 13:49:59 +0000500 // createInvocationFromCommandLine sets DisableFree.
501 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000502 }
503 assert(CI && "Couldn't create CompilerInvocation");
504
505 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000506 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000507
508 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000509 // not mutate any fields of CppFile, only does the actual computation.
510 // Lamdba is marked mutable to call reset() on OldPreamble.
511 auto DoRebuildPreamble =
512 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000513 auto Bounds =
514 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000515 if (OldPreamble &&
516 OldPreamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
517 Inputs.FS.get())) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000518 log(Ctx, "Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000519 return OldPreamble;
520 }
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000521 log(Ctx, "Premble for file " + Twine(That->FileName) +
522 " cannot be reused. Attempting to rebuild it.");
523 // We won't need the OldPreamble anymore, release it so it can be
524 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000525 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000526
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000527 trace::Span Tracer(Ctx, "Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000528 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000529 std::vector<DiagWithFixIts> PreambleDiags;
530 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
531 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
532 CompilerInstance::createDiagnostics(
533 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000534
535 // Skip function bodies when building the preamble to speed up building
536 // the preamble and make it smaller.
537 assert(!CI->getFrontendOpts().SkipFunctionBodies);
538 CI->getFrontendOpts().SkipFunctionBodies = true;
539
Ilya Biryukov02d58702017-08-01 15:51:38 +0000540 CppFilePreambleCallbacks SerializedDeclsCollector;
541 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000542 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS,
543 PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000544 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000545 SerializedDeclsCollector);
546
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000547 // When building the AST for the main file, we do want the function
548 // bodies.
549 CI->getFrontendOpts().SkipFunctionBodies = false;
550
Ilya Biryukov02d58702017-08-01 15:51:38 +0000551 if (BuiltPreamble) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000552 log(Ctx, "Built preamble of size " + Twine(BuiltPreamble->getSize()) +
553 " for file " + Twine(That->FileName));
554
Ilya Biryukov02d58702017-08-01 15:51:38 +0000555 return std::make_shared<PreambleData>(
556 std::move(*BuiltPreamble),
557 SerializedDeclsCollector.takeTopLevelDeclIDs(),
558 std::move(PreambleDiags));
559 } else {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000560 log(Ctx,
561 "Could not build a preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000562 return nullptr;
563 }
564 };
565
566 // Compute updated Preamble.
567 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
568 // Publish the new Preamble.
569 {
570 std::lock_guard<std::mutex> Lock(That->Mutex);
571 // We always set LatestAvailablePreamble to the new value, hoping that it
572 // will still be usable in the further requests.
573 That->LatestAvailablePreamble = NewPreamble;
574 if (RequestRebuildCounter != That->RebuildCounter)
575 return llvm::None; // Our rebuild request was cancelled, do nothing.
576 That->PreamblePromise.set_value(NewPreamble);
577 } // unlock Mutex
578
579 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000580 std::vector<DiagWithFixIts> Diagnostics;
581 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000582 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
583 NewPreamble->Diags.end());
584 }
585
586 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000587 llvm::Optional<ParsedAST> NewAST;
588 {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000589 trace::Span Tracer(Ctx, "Build");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000590 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000591 NewAST = ParsedAST::Build(Ctx, std::move(CI), std::move(NewPreamble),
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000592 std::move(ContentsBuffer), PCHs, Inputs.FS);
Sam McCall8567cb32017-11-02 09:21:51 +0000593 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000594
595 if (NewAST) {
596 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
597 NewAST->getDiagnostics().end());
Eric Liubfac8f72017-12-19 18:00:37 +0000598 if (That->ASTCallback)
599 That->ASTCallback(Ctx, That->FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000600 } else {
601 // Don't report even Preamble diagnostics if we coulnd't build AST.
602 Diagnostics.clear();
603 }
604
605 // Publish the new AST.
606 {
607 std::lock_guard<std::mutex> Lock(That->Mutex);
608 if (RequestRebuildCounter != That->RebuildCounter)
609 return Diagnostics; // Our rebuild request was cancelled, don't set
610 // ASTPromise.
611
Ilya Biryukov574b7532017-08-02 09:08:39 +0000612 That->ASTPromise.set_value(
613 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000614 } // unlock Mutex
615
616 return Diagnostics;
617 };
618
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000619 return BindWithForward(FinishRebuild, std::move(Inputs));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000620}
621
622std::shared_future<std::shared_ptr<const PreambleData>>
623CppFile::getPreamble() const {
624 std::lock_guard<std::mutex> Lock(Mutex);
625 return PreambleFuture;
626}
627
628std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
629 std::lock_guard<std::mutex> Lock(Mutex);
630 return LatestAvailablePreamble;
631}
632
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000633std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000634 std::lock_guard<std::mutex> Lock(Mutex);
635 return ASTFuture;
636}
637
Ilya Biryukov02d58702017-08-01 15:51:38 +0000638CppFile::RebuildGuard::RebuildGuard(CppFile &File,
639 unsigned RequestRebuildCounter)
640 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
641 std::unique_lock<std::mutex> Lock(File.Mutex);
642 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
643 if (WasCancelledBeforeConstruction)
644 return;
645
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000646 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
647 return !File.RebuildInProgress ||
648 File.RebuildCounter != RequestRebuildCounter;
649 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000650
651 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
652 if (WasCancelledBeforeConstruction)
653 return;
654
655 File.RebuildInProgress = true;
656}
657
658bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
659 return WasCancelledBeforeConstruction;
660}
661
662CppFile::RebuildGuard::~RebuildGuard() {
663 if (WasCancelledBeforeConstruction)
664 return;
665
666 std::unique_lock<std::mutex> Lock(File.Mutex);
667 assert(File.RebuildInProgress);
668 File.RebuildInProgress = false;
669
670 if (File.RebuildCounter == RequestRebuildCounter) {
671 // Our rebuild request was successful.
672 assert(futureIsReady(File.ASTFuture));
673 assert(futureIsReady(File.PreambleFuture));
674 } else {
675 // Our rebuild request was cancelled, because further reparse was requested.
676 assert(!futureIsReady(File.ASTFuture));
677 assert(!futureIsReady(File.PreambleFuture));
678 }
679
680 Lock.unlock();
681 File.RebuildCond.notify_all();
682}
Haojian Wu345099c2017-11-09 11:30:04 +0000683
684SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
685 const Position &Pos,
686 const FileEntry *FE) {
687 // The language server protocol uses zero-based line and column numbers.
688 // Clang uses one-based numbers.
689
690 const ASTContext &AST = Unit.getASTContext();
691 const SourceManager &SourceMgr = AST.getSourceManager();
692
693 SourceLocation InputLocation =
694 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
695 if (Pos.character == 0) {
696 return InputLocation;
697 }
698
699 // This handle cases where the position is in the middle of a token or right
700 // after the end of a token. In theory we could just use GetBeginningOfToken
701 // to find the start of the token at the input position, but this doesn't
702 // work when right after the end, i.e. foo|.
703 // So try to go back by one and see if we're still inside the an identifier
704 // token. If so, Take the beginning of this token.
705 // (It should be the same identifier because you can't have two adjacent
706 // identifiers without another token in between.)
707 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
708 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
709 Token Result;
710 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
711 AST.getLangOpts(), false)) {
712 // getRawToken failed, just use InputLocation.
713 return InputLocation;
714 }
715
716 if (Result.is(tok::raw_identifier)) {
717 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
718 AST.getLangOpts());
719 }
720
721 return InputLocation;
722}