blob: 82ca109d2a53b3db2089c85872f1dc13e356468a [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 Biryukov0e6a51f2017-12-12 12:27:47 +0000276
Ilya Biryukov02d58702017-08-01 15:51:38 +0000277} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000278
Ilya Biryukov02d58702017-08-01 15:51:38 +0000279void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000280 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000281 return;
282
283 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000284 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000285
286 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000287 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000288 // Resolve the declaration ID to an actual declaration, possibly
289 // deserializing the declaration in the process.
290 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
291 Resolved.push_back(D);
292 }
293
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000294 TopLevelDecls.reserve(TopLevelDecls.size() +
295 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000296 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
297
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000298 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000299}
300
Ilya Biryukov02d58702017-08-01 15:51:38 +0000301ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000302
Ilya Biryukov02d58702017-08-01 15:51:38 +0000303ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000304
Ilya Biryukov02d58702017-08-01 15:51:38 +0000305ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000306 if (Action) {
307 Action->EndSourceFile();
308 }
309}
310
Ilya Biryukov02d58702017-08-01 15:51:38 +0000311ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
312
313const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000314 return Clang->getASTContext();
315}
316
Ilya Biryukov02d58702017-08-01 15:51:38 +0000317Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000318
Ilya Biryukov02d58702017-08-01 15:51:38 +0000319const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000320 return Clang->getPreprocessor();
321}
322
Ilya Biryukov02d58702017-08-01 15:51:38 +0000323ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000324 ensurePreambleDeclsDeserialized();
325 return TopLevelDecls;
326}
327
Ilya Biryukov02d58702017-08-01 15:51:38 +0000328const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000329 return Diags;
330}
331
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000332PreambleData::PreambleData(PrecompiledPreamble Preamble,
333 std::vector<serialization::DeclID> TopLevelDeclIDs,
334 std::vector<DiagWithFixIts> Diags)
335 : Preamble(std::move(Preamble)),
336 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
337
338ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
339 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000340 std::unique_ptr<FrontendAction> Action,
341 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000342 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000343 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
344 Action(std::move(Action)), Diags(std::move(Diags)),
345 TopLevelDecls(std::move(TopLevelDecls)),
346 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000347 assert(this->Clang);
348 assert(this->Action);
349}
350
Ilya Biryukov02d58702017-08-01 15:51:38 +0000351ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
352 : AST(std::move(Wrapper.AST)) {}
353
354ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
355 : AST(std::move(AST)) {}
356
Ilya Biryukov02d58702017-08-01 15:51:38 +0000357std::shared_ptr<CppFile>
358CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000359 bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000360 std::shared_ptr<PCHContainerOperations> PCHs,
361 ASTParsedCallback ASTCallback) {
362 return std::shared_ptr<CppFile>(
363 new CppFile(FileName, std::move(Command), StorePreamblesInMemory,
364 std::move(PCHs), std::move(ASTCallback)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000365}
366
367CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000368 bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000369 std::shared_ptr<PCHContainerOperations> PCHs,
370 ASTParsedCallback ASTCallback)
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000371 : FileName(FileName), Command(std::move(Command)),
372 StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
Eric Liubfac8f72017-12-19 18:00:37 +0000373 RebuildInProgress(false), PCHs(std::move(PCHs)),
374 ASTCallback(std::move(ASTCallback)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000375 // FIXME(ibiryukov): we should pass a proper Context here.
376 log(Context::empty(), "Opened file " + FileName + " with command [" +
377 this->Command.Directory + "] " +
378 llvm::join(this->Command.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000379
380 std::lock_guard<std::mutex> Lock(Mutex);
381 LatestAvailablePreamble = nullptr;
382 PreamblePromise.set_value(nullptr);
383 PreambleFuture = PreamblePromise.get_future();
384
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000385 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000386 ASTFuture = ASTPromise.get_future();
387}
388
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000389void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000390
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000391UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000392 std::unique_lock<std::mutex> Lock(Mutex);
393 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000394 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000395 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
396 // We want to keep this invariant.
397 if (futureIsReady(PreambleFuture)) {
398 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
399 PreambleFuture = PreamblePromise.get_future();
400 }
401 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000402 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403 ASTFuture = ASTPromise.get_future();
404 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000405
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000406 Lock.unlock();
407 // Notify about changes to RebuildCounter.
408 RebuildCond.notify_all();
409
410 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000411 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000412 std::unique_lock<std::mutex> Lock(That->Mutex);
413 CppFile *This = &*That;
414 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
415 return !This->RebuildInProgress ||
416 This->RebuildCounter != RequestRebuildCounter;
417 });
418
419 // This computation got cancelled itself, do nothing.
420 if (This->RebuildCounter != RequestRebuildCounter)
421 return;
422
423 // Set empty results for Promises.
424 That->PreamblePromise.set_value(nullptr);
425 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000426 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000427}
428
429llvm::Optional<std::vector<DiagWithFixIts>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000430CppFile::rebuild(const Context &Ctx, StringRef NewContents,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000431 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000432 return deferRebuild(NewContents, std::move(VFS))(Ctx);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000433}
434
Ilya Biryukov940901e2017-12-13 12:51:22 +0000435UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov02d58702017-08-01 15:51:38 +0000436CppFile::deferRebuild(StringRef NewContents,
437 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
438 std::shared_ptr<const PreambleData> OldPreamble;
439 std::shared_ptr<PCHContainerOperations> PCHs;
440 unsigned RequestRebuildCounter;
441 {
442 std::unique_lock<std::mutex> Lock(Mutex);
443 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
444 // They will try to exit as early as possible and won't call set_value on
445 // our promises.
446 RequestRebuildCounter = ++this->RebuildCounter;
447 PCHs = this->PCHs;
448
449 // Remember the preamble to be used during rebuild.
450 OldPreamble = this->LatestAvailablePreamble;
451 // Setup std::promises and std::futures for Preamble and AST. Corresponding
452 // futures will wait until the rebuild process is finished.
453 if (futureIsReady(this->PreambleFuture)) {
454 this->PreamblePromise =
455 std::promise<std::shared_ptr<const PreambleData>>();
456 this->PreambleFuture = this->PreamblePromise.get_future();
457 }
458 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000459 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000460 this->ASTFuture = this->ASTPromise.get_future();
461 }
462 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000463 // Notify about changes to RebuildCounter.
464 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000465
466 // A helper to function to finish the rebuild. May be run on a different
467 // thread.
468
469 // Don't let this CppFile die before rebuild is finished.
470 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000471 auto FinishRebuild =
472 [OldPreamble, VFS, RequestRebuildCounter, PCHs,
473 That](std::string NewContents,
474 const Context &Ctx) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000475 -> llvm::Optional<std::vector<DiagWithFixIts>> {
476 // Only one execution of this method is possible at a time.
477 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
478 // into a state for doing a rebuild.
479 RebuildGuard Rebuild(*That, RequestRebuildCounter);
480 if (Rebuild.wasCancelledBeforeConstruction())
481 return llvm::None;
482
483 std::vector<const char *> ArgStrs;
484 for (const auto &S : That->Command.CommandLine)
485 ArgStrs.push_back(S.c_str());
486
487 VFS->setCurrentWorkingDirectory(That->Command.Directory);
488
489 std::unique_ptr<CompilerInvocation> CI;
490 {
491 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
492 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000493 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000494 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
495 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000496 &IgnoreDiagnostics, false);
497 CI =
498 createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine, VFS);
499 // createInvocationFromCommandLine sets DisableFree.
500 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000501 }
502 assert(CI && "Couldn't create CompilerInvocation");
503
504 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
505 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
506
507 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000508 // not mutate any fields of CppFile, only does the actual computation.
509 // Lamdba is marked mutable to call reset() on OldPreamble.
510 auto DoRebuildPreamble =
511 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000512 auto Bounds =
513 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
514 if (OldPreamble && OldPreamble->Preamble.CanReuse(
515 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000516 log(Ctx, "Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000517 return OldPreamble;
518 }
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000519 log(Ctx, "Premble for file " + Twine(That->FileName) +
520 " cannot be reused. Attempting to rebuild it.");
521 // We won't need the OldPreamble anymore, release it so it can be
522 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000523 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000524
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000525 trace::Span Tracer(Ctx, "Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000526 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000527 std::vector<DiagWithFixIts> PreambleDiags;
528 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
529 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
530 CompilerInstance::createDiagnostics(
531 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000532
533 // Skip function bodies when building the preamble to speed up building
534 // the preamble and make it smaller.
535 assert(!CI->getFrontendOpts().SkipFunctionBodies);
536 CI->getFrontendOpts().SkipFunctionBodies = true;
537
Ilya Biryukov02d58702017-08-01 15:51:38 +0000538 CppFilePreambleCallbacks SerializedDeclsCollector;
539 auto BuiltPreamble = PrecompiledPreamble::Build(
540 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000541 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000542 SerializedDeclsCollector);
543
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000544 // When building the AST for the main file, we do want the function
545 // bodies.
546 CI->getFrontendOpts().SkipFunctionBodies = false;
547
Ilya Biryukov02d58702017-08-01 15:51:38 +0000548 if (BuiltPreamble) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000549 log(Ctx, "Built preamble of size " + Twine(BuiltPreamble->getSize()) +
550 " for file " + Twine(That->FileName));
551
Ilya Biryukov02d58702017-08-01 15:51:38 +0000552 return std::make_shared<PreambleData>(
553 std::move(*BuiltPreamble),
554 SerializedDeclsCollector.takeTopLevelDeclIDs(),
555 std::move(PreambleDiags));
556 } else {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000557 log(Ctx,
558 "Could not build a preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000559 return nullptr;
560 }
561 };
562
563 // Compute updated Preamble.
564 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
565 // Publish the new Preamble.
566 {
567 std::lock_guard<std::mutex> Lock(That->Mutex);
568 // We always set LatestAvailablePreamble to the new value, hoping that it
569 // will still be usable in the further requests.
570 That->LatestAvailablePreamble = NewPreamble;
571 if (RequestRebuildCounter != That->RebuildCounter)
572 return llvm::None; // Our rebuild request was cancelled, do nothing.
573 That->PreamblePromise.set_value(NewPreamble);
574 } // unlock Mutex
575
576 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000577 std::vector<DiagWithFixIts> Diagnostics;
578 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000579 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
580 NewPreamble->Diags.end());
581 }
582
583 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000584 llvm::Optional<ParsedAST> NewAST;
585 {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000586 trace::Span Tracer(Ctx, "Build");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000587 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000588 NewAST = ParsedAST::Build(Ctx, std::move(CI), std::move(NewPreamble),
589 std::move(ContentsBuffer), PCHs, VFS);
Sam McCall8567cb32017-11-02 09:21:51 +0000590 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000591
592 if (NewAST) {
593 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
594 NewAST->getDiagnostics().end());
Eric Liubfac8f72017-12-19 18:00:37 +0000595 if (That->ASTCallback)
596 That->ASTCallback(Ctx, That->FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000597 } else {
598 // Don't report even Preamble diagnostics if we coulnd't build AST.
599 Diagnostics.clear();
600 }
601
602 // Publish the new AST.
603 {
604 std::lock_guard<std::mutex> Lock(That->Mutex);
605 if (RequestRebuildCounter != That->RebuildCounter)
606 return Diagnostics; // Our rebuild request was cancelled, don't set
607 // ASTPromise.
608
Ilya Biryukov574b7532017-08-02 09:08:39 +0000609 That->ASTPromise.set_value(
610 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000611 } // unlock Mutex
612
613 return Diagnostics;
614 };
615
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000616 return BindWithForward(FinishRebuild, NewContents.str());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000617}
618
619std::shared_future<std::shared_ptr<const PreambleData>>
620CppFile::getPreamble() const {
621 std::lock_guard<std::mutex> Lock(Mutex);
622 return PreambleFuture;
623}
624
625std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
626 std::lock_guard<std::mutex> Lock(Mutex);
627 return LatestAvailablePreamble;
628}
629
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000630std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000631 std::lock_guard<std::mutex> Lock(Mutex);
632 return ASTFuture;
633}
634
635tooling::CompileCommand const &CppFile::getCompileCommand() const {
636 return Command;
637}
638
639CppFile::RebuildGuard::RebuildGuard(CppFile &File,
640 unsigned RequestRebuildCounter)
641 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
642 std::unique_lock<std::mutex> Lock(File.Mutex);
643 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
644 if (WasCancelledBeforeConstruction)
645 return;
646
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000647 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
648 return !File.RebuildInProgress ||
649 File.RebuildCounter != RequestRebuildCounter;
650 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000651
652 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
653 if (WasCancelledBeforeConstruction)
654 return;
655
656 File.RebuildInProgress = true;
657}
658
659bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
660 return WasCancelledBeforeConstruction;
661}
662
663CppFile::RebuildGuard::~RebuildGuard() {
664 if (WasCancelledBeforeConstruction)
665 return;
666
667 std::unique_lock<std::mutex> Lock(File.Mutex);
668 assert(File.RebuildInProgress);
669 File.RebuildInProgress = false;
670
671 if (File.RebuildCounter == RequestRebuildCounter) {
672 // Our rebuild request was successful.
673 assert(futureIsReady(File.ASTFuture));
674 assert(futureIsReady(File.PreambleFuture));
675 } else {
676 // Our rebuild request was cancelled, because further reparse was requested.
677 assert(!futureIsReady(File.ASTFuture));
678 assert(!futureIsReady(File.PreambleFuture));
679 }
680
681 Lock.unlock();
682 File.RebuildCond.notify_all();
683}
Haojian Wu345099c2017-11-09 11:30:04 +0000684
685SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
686 const Position &Pos,
687 const FileEntry *FE) {
688 // The language server protocol uses zero-based line and column numbers.
689 // Clang uses one-based numbers.
690
691 const ASTContext &AST = Unit.getASTContext();
692 const SourceManager &SourceMgr = AST.getSourceManager();
693
694 SourceLocation InputLocation =
695 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
696 if (Pos.character == 0) {
697 return InputLocation;
698 }
699
700 // This handle cases where the position is in the middle of a token or right
701 // after the end of a token. In theory we could just use GetBeginningOfToken
702 // to find the start of the token at the input position, but this doesn't
703 // work when right after the end, i.e. foo|.
704 // So try to go back by one and see if we're still inside the an identifier
705 // token. If so, Take the beginning of this token.
706 // (It should be the same identifier because you can't have two adjacent
707 // identifiers without another token in between.)
708 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
709 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
710 Token Result;
711 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
712 AST.getLangOpts(), false)) {
713 // getRawToken failed, just use InputLocation.
714 return InputLocation;
715 }
716
717 if (Result.is(tok::raw_identifier)) {
718 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
719 AST.getLangOpts());
720 }
721
722 return InputLocation;
723}