blob: c16c218fbae1ae834877f46c3c72a1be74de3ada [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"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000030#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000031#include <algorithm>
32
Ilya Biryukov38d79772017-05-16 09:38:59 +000033using namespace clang::clangd;
34using namespace clang;
35
Ilya Biryukov04db3682017-07-21 13:29:29 +000036namespace {
37
Ilya Biryukovdf842342018-01-25 14:32:21 +000038template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
39 return Vec.capacity() * sizeof(T);
40}
41
Ilya Biryukov04db3682017-07-21 13:29:29 +000042class DeclTrackingASTConsumer : public ASTConsumer {
43public:
44 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
45 : TopLevelDecls(TopLevelDecls) {}
46
47 bool HandleTopLevelDecl(DeclGroupRef DG) override {
48 for (const Decl *D : DG) {
49 // ObjCMethodDecl are not actually top-level decls.
50 if (isa<ObjCMethodDecl>(D))
51 continue;
52
53 TopLevelDecls.push_back(D);
54 }
55 return true;
56 }
57
58private:
59 std::vector<const Decl *> &TopLevelDecls;
60};
61
62class ClangdFrontendAction : public SyntaxOnlyAction {
63public:
64 std::vector<const Decl *> takeTopLevelDecls() {
65 return std::move(TopLevelDecls);
66 }
67
68protected:
69 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
70 StringRef InFile) override {
71 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
72 }
73
74private:
75 std::vector<const Decl *> TopLevelDecls;
76};
77
Ilya Biryukov02d58702017-08-01 15:51:38 +000078class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000079public:
80 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
81 return std::move(TopLevelDeclIDs);
82 }
83
84 void AfterPCHEmitted(ASTWriter &Writer) override {
85 TopLevelDeclIDs.reserve(TopLevelDecls.size());
86 for (Decl *D : TopLevelDecls) {
87 // Invalid top-level decls may not have been serialized.
88 if (D->isInvalidDecl())
89 continue;
90 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
91 }
92 }
93
94 void HandleTopLevelDecl(DeclGroupRef DG) override {
95 for (Decl *D : DG) {
96 if (isa<ObjCMethodDecl>(D))
97 continue;
98 TopLevelDecls.push_back(D);
99 }
100 }
101
102private:
103 std::vector<Decl *> TopLevelDecls;
104 std::vector<serialization::DeclID> TopLevelDeclIDs;
105};
106
107/// Convert from clang diagnostic level to LSP severity.
108static int getSeverity(DiagnosticsEngine::Level L) {
109 switch (L) {
110 case DiagnosticsEngine::Remark:
111 return 4;
112 case DiagnosticsEngine::Note:
113 return 3;
114 case DiagnosticsEngine::Warning:
115 return 2;
116 case DiagnosticsEngine::Fatal:
117 case DiagnosticsEngine::Error:
118 return 1;
119 case DiagnosticsEngine::Ignored:
120 return 0;
121 }
122 llvm_unreachable("Unknown diagnostic level!");
123}
124
Sam McCall8111d3b2017-12-13 08:48:42 +0000125// Checks whether a location is within a half-open range.
126// Note that clang also uses closed source ranges, which this can't handle!
127bool locationInRange(SourceLocation L, CharSourceRange R,
128 const SourceManager &M) {
129 assert(R.isCharRange());
130 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
131 M.getFileID(R.getBegin()) != M.getFileID(L))
132 return false;
133 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
134}
135
136// Converts a half-open clang source range to an LSP range.
137// Note that clang also uses closed source ranges, which this can't handle!
138Range toRange(CharSourceRange R, const SourceManager &M) {
139 // Clang is 1-based, LSP uses 0-based indexes.
140 return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
141 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
142 {static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
143 static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
144}
145
146// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
147// LSP needs a single range.
148Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
149 auto &M = D.getSourceManager();
150 auto Loc = M.getFileLoc(D.getLocation());
151 // Accept the first range that contains the location.
152 for (const auto &CR : D.getRanges()) {
153 auto R = Lexer::makeFileCharRange(CR, M, L);
154 if (locationInRange(Loc, R, M))
155 return toRange(R, M);
156 }
157 // The range may be given as a fixit hint instead.
158 for (const auto &F : D.getFixItHints()) {
159 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
160 if (locationInRange(Loc, R, M))
161 return toRange(R, M);
162 }
163 // If no suitable range is found, just use the token at the location.
164 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
165 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
166 R = CharSourceRange::getCharRange(Loc);
167 return toRange(R, M);
168}
169
170TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
171 const LangOptions &L) {
172 TextEdit Result;
173 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
174 Result.newText = FixIt.CodeToInsert;
175 return Result;
176}
177
178llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
179 DiagnosticsEngine::Level Level,
180 const LangOptions &LangOpts) {
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000181 SmallString<64> Message;
182 D.FormatDiagnostic(Message);
183
Sam McCall8111d3b2017-12-13 08:48:42 +0000184 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000185 !D.getSourceManager().isInMainFile(D.getLocation())) {
186
187 SmallString<64> Location;
188 if (D.hasSourceManager() && D.getLocation().isValid()) {
189 auto &SourceMgr = D.getSourceManager();
190 auto Loc = SourceMgr.getFileLoc(D.getLocation());
191 llvm::raw_svector_ostream OS(Location);
192 Loc.print(OS, SourceMgr);
193 } else {
194 Location = "<no-loc>";
195 }
196
197 log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
198 Location, Message));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000199 return llvm::None;
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000200 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000201
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
395 Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
396
397 // Prepare CompilerInvocation.
398 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000399 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000400 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
401 // reporting them.
402 IgnoreDiagnostics IgnoreDiagnostics;
403 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
404 CompilerInstance::createDiagnostics(new DiagnosticOptions,
405 &IgnoreDiagnostics, false);
406 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
407 Inputs.FS);
408 // createInvocationFromCommandLine sets DisableFree.
409 CI->getFrontendOpts().DisableFree = false;
410 }
411 assert(CI && "Couldn't create CompilerInvocation");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000412
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000413 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
414 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000415
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000416 // Compute updated Preamble.
417 std::shared_ptr<const PreambleData> NewPreamble =
418 rebuildPreamble(*CI, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000419
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000420 // Remove current AST to avoid wasting memory.
421 AST = llvm::None;
422 // Compute updated AST.
423 llvm::Optional<ParsedAST> NewAST;
424 {
425 trace::Span Tracer("Build");
426 SPAN_ATTACH(Tracer, "File", FileName);
427 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
428 std::move(ContentsBuffer), PCHs, Inputs.FS);
429 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000430
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000431 std::vector<DiagWithFixIts> Diagnostics;
432 if (NewAST) {
433 // Collect diagnostics from both the preamble and the AST.
434 if (NewPreamble)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000435 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
436 NewPreamble->Diags.end());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000437 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
438 NewAST->getDiagnostics().end());
439 }
440 if (ASTCallback && NewAST)
441 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000442
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000443 // Write the results of rebuild into class fields.
444 Preamble = std::move(NewPreamble);
445 AST = std::move(NewAST);
446 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000447}
448
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000449const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
450 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000451}
452
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000453ParsedAST *CppFile::getAST() const {
454 // We could add mutable to AST instead of const_cast here, but that would also
455 // allow writing to AST from const methods.
456 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000457}
458
Ilya Biryukovdf842342018-01-25 14:32:21 +0000459std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000460 std::size_t Total = 0;
461 if (AST)
462 Total += AST->getUsedBytes();
463 if (StorePreamblesInMemory && Preamble)
464 Total += Preamble->Preamble.getSize();
465 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000466}
467
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000468std::shared_ptr<const PreambleData>
469CppFile::rebuildPreamble(CompilerInvocation &CI,
470 IntrusiveRefCntPtr<vfs::FileSystem> FS,
471 llvm::MemoryBuffer &ContentsBuffer) const {
472 const auto &OldPreamble = this->Preamble;
473 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
474 if (OldPreamble &&
475 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
476 log("Reusing preamble for file " + Twine(FileName));
477 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000478 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000479 log("Preamble for file " + Twine(FileName) +
480 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000481
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000482 trace::Span Tracer("Preamble");
483 SPAN_ATTACH(Tracer, "File", FileName);
484 std::vector<DiagWithFixIts> PreambleDiags;
485 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
486 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
487 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
488 &PreambleDiagnosticsConsumer, false);
489
490 // Skip function bodies when building the preamble to speed up building
491 // the preamble and make it smaller.
492 assert(!CI.getFrontendOpts().SkipFunctionBodies);
493 CI.getFrontendOpts().SkipFunctionBodies = true;
494
495 CppFilePreambleCallbacks SerializedDeclsCollector;
496 auto BuiltPreamble = PrecompiledPreamble::Build(
497 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
498 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
499
500 // When building the AST for the main file, we do want the function
501 // bodies.
502 CI.getFrontendOpts().SkipFunctionBodies = false;
503
504 if (BuiltPreamble) {
505 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
506 " for file " + Twine(FileName));
507
508 return std::make_shared<PreambleData>(
509 std::move(*BuiltPreamble),
510 SerializedDeclsCollector.takeTopLevelDeclIDs(),
511 std::move(PreambleDiags));
512 } else {
513 log("Could not build a preamble for file " + Twine(FileName));
514 return nullptr;
515 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000516}
Haojian Wu345099c2017-11-09 11:30:04 +0000517
518SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
519 const Position &Pos,
520 const FileEntry *FE) {
521 // The language server protocol uses zero-based line and column numbers.
522 // Clang uses one-based numbers.
523
524 const ASTContext &AST = Unit.getASTContext();
525 const SourceManager &SourceMgr = AST.getSourceManager();
526
527 SourceLocation InputLocation =
528 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
529 if (Pos.character == 0) {
530 return InputLocation;
531 }
532
533 // This handle cases where the position is in the middle of a token or right
534 // after the end of a token. In theory we could just use GetBeginningOfToken
535 // to find the start of the token at the input position, but this doesn't
536 // work when right after the end, i.e. foo|.
Benjamin Kramer5eb6a282018-02-06 20:08:23 +0000537 // So try to go back by one and see if we're still inside an identifier
Haojian Wu345099c2017-11-09 11:30:04 +0000538 // token. If so, Take the beginning of this token.
539 // (It should be the same identifier because you can't have two adjacent
540 // identifiers without another token in between.)
541 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
542 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
543 Token Result;
544 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
545 AST.getLangOpts(), false)) {
546 // getRawToken failed, just use InputLocation.
547 return InputLocation;
548 }
549
550 if (Result.is(tok::raw_identifier)) {
551 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
552 AST.getLangOpts());
553 }
554
555 return InputLocation;
556}