blob: df2a4e8c91268c4937fb36f96f310b1d3ee7d32f [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"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000029#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
31
Ilya Biryukov38d79772017-05-16 09:38:59 +000032using namespace clang::clangd;
33using namespace clang;
34
Ilya Biryukov04db3682017-07-21 13:29:29 +000035namespace {
36
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000037bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
38 const tooling::CompileCommand &RHS) {
39 // We don't check for Output, it should not matter to clangd.
40 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
41 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
42}
43
Ilya Biryukovdf842342018-01-25 14:32:21 +000044template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
45 return Vec.capacity() * sizeof(T);
46}
47
Ilya Biryukov04db3682017-07-21 13:29:29 +000048class DeclTrackingASTConsumer : public ASTConsumer {
49public:
50 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
51 : TopLevelDecls(TopLevelDecls) {}
52
53 bool HandleTopLevelDecl(DeclGroupRef DG) override {
54 for (const Decl *D : DG) {
55 // ObjCMethodDecl are not actually top-level decls.
56 if (isa<ObjCMethodDecl>(D))
57 continue;
58
59 TopLevelDecls.push_back(D);
60 }
61 return true;
62 }
63
64private:
65 std::vector<const Decl *> &TopLevelDecls;
66};
67
68class ClangdFrontendAction : public SyntaxOnlyAction {
69public:
70 std::vector<const Decl *> takeTopLevelDecls() {
71 return std::move(TopLevelDecls);
72 }
73
74protected:
75 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
76 StringRef InFile) override {
77 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
78 }
79
80private:
81 std::vector<const Decl *> TopLevelDecls;
82};
83
Ilya Biryukov02d58702017-08-01 15:51:38 +000084class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000085public:
86 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
87 return std::move(TopLevelDeclIDs);
88 }
89
90 void AfterPCHEmitted(ASTWriter &Writer) override {
91 TopLevelDeclIDs.reserve(TopLevelDecls.size());
92 for (Decl *D : TopLevelDecls) {
93 // Invalid top-level decls may not have been serialized.
94 if (D->isInvalidDecl())
95 continue;
96 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
97 }
98 }
99
100 void HandleTopLevelDecl(DeclGroupRef DG) override {
101 for (Decl *D : DG) {
102 if (isa<ObjCMethodDecl>(D))
103 continue;
104 TopLevelDecls.push_back(D);
105 }
106 }
107
108private:
109 std::vector<Decl *> TopLevelDecls;
110 std::vector<serialization::DeclID> TopLevelDeclIDs;
111};
112
113/// Convert from clang diagnostic level to LSP severity.
114static int getSeverity(DiagnosticsEngine::Level L) {
115 switch (L) {
116 case DiagnosticsEngine::Remark:
117 return 4;
118 case DiagnosticsEngine::Note:
119 return 3;
120 case DiagnosticsEngine::Warning:
121 return 2;
122 case DiagnosticsEngine::Fatal:
123 case DiagnosticsEngine::Error:
124 return 1;
125 case DiagnosticsEngine::Ignored:
126 return 0;
127 }
128 llvm_unreachable("Unknown diagnostic level!");
129}
130
Sam McCall8111d3b2017-12-13 08:48:42 +0000131// Checks whether a location is within a half-open range.
132// Note that clang also uses closed source ranges, which this can't handle!
133bool locationInRange(SourceLocation L, CharSourceRange R,
134 const SourceManager &M) {
135 assert(R.isCharRange());
136 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
137 M.getFileID(R.getBegin()) != M.getFileID(L))
138 return false;
139 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
140}
141
142// Converts a half-open clang source range to an LSP range.
143// Note that clang also uses closed source ranges, which this can't handle!
144Range toRange(CharSourceRange R, const SourceManager &M) {
145 // Clang is 1-based, LSP uses 0-based indexes.
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000146 Position Begin;
147 Begin.line = static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1;
148 Begin.character =
149 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1;
150
151 Position End;
152 End.line = static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1;
153 End.character = static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1;
154
155 return {Begin, End};
Sam McCall8111d3b2017-12-13 08:48:42 +0000156}
157
158// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
159// LSP needs a single range.
160Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
161 auto &M = D.getSourceManager();
162 auto Loc = M.getFileLoc(D.getLocation());
163 // Accept the first range that contains the location.
164 for (const auto &CR : D.getRanges()) {
165 auto R = Lexer::makeFileCharRange(CR, M, L);
166 if (locationInRange(Loc, R, M))
167 return toRange(R, M);
168 }
169 // The range may be given as a fixit hint instead.
170 for (const auto &F : D.getFixItHints()) {
171 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
172 if (locationInRange(Loc, R, M))
173 return toRange(R, M);
174 }
175 // If no suitable range is found, just use the token at the location.
176 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
177 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
178 R = CharSourceRange::getCharRange(Loc);
179 return toRange(R, M);
180}
181
182TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
183 const LangOptions &L) {
184 TextEdit Result;
185 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
186 Result.newText = FixIt.CodeToInsert;
187 return Result;
188}
189
190llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
191 DiagnosticsEngine::Level Level,
192 const LangOptions &LangOpts) {
193 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000194 !D.getSourceManager().isInMainFile(D.getLocation())) {
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000195 IgnoreDiagnostics::log(Level, D);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000196 return llvm::None;
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000197 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000198
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000199 SmallString<64> Message;
200 D.FormatDiagnostic(Message);
201
Sam McCall8111d3b2017-12-13 08:48:42 +0000202 DiagWithFixIts Result;
203 Result.Diag.range = diagnosticRange(D, LangOpts);
204 Result.Diag.severity = getSeverity(Level);
Sam McCall8111d3b2017-12-13 08:48:42 +0000205 Result.Diag.message = Message.str();
206 for (const FixItHint &Fix : D.getFixItHints())
207 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
208 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000209}
210
211class StoreDiagsConsumer : public DiagnosticConsumer {
212public:
213 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
214
Sam McCall8111d3b2017-12-13 08:48:42 +0000215 // Track language options in case we need to expand token ranges.
216 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
217 LangOpts = Opts;
218 }
219
220 void EndSourceFile() override { LangOpts = llvm::None; }
221
Ilya Biryukov04db3682017-07-21 13:29:29 +0000222 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
223 const clang::Diagnostic &Info) override {
224 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
225
Sam McCall8111d3b2017-12-13 08:48:42 +0000226 if (LangOpts)
227 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
228 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000229 }
230
231private:
232 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000233 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000234};
235
Ilya Biryukov04db3682017-07-21 13:29:29 +0000236} // namespace
237
Ilya Biryukov02d58702017-08-01 15:51:38 +0000238void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
239 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000241
Ilya Biryukov02d58702017-08-01 15:51:38 +0000242llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000243ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000244 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000245 std::unique_ptr<llvm::MemoryBuffer> Buffer,
246 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000247 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000248 std::vector<DiagWithFixIts> ASTDiags;
249 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
250
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000251 const PrecompiledPreamble *PreamblePCH =
252 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000253 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000254 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000255 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000256 if (!Clang)
257 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000258
259 // Recover resources if we crash before exiting this method.
260 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
261 Clang.get());
262
263 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000264 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
265 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000266 log("BeginSourceFile() failed when building AST for " +
267 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268 return llvm::None;
269 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000270 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000271 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000272
273 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
274 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000275 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000276
277 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000278 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
279 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000280}
281
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000282namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000283
284SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000285 const FileEntry *FE, Position Pos) {
286 SourceLocation InputLoc =
287 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
288 return Mgr.getMacroArgExpandedLocation(InputLoc);
289}
290
Ilya Biryukov02d58702017-08-01 15:51:38 +0000291} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000292
Ilya Biryukov02d58702017-08-01 15:51:38 +0000293void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000294 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000295 return;
296
297 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000298 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000299
300 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000301 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000302 // Resolve the declaration ID to an actual declaration, possibly
303 // deserializing the declaration in the process.
304 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
305 Resolved.push_back(D);
306 }
307
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000308 TopLevelDecls.reserve(TopLevelDecls.size() +
309 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000310 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
311
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000312 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000313}
314
Ilya Biryukov02d58702017-08-01 15:51:38 +0000315ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000316
Ilya Biryukov02d58702017-08-01 15:51:38 +0000317ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000318
Ilya Biryukov02d58702017-08-01 15:51:38 +0000319ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000320 if (Action) {
321 Action->EndSourceFile();
322 }
323}
324
Ilya Biryukov02d58702017-08-01 15:51:38 +0000325ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
326
327const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000328 return Clang->getASTContext();
329}
330
Ilya Biryukov02d58702017-08-01 15:51:38 +0000331Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000332
Eric Liu76f6b442018-01-09 17:32:00 +0000333std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
334 return Clang->getPreprocessorPtr();
335}
336
Ilya Biryukov02d58702017-08-01 15:51:38 +0000337const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000338 return Clang->getPreprocessor();
339}
340
Ilya Biryukov02d58702017-08-01 15:51:38 +0000341ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000342 ensurePreambleDeclsDeserialized();
343 return TopLevelDecls;
344}
345
Ilya Biryukov02d58702017-08-01 15:51:38 +0000346const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000347 return Diags;
348}
349
Ilya Biryukovdf842342018-01-25 14:32:21 +0000350std::size_t ParsedAST::getUsedBytes() const {
351 auto &AST = getASTContext();
352 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
353 // SmallVector<FixIt> inside each Diag.
354 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
355 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
356}
357
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000358PreambleData::PreambleData(PrecompiledPreamble Preamble,
359 std::vector<serialization::DeclID> TopLevelDeclIDs,
360 std::vector<DiagWithFixIts> Diags)
361 : Preamble(std::move(Preamble)),
362 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
363
364ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
365 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000366 std::unique_ptr<FrontendAction> Action,
367 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000368 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000369 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
370 Action(std::move(Action)), Diags(std::move(Diags)),
371 TopLevelDecls(std::move(TopLevelDecls)),
372 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000373 assert(this->Clang);
374 assert(this->Action);
375}
376
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000377CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000378 std::shared_ptr<PCHContainerOperations> PCHs,
379 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000380 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000381 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000382 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000383}
384
385llvm::Optional<std::vector<DiagWithFixIts>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000386CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000387 log("Rebuilding file " + FileName + " with command [" +
388 Inputs.CompileCommand.Directory + "] " +
389 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000391 std::vector<const char *> ArgStrs;
392 for (const auto &S : Inputs.CompileCommand.CommandLine)
393 ArgStrs.push_back(S.c_str());
394
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000395 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
396 log("Couldn't set working directory");
397 // We run parsing anyway, our lit-tests rely on results for non-existing
398 // working dirs.
399 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000400
401 // Prepare CompilerInvocation.
402 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000404 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
405 // reporting them.
406 IgnoreDiagnostics IgnoreDiagnostics;
407 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
408 CompilerInstance::createDiagnostics(new DiagnosticOptions,
409 &IgnoreDiagnostics, false);
410 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
411 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000412 if (!CI) {
413 log("Could not build CompilerInvocation for file " + FileName);
414 AST = llvm::None;
415 Preamble = nullptr;
416 return llvm::None;
417 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000418 // createInvocationFromCommandLine sets DisableFree.
419 CI->getFrontendOpts().DisableFree = false;
420 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000421
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000422 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
423 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000424
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000425 // Compute updated Preamble.
426 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000427 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000428
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000429 // Remove current AST to avoid wasting memory.
430 AST = llvm::None;
431 // Compute updated AST.
432 llvm::Optional<ParsedAST> NewAST;
433 {
434 trace::Span Tracer("Build");
435 SPAN_ATTACH(Tracer, "File", FileName);
436 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
437 std::move(ContentsBuffer), PCHs, Inputs.FS);
438 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000439
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000440 std::vector<DiagWithFixIts> Diagnostics;
441 if (NewAST) {
442 // Collect diagnostics from both the preamble and the AST.
443 if (NewPreamble)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000444 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
445 NewPreamble->Diags.end());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000446 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
447 NewAST->getDiagnostics().end());
448 }
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000449 if (ASTCallback && NewAST) {
450 trace::Span Tracer("Running ASTCallback");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000451 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000452 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000453
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000454 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000455 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000456 Preamble = std::move(NewPreamble);
457 AST = std::move(NewAST);
458 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000459}
460
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000461const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
462 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000463}
464
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000465ParsedAST *CppFile::getAST() const {
466 // We could add mutable to AST instead of const_cast here, but that would also
467 // allow writing to AST from const methods.
468 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000469}
470
Ilya Biryukovdf842342018-01-25 14:32:21 +0000471std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000472 std::size_t Total = 0;
473 if (AST)
474 Total += AST->getUsedBytes();
475 if (StorePreamblesInMemory && Preamble)
476 Total += Preamble->Preamble.getSize();
477 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000478}
479
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000480std::shared_ptr<const PreambleData>
481CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000482 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000483 IntrusiveRefCntPtr<vfs::FileSystem> FS,
484 llvm::MemoryBuffer &ContentsBuffer) const {
485 const auto &OldPreamble = this->Preamble;
486 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000487 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000488 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
489 log("Reusing preamble for file " + Twine(FileName));
490 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000491 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000492 log("Preamble for file " + Twine(FileName) +
493 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000494
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000495 trace::Span Tracer("Preamble");
496 SPAN_ATTACH(Tracer, "File", FileName);
497 std::vector<DiagWithFixIts> PreambleDiags;
498 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
499 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
500 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
501 &PreambleDiagnosticsConsumer, false);
502
503 // Skip function bodies when building the preamble to speed up building
504 // the preamble and make it smaller.
505 assert(!CI.getFrontendOpts().SkipFunctionBodies);
506 CI.getFrontendOpts().SkipFunctionBodies = true;
507
508 CppFilePreambleCallbacks SerializedDeclsCollector;
509 auto BuiltPreamble = PrecompiledPreamble::Build(
510 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
511 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
512
513 // When building the AST for the main file, we do want the function
514 // bodies.
515 CI.getFrontendOpts().SkipFunctionBodies = false;
516
517 if (BuiltPreamble) {
518 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
519 " for file " + Twine(FileName));
520
521 return std::make_shared<PreambleData>(
522 std::move(*BuiltPreamble),
523 SerializedDeclsCollector.takeTopLevelDeclIDs(),
524 std::move(PreambleDiags));
525 } else {
526 log("Could not build a preamble for file " + Twine(FileName));
527 return nullptr;
528 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000529}
Haojian Wu345099c2017-11-09 11:30:04 +0000530
531SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
532 const Position &Pos,
533 const FileEntry *FE) {
534 // The language server protocol uses zero-based line and column numbers.
535 // Clang uses one-based numbers.
536
537 const ASTContext &AST = Unit.getASTContext();
538 const SourceManager &SourceMgr = AST.getSourceManager();
539
540 SourceLocation InputLocation =
541 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
542 if (Pos.character == 0) {
543 return InputLocation;
544 }
545
546 // This handle cases where the position is in the middle of a token or right
547 // after the end of a token. In theory we could just use GetBeginningOfToken
548 // to find the start of the token at the input position, but this doesn't
549 // work when right after the end, i.e. foo|.
Benjamin Kramer5eb6a282018-02-06 20:08:23 +0000550 // So try to go back by one and see if we're still inside an identifier
Haojian Wu345099c2017-11-09 11:30:04 +0000551 // token. If so, Take the beginning of this token.
552 // (It should be the same identifier because you can't have two adjacent
553 // identifiers without another token in between.)
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000554 Position PosCharBehind = Pos;
555 --PosCharBehind.character;
556
557 SourceLocation PeekBeforeLocation =
558 getMacroArgExpandedLocation(SourceMgr, FE, PosCharBehind);
Haojian Wu345099c2017-11-09 11:30:04 +0000559 Token Result;
560 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
561 AST.getLangOpts(), false)) {
562 // getRawToken failed, just use InputLocation.
563 return InputLocation;
564 }
565
566 if (Result.is(tok::raw_identifier)) {
567 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
568 AST.getLangOpts());
569 }
570
571 return InputLocation;
572}