blob: d0dfe6833a88c92a2068c96b0172d8957a81073a [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 Biryukovdf842342018-01-25 14:32:21 +000037template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
38 return Vec.capacity() * sizeof(T);
39}
40
Ilya Biryukov04db3682017-07-21 13:29:29 +000041class DeclTrackingASTConsumer : public ASTConsumer {
42public:
43 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
44 : TopLevelDecls(TopLevelDecls) {}
45
46 bool HandleTopLevelDecl(DeclGroupRef DG) override {
47 for (const Decl *D : DG) {
48 // ObjCMethodDecl are not actually top-level decls.
49 if (isa<ObjCMethodDecl>(D))
50 continue;
51
52 TopLevelDecls.push_back(D);
53 }
54 return true;
55 }
56
57private:
58 std::vector<const Decl *> &TopLevelDecls;
59};
60
61class ClangdFrontendAction : public SyntaxOnlyAction {
62public:
63 std::vector<const Decl *> takeTopLevelDecls() {
64 return std::move(TopLevelDecls);
65 }
66
67protected:
68 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
69 StringRef InFile) override {
70 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
71 }
72
73private:
74 std::vector<const Decl *> TopLevelDecls;
75};
76
Ilya Biryukov02d58702017-08-01 15:51:38 +000077class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000078public:
79 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
80 return std::move(TopLevelDeclIDs);
81 }
82
83 void AfterPCHEmitted(ASTWriter &Writer) override {
84 TopLevelDeclIDs.reserve(TopLevelDecls.size());
85 for (Decl *D : TopLevelDecls) {
86 // Invalid top-level decls may not have been serialized.
87 if (D->isInvalidDecl())
88 continue;
89 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
90 }
91 }
92
93 void HandleTopLevelDecl(DeclGroupRef DG) override {
94 for (Decl *D : DG) {
95 if (isa<ObjCMethodDecl>(D))
96 continue;
97 TopLevelDecls.push_back(D);
98 }
99 }
100
101private:
102 std::vector<Decl *> TopLevelDecls;
103 std::vector<serialization::DeclID> TopLevelDeclIDs;
104};
105
106/// Convert from clang diagnostic level to LSP severity.
107static int getSeverity(DiagnosticsEngine::Level L) {
108 switch (L) {
109 case DiagnosticsEngine::Remark:
110 return 4;
111 case DiagnosticsEngine::Note:
112 return 3;
113 case DiagnosticsEngine::Warning:
114 return 2;
115 case DiagnosticsEngine::Fatal:
116 case DiagnosticsEngine::Error:
117 return 1;
118 case DiagnosticsEngine::Ignored:
119 return 0;
120 }
121 llvm_unreachable("Unknown diagnostic level!");
122}
123
Sam McCall8111d3b2017-12-13 08:48:42 +0000124// Checks whether a location is within a half-open range.
125// Note that clang also uses closed source ranges, which this can't handle!
126bool locationInRange(SourceLocation L, CharSourceRange R,
127 const SourceManager &M) {
128 assert(R.isCharRange());
129 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
130 M.getFileID(R.getBegin()) != M.getFileID(L))
131 return false;
132 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
133}
134
135// Converts a half-open clang source range to an LSP range.
136// Note that clang also uses closed source ranges, which this can't handle!
137Range toRange(CharSourceRange R, const SourceManager &M) {
138 // Clang is 1-based, LSP uses 0-based indexes.
139 return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
140 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
141 {static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
142 static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
143}
144
145// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
146// LSP needs a single range.
147Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
148 auto &M = D.getSourceManager();
149 auto Loc = M.getFileLoc(D.getLocation());
150 // Accept the first range that contains the location.
151 for (const auto &CR : D.getRanges()) {
152 auto R = Lexer::makeFileCharRange(CR, M, L);
153 if (locationInRange(Loc, R, M))
154 return toRange(R, M);
155 }
156 // The range may be given as a fixit hint instead.
157 for (const auto &F : D.getFixItHints()) {
158 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
159 if (locationInRange(Loc, R, M))
160 return toRange(R, M);
161 }
162 // If no suitable range is found, just use the token at the location.
163 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
164 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
165 R = CharSourceRange::getCharRange(Loc);
166 return toRange(R, M);
167}
168
169TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
170 const LangOptions &L) {
171 TextEdit Result;
172 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
173 Result.newText = FixIt.CodeToInsert;
174 return Result;
175}
176
177llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
178 DiagnosticsEngine::Level Level,
179 const LangOptions &LangOpts) {
180 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000181 !D.getSourceManager().isInMainFile(D.getLocation())) {
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000182 IgnoreDiagnostics::log(Level, D);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183 return llvm::None;
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000184 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000185
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000186 SmallString<64> Message;
187 D.FormatDiagnostic(Message);
188
Sam McCall8111d3b2017-12-13 08:48:42 +0000189 DiagWithFixIts Result;
190 Result.Diag.range = diagnosticRange(D, LangOpts);
191 Result.Diag.severity = getSeverity(Level);
Sam McCall8111d3b2017-12-13 08:48:42 +0000192 Result.Diag.message = Message.str();
193 for (const FixItHint &Fix : D.getFixItHints())
194 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
195 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000196}
197
198class StoreDiagsConsumer : public DiagnosticConsumer {
199public:
200 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
201
Sam McCall8111d3b2017-12-13 08:48:42 +0000202 // Track language options in case we need to expand token ranges.
203 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
204 LangOpts = Opts;
205 }
206
207 void EndSourceFile() override { LangOpts = llvm::None; }
208
Ilya Biryukov04db3682017-07-21 13:29:29 +0000209 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
210 const clang::Diagnostic &Info) override {
211 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
212
Sam McCall8111d3b2017-12-13 08:48:42 +0000213 if (LangOpts)
214 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
215 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000216 }
217
218private:
219 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000220 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000221};
222
Ilya Biryukov04db3682017-07-21 13:29:29 +0000223} // namespace
224
Ilya Biryukov02d58702017-08-01 15:51:38 +0000225void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
226 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000227}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000228
Ilya Biryukov02d58702017-08-01 15:51:38 +0000229llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000230ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000231 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000232 std::unique_ptr<llvm::MemoryBuffer> Buffer,
233 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000234 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000235 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 Biryukovcec63352018-01-29 14:30:28 +0000243 if (!Clang)
244 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000245
246 // Recover resources if we crash before exiting this method.
247 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
248 Clang.get());
249
250 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000251 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
252 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000253 log("BeginSourceFile() failed when building AST for " +
254 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000255 return llvm::None;
256 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000257 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000258 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000259
260 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
261 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000262 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000263
264 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000265 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
266 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000267}
268
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000269namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000270
271SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000272 const FileEntry *FE, Position Pos) {
273 SourceLocation InputLoc =
274 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
275 return Mgr.getMacroArgExpandedLocation(InputLoc);
276}
277
Ilya Biryukov02d58702017-08-01 15:51:38 +0000278} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000279
Ilya Biryukov02d58702017-08-01 15:51:38 +0000280void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000281 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000282 return;
283
284 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000285 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000286
287 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000288 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000289 // Resolve the declaration ID to an actual declaration, possibly
290 // deserializing the declaration in the process.
291 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
292 Resolved.push_back(D);
293 }
294
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000295 TopLevelDecls.reserve(TopLevelDecls.size() +
296 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000297 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
298
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000299 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000300}
301
Ilya Biryukov02d58702017-08-01 15:51:38 +0000302ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000303
Ilya Biryukov02d58702017-08-01 15:51:38 +0000304ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000305
Ilya Biryukov02d58702017-08-01 15:51:38 +0000306ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000307 if (Action) {
308 Action->EndSourceFile();
309 }
310}
311
Ilya Biryukov02d58702017-08-01 15:51:38 +0000312ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
313
314const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000315 return Clang->getASTContext();
316}
317
Ilya Biryukov02d58702017-08-01 15:51:38 +0000318Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000319
Eric Liu76f6b442018-01-09 17:32:00 +0000320std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
321 return Clang->getPreprocessorPtr();
322}
323
Ilya Biryukov02d58702017-08-01 15:51:38 +0000324const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000325 return Clang->getPreprocessor();
326}
327
Ilya Biryukov02d58702017-08-01 15:51:38 +0000328ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000329 ensurePreambleDeclsDeserialized();
330 return TopLevelDecls;
331}
332
Ilya Biryukov02d58702017-08-01 15:51:38 +0000333const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000334 return Diags;
335}
336
Ilya Biryukovdf842342018-01-25 14:32:21 +0000337std::size_t ParsedAST::getUsedBytes() const {
338 auto &AST = getASTContext();
339 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
340 // SmallVector<FixIt> inside each Diag.
341 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
342 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
343}
344
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000345PreambleData::PreambleData(PrecompiledPreamble Preamble,
346 std::vector<serialization::DeclID> TopLevelDeclIDs,
347 std::vector<DiagWithFixIts> Diags)
348 : Preamble(std::move(Preamble)),
349 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
350
351ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
352 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353 std::unique_ptr<FrontendAction> Action,
354 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000356 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
357 Action(std::move(Action)), Diags(std::move(Diags)),
358 TopLevelDecls(std::move(TopLevelDecls)),
359 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000360 assert(this->Clang);
361 assert(this->Action);
362}
363
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000364CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000365 std::shared_ptr<PCHContainerOperations> PCHs,
366 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000367 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000368 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000369 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000370}
371
372llvm::Optional<std::vector<DiagWithFixIts>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000373CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000374 log("Rebuilding file " + FileName + " with command [" +
375 Inputs.CompileCommand.Directory + "] " +
376 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000377
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000378 std::vector<const char *> ArgStrs;
379 for (const auto &S : Inputs.CompileCommand.CommandLine)
380 ArgStrs.push_back(S.c_str());
381
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000382 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
383 log("Couldn't set working directory");
384 // We run parsing anyway, our lit-tests rely on results for non-existing
385 // working dirs.
386 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000387
388 // Prepare CompilerInvocation.
389 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000391 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
392 // reporting them.
393 IgnoreDiagnostics IgnoreDiagnostics;
394 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
395 CompilerInstance::createDiagnostics(new DiagnosticOptions,
396 &IgnoreDiagnostics, false);
397 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
398 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000399 if (!CI) {
400 log("Could not build CompilerInvocation for file " + FileName);
401 AST = llvm::None;
402 Preamble = nullptr;
403 return llvm::None;
404 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000405 // createInvocationFromCommandLine sets DisableFree.
406 CI->getFrontendOpts().DisableFree = false;
407 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000408
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000409 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
410 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000411
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000412 // Compute updated Preamble.
413 std::shared_ptr<const PreambleData> NewPreamble =
414 rebuildPreamble(*CI, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000415
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000416 // Remove current AST to avoid wasting memory.
417 AST = llvm::None;
418 // Compute updated AST.
419 llvm::Optional<ParsedAST> NewAST;
420 {
421 trace::Span Tracer("Build");
422 SPAN_ATTACH(Tracer, "File", FileName);
423 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
424 std::move(ContentsBuffer), PCHs, Inputs.FS);
425 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000426
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000427 std::vector<DiagWithFixIts> Diagnostics;
428 if (NewAST) {
429 // Collect diagnostics from both the preamble and the AST.
430 if (NewPreamble)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000431 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
432 NewPreamble->Diags.end());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000433 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
434 NewAST->getDiagnostics().end());
435 }
436 if (ASTCallback && NewAST)
437 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000438
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000439 // Write the results of rebuild into class fields.
440 Preamble = std::move(NewPreamble);
441 AST = std::move(NewAST);
442 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000443}
444
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000445const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
446 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000447}
448
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000449ParsedAST *CppFile::getAST() const {
450 // We could add mutable to AST instead of const_cast here, but that would also
451 // allow writing to AST from const methods.
452 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000453}
454
Ilya Biryukovdf842342018-01-25 14:32:21 +0000455std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000456 std::size_t Total = 0;
457 if (AST)
458 Total += AST->getUsedBytes();
459 if (StorePreamblesInMemory && Preamble)
460 Total += Preamble->Preamble.getSize();
461 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000462}
463
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000464std::shared_ptr<const PreambleData>
465CppFile::rebuildPreamble(CompilerInvocation &CI,
466 IntrusiveRefCntPtr<vfs::FileSystem> FS,
467 llvm::MemoryBuffer &ContentsBuffer) const {
468 const auto &OldPreamble = this->Preamble;
469 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
470 if (OldPreamble &&
471 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
472 log("Reusing preamble for file " + Twine(FileName));
473 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000474 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000475 log("Preamble for file " + Twine(FileName) +
476 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000477
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000478 trace::Span Tracer("Preamble");
479 SPAN_ATTACH(Tracer, "File", FileName);
480 std::vector<DiagWithFixIts> PreambleDiags;
481 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
482 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
483 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
484 &PreambleDiagnosticsConsumer, false);
485
486 // Skip function bodies when building the preamble to speed up building
487 // the preamble and make it smaller.
488 assert(!CI.getFrontendOpts().SkipFunctionBodies);
489 CI.getFrontendOpts().SkipFunctionBodies = true;
490
491 CppFilePreambleCallbacks SerializedDeclsCollector;
492 auto BuiltPreamble = PrecompiledPreamble::Build(
493 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
494 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
495
496 // When building the AST for the main file, we do want the function
497 // bodies.
498 CI.getFrontendOpts().SkipFunctionBodies = false;
499
500 if (BuiltPreamble) {
501 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
502 " for file " + Twine(FileName));
503
504 return std::make_shared<PreambleData>(
505 std::move(*BuiltPreamble),
506 SerializedDeclsCollector.takeTopLevelDeclIDs(),
507 std::move(PreambleDiags));
508 } else {
509 log("Could not build a preamble for file " + Twine(FileName));
510 return nullptr;
511 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000512}
Haojian Wu345099c2017-11-09 11:30:04 +0000513
514SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
515 const Position &Pos,
516 const FileEntry *FE) {
517 // The language server protocol uses zero-based line and column numbers.
518 // Clang uses one-based numbers.
519
520 const ASTContext &AST = Unit.getASTContext();
521 const SourceManager &SourceMgr = AST.getSourceManager();
522
523 SourceLocation InputLocation =
524 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
525 if (Pos.character == 0) {
526 return InputLocation;
527 }
528
529 // This handle cases where the position is in the middle of a token or right
530 // after the end of a token. In theory we could just use GetBeginningOfToken
531 // to find the start of the token at the input position, but this doesn't
532 // work when right after the end, i.e. foo|.
Benjamin Kramer5eb6a282018-02-06 20:08:23 +0000533 // So try to go back by one and see if we're still inside an identifier
Haojian Wu345099c2017-11-09 11:30:04 +0000534 // token. If so, Take the beginning of this token.
535 // (It should be the same identifier because you can't have two adjacent
536 // identifiers without another token in between.)
537 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
538 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
539 Token Result;
540 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
541 AST.getLangOpts(), false)) {
542 // getRawToken failed, just use InputLocation.
543 return InputLocation;
544 }
545
546 if (Result.is(tok::raw_identifier)) {
547 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
548 AST.getLangOpts());
549 }
550
551 return InputLocation;
552}