blob: d1fa96bf7705161d5cdd93c168133ff45ad90e67 [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.
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000139 Position Begin;
140 Begin.line = static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1;
141 Begin.character =
142 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1;
143
144 Position End;
145 End.line = static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1;
146 End.character = static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1;
147
148 return {Begin, End};
Sam McCall8111d3b2017-12-13 08:48:42 +0000149}
150
151// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
152// LSP needs a single range.
153Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
154 auto &M = D.getSourceManager();
155 auto Loc = M.getFileLoc(D.getLocation());
156 // Accept the first range that contains the location.
157 for (const auto &CR : D.getRanges()) {
158 auto R = Lexer::makeFileCharRange(CR, M, L);
159 if (locationInRange(Loc, R, M))
160 return toRange(R, M);
161 }
162 // The range may be given as a fixit hint instead.
163 for (const auto &F : D.getFixItHints()) {
164 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
165 if (locationInRange(Loc, R, M))
166 return toRange(R, M);
167 }
168 // If no suitable range is found, just use the token at the location.
169 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
170 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
171 R = CharSourceRange::getCharRange(Loc);
172 return toRange(R, M);
173}
174
175TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
176 const LangOptions &L) {
177 TextEdit Result;
178 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
179 Result.newText = FixIt.CodeToInsert;
180 return Result;
181}
182
183llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
184 DiagnosticsEngine::Level Level,
185 const LangOptions &LangOpts) {
186 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000187 !D.getSourceManager().isInMainFile(D.getLocation())) {
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000188 IgnoreDiagnostics::log(Level, D);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000189 return llvm::None;
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000190 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000191
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000192 SmallString<64> Message;
193 D.FormatDiagnostic(Message);
194
Sam McCall8111d3b2017-12-13 08:48:42 +0000195 DiagWithFixIts Result;
196 Result.Diag.range = diagnosticRange(D, LangOpts);
197 Result.Diag.severity = getSeverity(Level);
Sam McCall8111d3b2017-12-13 08:48:42 +0000198 Result.Diag.message = Message.str();
199 for (const FixItHint &Fix : D.getFixItHints())
200 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
201 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000202}
203
204class StoreDiagsConsumer : public DiagnosticConsumer {
205public:
206 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
207
Sam McCall8111d3b2017-12-13 08:48:42 +0000208 // Track language options in case we need to expand token ranges.
209 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
210 LangOpts = Opts;
211 }
212
213 void EndSourceFile() override { LangOpts = llvm::None; }
214
Ilya Biryukov04db3682017-07-21 13:29:29 +0000215 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
216 const clang::Diagnostic &Info) override {
217 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
218
Sam McCall8111d3b2017-12-13 08:48:42 +0000219 if (LangOpts)
220 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
221 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000222 }
223
224private:
225 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000226 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000227};
228
Ilya Biryukov04db3682017-07-21 13:29:29 +0000229} // namespace
230
Ilya Biryukov02d58702017-08-01 15:51:38 +0000231void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
232 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000233}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000234
Ilya Biryukov02d58702017-08-01 15:51:38 +0000235llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000236ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000237 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000238 std::unique_ptr<llvm::MemoryBuffer> Buffer,
239 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000240 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000241 std::vector<DiagWithFixIts> ASTDiags;
242 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
243
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000244 const PrecompiledPreamble *PreamblePCH =
245 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000246 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000247 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000248 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000249 if (!Clang)
250 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000251
252 // Recover resources if we crash before exiting this method.
253 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
254 Clang.get());
255
256 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000257 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
258 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000259 log("BeginSourceFile() failed when building AST for " +
260 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000261 return llvm::None;
262 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000263 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000264 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000265
266 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
267 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000268 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000269
270 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000271 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
272 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000273}
274
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000275namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000276
277SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000278 const FileEntry *FE, Position Pos) {
279 SourceLocation InputLoc =
280 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
281 return Mgr.getMacroArgExpandedLocation(InputLoc);
282}
283
Ilya Biryukov02d58702017-08-01 15:51:38 +0000284} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000285
Ilya Biryukov02d58702017-08-01 15:51:38 +0000286void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000287 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000288 return;
289
290 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000291 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000292
293 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000294 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000295 // Resolve the declaration ID to an actual declaration, possibly
296 // deserializing the declaration in the process.
297 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
298 Resolved.push_back(D);
299 }
300
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000301 TopLevelDecls.reserve(TopLevelDecls.size() +
302 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000303 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
304
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000305 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000306}
307
Ilya Biryukov02d58702017-08-01 15:51:38 +0000308ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000309
Ilya Biryukov02d58702017-08-01 15:51:38 +0000310ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000311
Ilya Biryukov02d58702017-08-01 15:51:38 +0000312ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000313 if (Action) {
314 Action->EndSourceFile();
315 }
316}
317
Ilya Biryukov02d58702017-08-01 15:51:38 +0000318ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
319
320const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000321 return Clang->getASTContext();
322}
323
Ilya Biryukov02d58702017-08-01 15:51:38 +0000324Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000325
Eric Liu76f6b442018-01-09 17:32:00 +0000326std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
327 return Clang->getPreprocessorPtr();
328}
329
Ilya Biryukov02d58702017-08-01 15:51:38 +0000330const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000331 return Clang->getPreprocessor();
332}
333
Ilya Biryukov02d58702017-08-01 15:51:38 +0000334ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000335 ensurePreambleDeclsDeserialized();
336 return TopLevelDecls;
337}
338
Ilya Biryukov02d58702017-08-01 15:51:38 +0000339const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000340 return Diags;
341}
342
Ilya Biryukovdf842342018-01-25 14:32:21 +0000343std::size_t ParsedAST::getUsedBytes() const {
344 auto &AST = getASTContext();
345 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
346 // SmallVector<FixIt> inside each Diag.
347 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
348 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
349}
350
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000351PreambleData::PreambleData(PrecompiledPreamble Preamble,
352 std::vector<serialization::DeclID> TopLevelDeclIDs,
353 std::vector<DiagWithFixIts> Diags)
354 : Preamble(std::move(Preamble)),
355 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
356
357ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
358 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000359 std::unique_ptr<FrontendAction> Action,
360 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000361 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000362 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
363 Action(std::move(Action)), Diags(std::move(Diags)),
364 TopLevelDecls(std::move(TopLevelDecls)),
365 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000366 assert(this->Clang);
367 assert(this->Action);
368}
369
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000370CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000371 std::shared_ptr<PCHContainerOperations> PCHs,
372 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000373 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000374 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000375 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000376}
377
378llvm::Optional<std::vector<DiagWithFixIts>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000379CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000380 log("Rebuilding file " + FileName + " with command [" +
381 Inputs.CompileCommand.Directory + "] " +
382 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000383
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000384 std::vector<const char *> ArgStrs;
385 for (const auto &S : Inputs.CompileCommand.CommandLine)
386 ArgStrs.push_back(S.c_str());
387
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000388 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
389 log("Couldn't set working directory");
390 // We run parsing anyway, our lit-tests rely on results for non-existing
391 // working dirs.
392 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000393
394 // Prepare CompilerInvocation.
395 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000396 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000397 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
398 // reporting them.
399 IgnoreDiagnostics IgnoreDiagnostics;
400 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
401 CompilerInstance::createDiagnostics(new DiagnosticOptions,
402 &IgnoreDiagnostics, false);
403 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
404 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000405 if (!CI) {
406 log("Could not build CompilerInvocation for file " + FileName);
407 AST = llvm::None;
408 Preamble = nullptr;
409 return llvm::None;
410 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000411 // createInvocationFromCommandLine sets DisableFree.
412 CI->getFrontendOpts().DisableFree = false;
413 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000414
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000415 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
416 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000417
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000418 // Compute updated Preamble.
419 std::shared_ptr<const PreambleData> NewPreamble =
420 rebuildPreamble(*CI, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000421
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000422 // Remove current AST to avoid wasting memory.
423 AST = llvm::None;
424 // Compute updated AST.
425 llvm::Optional<ParsedAST> NewAST;
426 {
427 trace::Span Tracer("Build");
428 SPAN_ATTACH(Tracer, "File", FileName);
429 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
430 std::move(ContentsBuffer), PCHs, Inputs.FS);
431 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000432
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000433 std::vector<DiagWithFixIts> Diagnostics;
434 if (NewAST) {
435 // Collect diagnostics from both the preamble and the AST.
436 if (NewPreamble)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000437 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
438 NewPreamble->Diags.end());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000439 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
440 NewAST->getDiagnostics().end());
441 }
442 if (ASTCallback && NewAST)
443 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000444
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000445 // Write the results of rebuild into class fields.
446 Preamble = std::move(NewPreamble);
447 AST = std::move(NewAST);
448 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000449}
450
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000451const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
452 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000453}
454
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000455ParsedAST *CppFile::getAST() const {
456 // We could add mutable to AST instead of const_cast here, but that would also
457 // allow writing to AST from const methods.
458 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000459}
460
Ilya Biryukovdf842342018-01-25 14:32:21 +0000461std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000462 std::size_t Total = 0;
463 if (AST)
464 Total += AST->getUsedBytes();
465 if (StorePreamblesInMemory && Preamble)
466 Total += Preamble->Preamble.getSize();
467 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000468}
469
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000470std::shared_ptr<const PreambleData>
471CppFile::rebuildPreamble(CompilerInvocation &CI,
472 IntrusiveRefCntPtr<vfs::FileSystem> FS,
473 llvm::MemoryBuffer &ContentsBuffer) const {
474 const auto &OldPreamble = this->Preamble;
475 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
476 if (OldPreamble &&
477 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
478 log("Reusing preamble for file " + Twine(FileName));
479 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000480 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000481 log("Preamble for file " + Twine(FileName) +
482 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000483
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000484 trace::Span Tracer("Preamble");
485 SPAN_ATTACH(Tracer, "File", FileName);
486 std::vector<DiagWithFixIts> PreambleDiags;
487 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
488 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
489 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
490 &PreambleDiagnosticsConsumer, false);
491
492 // Skip function bodies when building the preamble to speed up building
493 // the preamble and make it smaller.
494 assert(!CI.getFrontendOpts().SkipFunctionBodies);
495 CI.getFrontendOpts().SkipFunctionBodies = true;
496
497 CppFilePreambleCallbacks SerializedDeclsCollector;
498 auto BuiltPreamble = PrecompiledPreamble::Build(
499 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
500 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
501
502 // When building the AST for the main file, we do want the function
503 // bodies.
504 CI.getFrontendOpts().SkipFunctionBodies = false;
505
506 if (BuiltPreamble) {
507 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
508 " for file " + Twine(FileName));
509
510 return std::make_shared<PreambleData>(
511 std::move(*BuiltPreamble),
512 SerializedDeclsCollector.takeTopLevelDeclIDs(),
513 std::move(PreambleDiags));
514 } else {
515 log("Could not build a preamble for file " + Twine(FileName));
516 return nullptr;
517 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000518}
Haojian Wu345099c2017-11-09 11:30:04 +0000519
520SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
521 const Position &Pos,
522 const FileEntry *FE) {
523 // The language server protocol uses zero-based line and column numbers.
524 // Clang uses one-based numbers.
525
526 const ASTContext &AST = Unit.getASTContext();
527 const SourceManager &SourceMgr = AST.getSourceManager();
528
529 SourceLocation InputLocation =
530 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
531 if (Pos.character == 0) {
532 return InputLocation;
533 }
534
535 // This handle cases where the position is in the middle of a token or right
536 // after the end of a token. In theory we could just use GetBeginningOfToken
537 // to find the start of the token at the input position, but this doesn't
538 // work when right after the end, i.e. foo|.
Benjamin Kramer5eb6a282018-02-06 20:08:23 +0000539 // So try to go back by one and see if we're still inside an identifier
Haojian Wu345099c2017-11-09 11:30:04 +0000540 // token. If so, Take the beginning of this token.
541 // (It should be the same identifier because you can't have two adjacent
542 // identifiers without another token in between.)
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000543 Position PosCharBehind = Pos;
544 --PosCharBehind.character;
545
546 SourceLocation PeekBeforeLocation =
547 getMacroArgExpandedLocation(SourceMgr, FE, PosCharBehind);
Haojian Wu345099c2017-11-09 11:30:04 +0000548 Token Result;
549 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
550 AST.getLangOpts(), false)) {
551 // getRawToken failed, just use InputLocation.
552 return InputLocation;
553 }
554
555 if (Result.is(tok::raw_identifier)) {
556 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
557 AST.getLangOpts());
558 }
559
560 return InputLocation;
561}