blob: 202f968c21a05f27248339e4969a1f96d75f844a [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
Eric Liu76f6b442018-01-09 17:32:00 +0000319std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
320 return Clang->getPreprocessorPtr();
321}
322
Ilya Biryukov02d58702017-08-01 15:51:38 +0000323const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000324 return Clang->getPreprocessor();
325}
326
Ilya Biryukov02d58702017-08-01 15:51:38 +0000327ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000328 ensurePreambleDeclsDeserialized();
329 return TopLevelDecls;
330}
331
Ilya Biryukov02d58702017-08-01 15:51:38 +0000332const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000333 return Diags;
334}
335
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000336PreambleData::PreambleData(PrecompiledPreamble Preamble,
337 std::vector<serialization::DeclID> TopLevelDeclIDs,
338 std::vector<DiagWithFixIts> Diags)
339 : Preamble(std::move(Preamble)),
340 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
341
342ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
343 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000344 std::unique_ptr<FrontendAction> Action,
345 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000346 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000347 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
348 Action(std::move(Action)), Diags(std::move(Diags)),
349 TopLevelDecls(std::move(TopLevelDecls)),
350 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000351 assert(this->Clang);
352 assert(this->Action);
353}
354
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
356 : AST(std::move(Wrapper.AST)) {}
357
358ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
359 : AST(std::move(AST)) {}
360
Ilya Biryukov02d58702017-08-01 15:51:38 +0000361std::shared_ptr<CppFile>
362CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000363 bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000364 std::shared_ptr<PCHContainerOperations> PCHs,
365 ASTParsedCallback ASTCallback) {
366 return std::shared_ptr<CppFile>(
367 new CppFile(FileName, std::move(Command), StorePreamblesInMemory,
368 std::move(PCHs), std::move(ASTCallback)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000369}
370
371CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000372 bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000373 std::shared_ptr<PCHContainerOperations> PCHs,
374 ASTParsedCallback ASTCallback)
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000375 : FileName(FileName), Command(std::move(Command)),
376 StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
Eric Liubfac8f72017-12-19 18:00:37 +0000377 RebuildInProgress(false), PCHs(std::move(PCHs)),
378 ASTCallback(std::move(ASTCallback)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000379 // FIXME(ibiryukov): we should pass a proper Context here.
380 log(Context::empty(), "Opened file " + FileName + " with command [" +
381 this->Command.Directory + "] " +
382 llvm::join(this->Command.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000383
384 std::lock_guard<std::mutex> Lock(Mutex);
385 LatestAvailablePreamble = nullptr;
386 PreamblePromise.set_value(nullptr);
387 PreambleFuture = PreamblePromise.get_future();
388
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000389 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390 ASTFuture = ASTPromise.get_future();
391}
392
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000393void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000394
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000395UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000396 std::unique_lock<std::mutex> Lock(Mutex);
397 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000398 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000399 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
400 // We want to keep this invariant.
401 if (futureIsReady(PreambleFuture)) {
402 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
403 PreambleFuture = PreamblePromise.get_future();
404 }
405 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000406 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000407 ASTFuture = ASTPromise.get_future();
408 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000409
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000410 Lock.unlock();
411 // Notify about changes to RebuildCounter.
412 RebuildCond.notify_all();
413
414 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000415 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000416 std::unique_lock<std::mutex> Lock(That->Mutex);
417 CppFile *This = &*That;
418 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
419 return !This->RebuildInProgress ||
420 This->RebuildCounter != RequestRebuildCounter;
421 });
422
423 // This computation got cancelled itself, do nothing.
424 if (This->RebuildCounter != RequestRebuildCounter)
425 return;
426
427 // Set empty results for Promises.
428 That->PreamblePromise.set_value(nullptr);
429 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000430 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000431}
432
433llvm::Optional<std::vector<DiagWithFixIts>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000434CppFile::rebuild(const Context &Ctx, StringRef NewContents,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000435 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000436 return deferRebuild(NewContents, std::move(VFS))(Ctx);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000437}
438
Ilya Biryukov940901e2017-12-13 12:51:22 +0000439UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov02d58702017-08-01 15:51:38 +0000440CppFile::deferRebuild(StringRef NewContents,
441 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
442 std::shared_ptr<const PreambleData> OldPreamble;
443 std::shared_ptr<PCHContainerOperations> PCHs;
444 unsigned RequestRebuildCounter;
445 {
446 std::unique_lock<std::mutex> Lock(Mutex);
447 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
448 // They will try to exit as early as possible and won't call set_value on
449 // our promises.
450 RequestRebuildCounter = ++this->RebuildCounter;
451 PCHs = this->PCHs;
452
453 // Remember the preamble to be used during rebuild.
454 OldPreamble = this->LatestAvailablePreamble;
455 // Setup std::promises and std::futures for Preamble and AST. Corresponding
456 // futures will wait until the rebuild process is finished.
457 if (futureIsReady(this->PreambleFuture)) {
458 this->PreamblePromise =
459 std::promise<std::shared_ptr<const PreambleData>>();
460 this->PreambleFuture = this->PreamblePromise.get_future();
461 }
462 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000463 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000464 this->ASTFuture = this->ASTPromise.get_future();
465 }
466 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000467 // Notify about changes to RebuildCounter.
468 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000469
470 // A helper to function to finish the rebuild. May be run on a different
471 // thread.
472
473 // Don't let this CppFile die before rebuild is finished.
474 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000475 auto FinishRebuild =
476 [OldPreamble, VFS, RequestRebuildCounter, PCHs,
477 That](std::string NewContents,
478 const Context &Ctx) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000479 -> llvm::Optional<std::vector<DiagWithFixIts>> {
480 // Only one execution of this method is possible at a time.
481 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
482 // into a state for doing a rebuild.
483 RebuildGuard Rebuild(*That, RequestRebuildCounter);
484 if (Rebuild.wasCancelledBeforeConstruction())
485 return llvm::None;
486
487 std::vector<const char *> ArgStrs;
488 for (const auto &S : That->Command.CommandLine)
489 ArgStrs.push_back(S.c_str());
490
491 VFS->setCurrentWorkingDirectory(That->Command.Directory);
492
493 std::unique_ptr<CompilerInvocation> CI;
494 {
495 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
496 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000497 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000498 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
499 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000500 &IgnoreDiagnostics, false);
501 CI =
502 createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine, VFS);
503 // createInvocationFromCommandLine sets DisableFree.
504 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000505 }
506 assert(CI && "Couldn't create CompilerInvocation");
507
508 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
509 llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName);
510
511 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000512 // not mutate any fields of CppFile, only does the actual computation.
513 // Lamdba is marked mutable to call reset() on OldPreamble.
514 auto DoRebuildPreamble =
515 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000516 auto Bounds =
517 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
518 if (OldPreamble && OldPreamble->Preamble.CanReuse(
519 *CI, ContentsBuffer.get(), Bounds, VFS.get())) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000520 log(Ctx, "Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000521 return OldPreamble;
522 }
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000523 log(Ctx, "Premble for file " + Twine(That->FileName) +
524 " cannot be reused. Attempting to rebuild it.");
525 // We won't need the OldPreamble anymore, release it so it can be
526 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000527 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000528
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000529 trace::Span Tracer(Ctx, "Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000530 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000531 std::vector<DiagWithFixIts> PreambleDiags;
532 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
533 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
534 CompilerInstance::createDiagnostics(
535 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000536
537 // Skip function bodies when building the preamble to speed up building
538 // the preamble and make it smaller.
539 assert(!CI->getFrontendOpts().SkipFunctionBodies);
540 CI->getFrontendOpts().SkipFunctionBodies = true;
541
Ilya Biryukov02d58702017-08-01 15:51:38 +0000542 CppFilePreambleCallbacks SerializedDeclsCollector;
543 auto BuiltPreamble = PrecompiledPreamble::Build(
544 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, 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),
593 std::move(ContentsBuffer), PCHs, VFS);
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 Biryukov98a1fd72017-10-10 16:12:54 +0000620 return BindWithForward(FinishRebuild, NewContents.str());
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
639tooling::CompileCommand const &CppFile::getCompileCommand() const {
640 return Command;
641}
642
643CppFile::RebuildGuard::RebuildGuard(CppFile &File,
644 unsigned RequestRebuildCounter)
645 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
646 std::unique_lock<std::mutex> Lock(File.Mutex);
647 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
648 if (WasCancelledBeforeConstruction)
649 return;
650
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000651 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
652 return !File.RebuildInProgress ||
653 File.RebuildCounter != RequestRebuildCounter;
654 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000655
656 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
657 if (WasCancelledBeforeConstruction)
658 return;
659
660 File.RebuildInProgress = true;
661}
662
663bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
664 return WasCancelledBeforeConstruction;
665}
666
667CppFile::RebuildGuard::~RebuildGuard() {
668 if (WasCancelledBeforeConstruction)
669 return;
670
671 std::unique_lock<std::mutex> Lock(File.Mutex);
672 assert(File.RebuildInProgress);
673 File.RebuildInProgress = false;
674
675 if (File.RebuildCounter == RequestRebuildCounter) {
676 // Our rebuild request was successful.
677 assert(futureIsReady(File.ASTFuture));
678 assert(futureIsReady(File.PreambleFuture));
679 } else {
680 // Our rebuild request was cancelled, because further reparse was requested.
681 assert(!futureIsReady(File.ASTFuture));
682 assert(!futureIsReady(File.PreambleFuture));
683 }
684
685 Lock.unlock();
686 File.RebuildCond.notify_all();
687}
Haojian Wu345099c2017-11-09 11:30:04 +0000688
689SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
690 const Position &Pos,
691 const FileEntry *FE) {
692 // The language server protocol uses zero-based line and column numbers.
693 // Clang uses one-based numbers.
694
695 const ASTContext &AST = Unit.getASTContext();
696 const SourceManager &SourceMgr = AST.getSourceManager();
697
698 SourceLocation InputLocation =
699 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
700 if (Pos.character == 0) {
701 return InputLocation;
702 }
703
704 // This handle cases where the position is in the middle of a token or right
705 // after the end of a token. In theory we could just use GetBeginningOfToken
706 // to find the start of the token at the input position, but this doesn't
707 // work when right after the end, i.e. foo|.
708 // So try to go back by one and see if we're still inside the an identifier
709 // token. If so, Take the beginning of this token.
710 // (It should be the same identifier because you can't have two adjacent
711 // identifiers without another token in between.)
712 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
713 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
714 Token Result;
715 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
716 AST.getLangOpts(), false)) {
717 // getRawToken failed, just use InputLocation.
718 return InputLocation;
719 }
720
721 if (Result.is(tok::raw_identifier)) {
722 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
723 AST.getLangOpts());
724 }
725
726 return InputLocation;
727}