blob: eb2fc184ccfe49fea97db339e5ba8f2f8e074b18 [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 Biryukov71028b82018-03-12 15:28:22 +000012#include "Diagnostics.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000013#include "Logger.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000014#include "SourceCode.h"
Sam McCall8567cb32017-11-02 09:21:51 +000015#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000018#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000019#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000021#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000022#include "clang/Lex/Lexer.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000025#include "clang/Sema/Sema.h"
26#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000027#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000028#include "clang/Basic/LangOptions.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000029#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/Support/CrashRecoveryContext.h"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000032#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000033#include <algorithm>
34
Ilya Biryukov38d79772017-05-16 09:38:59 +000035using namespace clang::clangd;
36using namespace clang;
37
Ilya Biryukov04db3682017-07-21 13:29:29 +000038namespace {
39
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000040bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
41 const tooling::CompileCommand &RHS) {
42 // We don't check for Output, it should not matter to clangd.
43 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
44 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
45}
46
Ilya Biryukovdf842342018-01-25 14:32:21 +000047template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
48 return Vec.capacity() * sizeof(T);
49}
50
Ilya Biryukov04db3682017-07-21 13:29:29 +000051class DeclTrackingASTConsumer : public ASTConsumer {
52public:
53 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
54 : TopLevelDecls(TopLevelDecls) {}
55
56 bool HandleTopLevelDecl(DeclGroupRef DG) override {
57 for (const Decl *D : DG) {
58 // ObjCMethodDecl are not actually top-level decls.
59 if (isa<ObjCMethodDecl>(D))
60 continue;
61
62 TopLevelDecls.push_back(D);
63 }
64 return true;
65 }
66
67private:
68 std::vector<const Decl *> &TopLevelDecls;
69};
70
71class ClangdFrontendAction : public SyntaxOnlyAction {
72public:
73 std::vector<const Decl *> takeTopLevelDecls() {
74 return std::move(TopLevelDecls);
75 }
76
77protected:
78 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
79 StringRef InFile) override {
80 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
81 }
82
83private:
84 std::vector<const Decl *> TopLevelDecls;
85};
86
Ilya Biryukov02d58702017-08-01 15:51:38 +000087class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000088public:
89 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
90 return std::move(TopLevelDeclIDs);
91 }
92
Eric Liu155f5a42018-05-14 12:19:16 +000093 std::vector<Inclusion> takeInclusions() { return std::move(Inclusions); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000094
Ilya Biryukov04db3682017-07-21 13:29:29 +000095 void AfterPCHEmitted(ASTWriter &Writer) override {
96 TopLevelDeclIDs.reserve(TopLevelDecls.size());
97 for (Decl *D : TopLevelDecls) {
98 // Invalid top-level decls may not have been serialized.
99 if (D->isInvalidDecl())
100 continue;
101 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
102 }
103 }
104
105 void HandleTopLevelDecl(DeclGroupRef DG) override {
106 for (Decl *D : DG) {
107 if (isa<ObjCMethodDecl>(D))
108 continue;
109 TopLevelDecls.push_back(D);
110 }
111 }
112
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000113 void BeforeExecute(CompilerInstance &CI) override {
114 SourceMgr = &CI.getSourceManager();
115 }
116
117 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
118 assert(SourceMgr && "SourceMgr must be set at this point");
Eric Liu155f5a42018-05-14 12:19:16 +0000119 return collectInclusionsInMainFileCallback(
120 *SourceMgr,
121 [this](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); });
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000122 }
123
Ilya Biryukov04db3682017-07-21 13:29:29 +0000124private:
125 std::vector<Decl *> TopLevelDecls;
126 std::vector<serialization::DeclID> TopLevelDeclIDs;
Eric Liu155f5a42018-05-14 12:19:16 +0000127 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000128 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000129};
130
Ilya Biryukov04db3682017-07-21 13:29:29 +0000131} // namespace
132
Ilya Biryukov02d58702017-08-01 15:51:38 +0000133void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
134 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000135}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000136
Ilya Biryukov02d58702017-08-01 15:51:38 +0000137llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000138ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000139 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000140 std::unique_ptr<llvm::MemoryBuffer> Buffer,
141 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000142 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000143 const PrecompiledPreamble *PreamblePCH =
144 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000145
146 StoreDiags ASTDiags;
147 auto Clang =
148 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
149 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000150 if (!Clang)
151 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000152
153 // Recover resources if we crash before exiting this method.
154 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
155 Clang.get());
156
157 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000158 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
159 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000160 log("BeginSourceFile() failed when building AST for " +
161 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000162 return llvm::None;
163 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000164
Eric Liu155f5a42018-05-14 12:19:16 +0000165 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000166 // Copy over the includes from the preamble, then combine with the
167 // non-preamble includes below.
168 if (Preamble)
Eric Liu155f5a42018-05-14 12:19:16 +0000169 Inclusions = Preamble->Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000170
Eric Liu155f5a42018-05-14 12:19:16 +0000171 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
172 Clang->getSourceManager(),
173 [&Inclusions](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); }));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000174
Ilya Biryukove5128f72017-09-20 07:24:15 +0000175 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000176 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000177
178 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
179 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000180 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000181 // CompilerInstance won't run this callback, do it directly.
182 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183
184 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000185 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000186 std::move(ParsedDecls), ASTDiags.take(),
Eric Liu155f5a42018-05-14 12:19:16 +0000187 std::move(Inclusions));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000188}
189
Ilya Biryukov02d58702017-08-01 15:51:38 +0000190void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000191 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000192 return;
193
194 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000195 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000196
197 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000198 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000199 // Resolve the declaration ID to an actual declaration, possibly
200 // deserializing the declaration in the process.
201 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
202 Resolved.push_back(D);
203 }
204
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000205 TopLevelDecls.reserve(TopLevelDecls.size() +
206 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000207 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
208
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000209 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000210}
211
Ilya Biryukov02d58702017-08-01 15:51:38 +0000212ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000213
Ilya Biryukov02d58702017-08-01 15:51:38 +0000214ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000215
Ilya Biryukov02d58702017-08-01 15:51:38 +0000216ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000217 if (Action) {
218 Action->EndSourceFile();
219 }
220}
221
Ilya Biryukov02d58702017-08-01 15:51:38 +0000222ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
223
224const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000225 return Clang->getASTContext();
226}
227
Ilya Biryukov02d58702017-08-01 15:51:38 +0000228Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000229
Eric Liu76f6b442018-01-09 17:32:00 +0000230std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
231 return Clang->getPreprocessorPtr();
232}
233
Ilya Biryukov02d58702017-08-01 15:51:38 +0000234const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000235 return Clang->getPreprocessor();
236}
237
Ilya Biryukov02d58702017-08-01 15:51:38 +0000238ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000239 ensurePreambleDeclsDeserialized();
240 return TopLevelDecls;
241}
242
Ilya Biryukov71028b82018-03-12 15:28:22 +0000243const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000244
Ilya Biryukovdf842342018-01-25 14:32:21 +0000245std::size_t ParsedAST::getUsedBytes() const {
246 auto &AST = getASTContext();
247 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000248 // Message and Fixes inside each diagnostic.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000249 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
250 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
251}
252
Eric Liu155f5a42018-05-14 12:19:16 +0000253const std::vector<Inclusion> &ParsedAST::getInclusions() const {
254 return Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000255}
256
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000257PreambleData::PreambleData(PrecompiledPreamble Preamble,
258 std::vector<serialization::DeclID> TopLevelDeclIDs,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000259 std::vector<Diag> Diags,
Eric Liu155f5a42018-05-14 12:19:16 +0000260 std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000261 : Preamble(std::move(Preamble)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000262 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)),
Eric Liu155f5a42018-05-14 12:19:16 +0000263 Inclusions(std::move(Inclusions)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000264
265ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
266 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000267 std::unique_ptr<FrontendAction> Action,
268 std::vector<const Decl *> TopLevelDecls,
Eric Liu155f5a42018-05-14 12:19:16 +0000269 std::vector<Diag> Diags, std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000270 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
271 Action(std::move(Action)), Diags(std::move(Diags)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000272 TopLevelDecls(std::move(TopLevelDecls)), PreambleDeclsDeserialized(false),
Eric Liu155f5a42018-05-14 12:19:16 +0000273 Inclusions(std::move(Inclusions)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000274 assert(this->Clang);
275 assert(this->Action);
276}
277
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000278CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000279 std::shared_ptr<PCHContainerOperations> PCHs,
280 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000281 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000282 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000283 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000284}
285
Ilya Biryukov71028b82018-03-12 15:28:22 +0000286llvm::Optional<std::vector<Diag>> CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000287 log("Rebuilding file " + FileName + " with command [" +
288 Inputs.CompileCommand.Directory + "] " +
289 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000290
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000291 std::vector<const char *> ArgStrs;
292 for (const auto &S : Inputs.CompileCommand.CommandLine)
293 ArgStrs.push_back(S.c_str());
294
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000295 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
296 log("Couldn't set working directory");
297 // We run parsing anyway, our lit-tests rely on results for non-existing
298 // working dirs.
299 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000300
301 // Prepare CompilerInvocation.
302 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000303 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000304 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
305 // reporting them.
306 IgnoreDiagnostics IgnoreDiagnostics;
307 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
308 CompilerInstance::createDiagnostics(new DiagnosticOptions,
309 &IgnoreDiagnostics, false);
310 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
311 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000312 if (!CI) {
313 log("Could not build CompilerInvocation for file " + FileName);
314 AST = llvm::None;
315 Preamble = nullptr;
316 return llvm::None;
317 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000318 // createInvocationFromCommandLine sets DisableFree.
319 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000320 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000321 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000322
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000323 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
324 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000325
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000326 // Compute updated Preamble.
327 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000328 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000329
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000330 // Remove current AST to avoid wasting memory.
331 AST = llvm::None;
332 // Compute updated AST.
333 llvm::Optional<ParsedAST> NewAST;
334 {
335 trace::Span Tracer("Build");
336 SPAN_ATTACH(Tracer, "File", FileName);
337 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
338 std::move(ContentsBuffer), PCHs, Inputs.FS);
339 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000340
Ilya Biryukov71028b82018-03-12 15:28:22 +0000341 std::vector<Diag> Diagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000342 if (NewAST) {
343 // Collect diagnostics from both the preamble and the AST.
344 if (NewPreamble)
Ilya Biryukov71028b82018-03-12 15:28:22 +0000345 Diagnostics = NewPreamble->Diags;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000346 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
347 NewAST->getDiagnostics().end());
348 }
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000349 if (ASTCallback && NewAST) {
350 trace::Span Tracer("Running ASTCallback");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000351 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000352 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000354 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000355 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000356 Preamble = std::move(NewPreamble);
357 AST = std::move(NewAST);
358 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000359}
360
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000361const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
362 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000363}
364
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000365ParsedAST *CppFile::getAST() const {
366 // We could add mutable to AST instead of const_cast here, but that would also
367 // allow writing to AST from const methods.
368 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000369}
370
Ilya Biryukovdf842342018-01-25 14:32:21 +0000371std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000372 std::size_t Total = 0;
373 if (AST)
374 Total += AST->getUsedBytes();
375 if (StorePreamblesInMemory && Preamble)
376 Total += Preamble->Preamble.getSize();
377 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000378}
379
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000380std::shared_ptr<const PreambleData>
381CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000382 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000383 IntrusiveRefCntPtr<vfs::FileSystem> FS,
384 llvm::MemoryBuffer &ContentsBuffer) const {
385 const auto &OldPreamble = this->Preamble;
386 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000387 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000388 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
389 log("Reusing preamble for file " + Twine(FileName));
390 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000391 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000392 log("Preamble for file " + Twine(FileName) +
393 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000394
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000395 trace::Span Tracer("Preamble");
396 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000397 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000398 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
399 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000400 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000401
402 // Skip function bodies when building the preamble to speed up building
403 // the preamble and make it smaller.
404 assert(!CI.getFrontendOpts().SkipFunctionBodies);
405 CI.getFrontendOpts().SkipFunctionBodies = true;
406
407 CppFilePreambleCallbacks SerializedDeclsCollector;
408 auto BuiltPreamble = PrecompiledPreamble::Build(
409 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
410 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
411
412 // When building the AST for the main file, we do want the function
413 // bodies.
414 CI.getFrontendOpts().SkipFunctionBodies = false;
415
416 if (BuiltPreamble) {
417 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
418 " for file " + Twine(FileName));
419
420 return std::make_shared<PreambleData>(
421 std::move(*BuiltPreamble),
422 SerializedDeclsCollector.takeTopLevelDeclIDs(),
Eric Liu155f5a42018-05-14 12:19:16 +0000423 PreambleDiagnostics.take(), SerializedDeclsCollector.takeInclusions());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000424 } else {
425 log("Could not build a preamble for file " + Twine(FileName));
426 return nullptr;
427 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000428}
Haojian Wu345099c2017-11-09 11:30:04 +0000429
430SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
431 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000432 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000433 const ASTContext &AST = Unit.getASTContext();
434 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000435 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
436 if (!Offset) {
437 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
438 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000439 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000440 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000441
Sam McCalla4962cc2018-04-27 11:59:28 +0000442 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
443 // if the cursor is at the end of the identifier.
444 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
445 // 1) at the beginning of an identifier, we'll be looking at something
446 // that isn't an identifier.
447 // 2) at the middle or end of an identifier, we get the identifier.
448 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
449 // We can't actually distinguish cases 1 and 3, but returning the original
450 // location is correct for both!
451 if (*Offset == 0) // Case 1 or 3.
452 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
453 SourceLocation Before =
454 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
455 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
456 Token Tok;
457 if (Before.isValid() &&
458 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
459 Tok.is(tok::raw_identifier))
460 return Before; // Case 2.
461 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000462}