blob: 6d65ef7273b27235b47884424b3bddbf4ed489aa [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 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000458 this->LastCommand = Inputs.CompileCommand;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000459 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000460 // Notify about changes to RebuildCounter.
461 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000462
463 // A helper to function to finish the rebuild. May be run on a different
464 // thread.
465
466 // Don't let this CppFile die before rebuild is finished.
467 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000468 auto FinishRebuild =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000469 [OldPreamble, RequestRebuildCounter, PCHs,
470 That](ParseInputs Inputs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000471 const Context &Ctx) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000472 -> llvm::Optional<std::vector<DiagWithFixIts>> {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000473 log(Context::empty(),
474 "Rebuilding file " + That->FileName + " with command [" +
475 Inputs.CompileCommand.Directory + "] " +
476 llvm::join(Inputs.CompileCommand.CommandLine, " "));
477
Ilya Biryukov02d58702017-08-01 15:51:38 +0000478 // Only one execution of this method is possible at a time.
479 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
480 // into a state for doing a rebuild.
481 RebuildGuard Rebuild(*That, RequestRebuildCounter);
482 if (Rebuild.wasCancelledBeforeConstruction())
483 return llvm::None;
484
485 std::vector<const char *> ArgStrs;
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000486 for (const auto &S : Inputs.CompileCommand.CommandLine)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000487 ArgStrs.push_back(S.c_str());
488
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000489 Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000490
491 std::unique_ptr<CompilerInvocation> CI;
492 {
493 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
494 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000495 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000496 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
497 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000498 &IgnoreDiagnostics, false);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000499 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
500 Inputs.FS);
Sam McCall98775c52017-12-04 13:49:59 +0000501 // createInvocationFromCommandLine sets DisableFree.
502 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000503 }
504 assert(CI && "Couldn't create CompilerInvocation");
505
506 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000507 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000508
509 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000510 // not mutate any fields of CppFile, only does the actual computation.
511 // Lamdba is marked mutable to call reset() on OldPreamble.
512 auto DoRebuildPreamble =
513 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000514 auto Bounds =
515 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000516 if (OldPreamble &&
517 OldPreamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
518 Inputs.FS.get())) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000519 log(Ctx, "Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000520 return OldPreamble;
521 }
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000522 log(Ctx, "Premble for file " + Twine(That->FileName) +
523 " cannot be reused. Attempting to rebuild it.");
524 // We won't need the OldPreamble anymore, release it so it can be
525 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000526 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000527
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000528 trace::Span Tracer(Ctx, "Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000529 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000530 std::vector<DiagWithFixIts> PreambleDiags;
531 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
532 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
533 CompilerInstance::createDiagnostics(
534 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000535
536 // Skip function bodies when building the preamble to speed up building
537 // the preamble and make it smaller.
538 assert(!CI->getFrontendOpts().SkipFunctionBodies);
539 CI->getFrontendOpts().SkipFunctionBodies = true;
540
Ilya Biryukov02d58702017-08-01 15:51:38 +0000541 CppFilePreambleCallbacks SerializedDeclsCollector;
542 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000543 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS,
544 PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000545 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000546 SerializedDeclsCollector);
547
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000548 // When building the AST for the main file, we do want the function
549 // bodies.
550 CI->getFrontendOpts().SkipFunctionBodies = false;
551
Ilya Biryukov02d58702017-08-01 15:51:38 +0000552 if (BuiltPreamble) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000553 log(Ctx, "Built preamble of size " + Twine(BuiltPreamble->getSize()) +
554 " for file " + Twine(That->FileName));
555
Ilya Biryukov02d58702017-08-01 15:51:38 +0000556 return std::make_shared<PreambleData>(
557 std::move(*BuiltPreamble),
558 SerializedDeclsCollector.takeTopLevelDeclIDs(),
559 std::move(PreambleDiags));
560 } else {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000561 log(Ctx,
562 "Could not build a preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000563 return nullptr;
564 }
565 };
566
567 // Compute updated Preamble.
568 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
569 // Publish the new Preamble.
570 {
571 std::lock_guard<std::mutex> Lock(That->Mutex);
572 // We always set LatestAvailablePreamble to the new value, hoping that it
573 // will still be usable in the further requests.
574 That->LatestAvailablePreamble = NewPreamble;
575 if (RequestRebuildCounter != That->RebuildCounter)
576 return llvm::None; // Our rebuild request was cancelled, do nothing.
577 That->PreamblePromise.set_value(NewPreamble);
578 } // unlock Mutex
579
580 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000581 std::vector<DiagWithFixIts> Diagnostics;
582 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000583 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
584 NewPreamble->Diags.end());
585 }
586
587 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000588 llvm::Optional<ParsedAST> NewAST;
589 {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000590 trace::Span Tracer(Ctx, "Build");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000591 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000592 NewAST = ParsedAST::Build(Ctx, std::move(CI), std::move(NewPreamble),
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000593 std::move(ContentsBuffer), PCHs, Inputs.FS);
Sam McCall8567cb32017-11-02 09:21:51 +0000594 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000595
596 if (NewAST) {
597 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
598 NewAST->getDiagnostics().end());
Eric Liubfac8f72017-12-19 18:00:37 +0000599 if (That->ASTCallback)
600 That->ASTCallback(Ctx, That->FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000601 } else {
602 // Don't report even Preamble diagnostics if we coulnd't build AST.
603 Diagnostics.clear();
604 }
605
606 // Publish the new AST.
607 {
608 std::lock_guard<std::mutex> Lock(That->Mutex);
609 if (RequestRebuildCounter != That->RebuildCounter)
610 return Diagnostics; // Our rebuild request was cancelled, don't set
611 // ASTPromise.
612
Ilya Biryukov574b7532017-08-02 09:08:39 +0000613 That->ASTPromise.set_value(
614 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000615 } // unlock Mutex
616
617 return Diagnostics;
618 };
619
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000620 return BindWithForward(FinishRebuild, std::move(Inputs));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000621}
622
623std::shared_future<std::shared_ptr<const PreambleData>>
624CppFile::getPreamble() const {
625 std::lock_guard<std::mutex> Lock(Mutex);
626 return PreambleFuture;
627}
628
629std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
630 std::lock_guard<std::mutex> Lock(Mutex);
631 return LatestAvailablePreamble;
632}
633
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000634std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000635 std::lock_guard<std::mutex> Lock(Mutex);
636 return ASTFuture;
637}
638
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000639llvm::Optional<tooling::CompileCommand> CppFile::getLastCommand() const {
640 std::lock_guard<std::mutex> Lock(Mutex);
641 return LastCommand;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000642}
643
644CppFile::RebuildGuard::RebuildGuard(CppFile &File,
645 unsigned RequestRebuildCounter)
646 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
647 std::unique_lock<std::mutex> Lock(File.Mutex);
648 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
649 if (WasCancelledBeforeConstruction)
650 return;
651
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000652 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
653 return !File.RebuildInProgress ||
654 File.RebuildCounter != RequestRebuildCounter;
655 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000656
657 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
658 if (WasCancelledBeforeConstruction)
659 return;
660
661 File.RebuildInProgress = true;
662}
663
664bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
665 return WasCancelledBeforeConstruction;
666}
667
668CppFile::RebuildGuard::~RebuildGuard() {
669 if (WasCancelledBeforeConstruction)
670 return;
671
672 std::unique_lock<std::mutex> Lock(File.Mutex);
673 assert(File.RebuildInProgress);
674 File.RebuildInProgress = false;
675
676 if (File.RebuildCounter == RequestRebuildCounter) {
677 // Our rebuild request was successful.
678 assert(futureIsReady(File.ASTFuture));
679 assert(futureIsReady(File.PreambleFuture));
680 } else {
681 // Our rebuild request was cancelled, because further reparse was requested.
682 assert(!futureIsReady(File.ASTFuture));
683 assert(!futureIsReady(File.PreambleFuture));
684 }
685
686 Lock.unlock();
687 File.RebuildCond.notify_all();
688}
Haojian Wu345099c2017-11-09 11:30:04 +0000689
690SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
691 const Position &Pos,
692 const FileEntry *FE) {
693 // The language server protocol uses zero-based line and column numbers.
694 // Clang uses one-based numbers.
695
696 const ASTContext &AST = Unit.getASTContext();
697 const SourceManager &SourceMgr = AST.getSourceManager();
698
699 SourceLocation InputLocation =
700 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
701 if (Pos.character == 0) {
702 return InputLocation;
703 }
704
705 // This handle cases where the position is in the middle of a token or right
706 // after the end of a token. In theory we could just use GetBeginningOfToken
707 // to find the start of the token at the input position, but this doesn't
708 // work when right after the end, i.e. foo|.
709 // So try to go back by one and see if we're still inside the an identifier
710 // token. If so, Take the beginning of this token.
711 // (It should be the same identifier because you can't have two adjacent
712 // identifiers without another token in between.)
713 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
714 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
715 Token Result;
716 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
717 AST.getLangOpts(), false)) {
718 // getRawToken failed, just use InputLocation.
719 return InputLocation;
720 }
721
722 if (Result.is(tok::raw_identifier)) {
723 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
724 AST.getLangOpts());
725 }
726
727 return InputLocation;
728}