blob: 41f2df3669e99bdc55de190eb8524d821a240e92 [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 Biryukov6c5e99e2018-05-24 15:50:15 +000016#include "clang/AST/ASTContext.h"
17#include "clang/Basic/LangOptions.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000018#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000020#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000021#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000022#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000024#include "clang/Lex/Lexer.h"
25#include "clang/Lex/MacroInfo.h"
26#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000027#include "clang/Sema/Sema.h"
28#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000029#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000030#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/Support/CrashRecoveryContext.h"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000033#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000034#include <algorithm>
35
Ilya Biryukov38d79772017-05-16 09:38:59 +000036using namespace clang::clangd;
37using namespace clang;
38
Ilya Biryukov04db3682017-07-21 13:29:29 +000039namespace {
40
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000041bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
42 const tooling::CompileCommand &RHS) {
43 // We don't check for Output, it should not matter to clangd.
44 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
45 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
46}
47
Ilya Biryukovdf842342018-01-25 14:32:21 +000048template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
49 return Vec.capacity() * sizeof(T);
50}
51
Ilya Biryukov04db3682017-07-21 13:29:29 +000052class DeclTrackingASTConsumer : public ASTConsumer {
53public:
54 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
55 : TopLevelDecls(TopLevelDecls) {}
56
57 bool HandleTopLevelDecl(DeclGroupRef DG) override {
58 for (const Decl *D : DG) {
59 // ObjCMethodDecl are not actually top-level decls.
60 if (isa<ObjCMethodDecl>(D))
61 continue;
62
63 TopLevelDecls.push_back(D);
64 }
65 return true;
66 }
67
68private:
69 std::vector<const Decl *> &TopLevelDecls;
70};
71
72class ClangdFrontendAction : public SyntaxOnlyAction {
73public:
74 std::vector<const Decl *> takeTopLevelDecls() {
75 return std::move(TopLevelDecls);
76 }
77
78protected:
79 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
80 StringRef InFile) override {
81 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
82 }
83
84private:
85 std::vector<const Decl *> TopLevelDecls;
86};
87
Ilya Biryukov02d58702017-08-01 15:51:38 +000088class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000089public:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000090 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
91 : File(File), ParsedCallback(ParsedCallback) {}
92
Ilya Biryukov04db3682017-07-21 13:29:29 +000093 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
94 return std::move(TopLevelDeclIDs);
95 }
96
Eric Liu155f5a42018-05-14 12:19:16 +000097 std::vector<Inclusion> takeInclusions() { return std::move(Inclusions); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000098
Ilya Biryukov04db3682017-07-21 13:29:29 +000099 void AfterPCHEmitted(ASTWriter &Writer) override {
100 TopLevelDeclIDs.reserve(TopLevelDecls.size());
101 for (Decl *D : TopLevelDecls) {
102 // Invalid top-level decls may not have been serialized.
103 if (D->isInvalidDecl())
104 continue;
105 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
106 }
107 }
108
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000109 void AfterExecute(CompilerInstance &CI) override {
110 if (!ParsedCallback)
111 return;
112 trace::Span Tracer("Running PreambleCallback");
113 ParsedCallback(File, CI.getASTContext(), CI.getPreprocessorPtr());
114 }
115
Ilya Biryukov04db3682017-07-21 13:29:29 +0000116 void HandleTopLevelDecl(DeclGroupRef DG) override {
117 for (Decl *D : DG) {
118 if (isa<ObjCMethodDecl>(D))
119 continue;
120 TopLevelDecls.push_back(D);
121 }
122 }
123
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000124 void BeforeExecute(CompilerInstance &CI) override {
125 SourceMgr = &CI.getSourceManager();
126 }
127
128 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
129 assert(SourceMgr && "SourceMgr must be set at this point");
Eric Liu155f5a42018-05-14 12:19:16 +0000130 return collectInclusionsInMainFileCallback(
131 *SourceMgr,
132 [this](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); });
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000133 }
134
Ilya Biryukov04db3682017-07-21 13:29:29 +0000135private:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000136 PathRef File;
137 PreambleParsedCallback ParsedCallback;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000138 std::vector<Decl *> TopLevelDecls;
139 std::vector<serialization::DeclID> TopLevelDeclIDs;
Eric Liu155f5a42018-05-14 12:19:16 +0000140 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000141 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000142};
143
Ilya Biryukov04db3682017-07-21 13:29:29 +0000144} // namespace
145
Ilya Biryukov02d58702017-08-01 15:51:38 +0000146void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
147 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000148}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000149
Ilya Biryukov02d58702017-08-01 15:51:38 +0000150llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000151ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000152 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000153 std::unique_ptr<llvm::MemoryBuffer> Buffer,
154 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000155 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000156 const PrecompiledPreamble *PreamblePCH =
157 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000158
159 StoreDiags ASTDiags;
160 auto Clang =
161 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
162 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000163 if (!Clang)
164 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000165
166 // Recover resources if we crash before exiting this method.
167 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
168 Clang.get());
169
170 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000171 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
172 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000173 log("BeginSourceFile() failed when building AST for " +
174 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000175 return llvm::None;
176 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000177
Eric Liu155f5a42018-05-14 12:19:16 +0000178 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000179 // Copy over the includes from the preamble, then combine with the
180 // non-preamble includes below.
181 if (Preamble)
Eric Liu155f5a42018-05-14 12:19:16 +0000182 Inclusions = Preamble->Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000183
Eric Liu155f5a42018-05-14 12:19:16 +0000184 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
185 Clang->getSourceManager(),
186 [&Inclusions](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); }));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000187
Ilya Biryukove5128f72017-09-20 07:24:15 +0000188 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000189 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000190
191 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
192 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000193 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000194 // CompilerInstance won't run this callback, do it directly.
195 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000196
197 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000198 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000199 std::move(ParsedDecls), ASTDiags.take(),
Eric Liu155f5a42018-05-14 12:19:16 +0000200 std::move(Inclusions));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000201}
202
Ilya Biryukov02d58702017-08-01 15:51:38 +0000203void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000204 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000205 return;
206
207 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000208 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000209
210 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000211 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000212 // Resolve the declaration ID to an actual declaration, possibly
213 // deserializing the declaration in the process.
214 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
215 Resolved.push_back(D);
216 }
217
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000218 TopLevelDecls.reserve(TopLevelDecls.size() +
219 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000220 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
221
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000222 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000223}
224
Ilya Biryukov02d58702017-08-01 15:51:38 +0000225ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000228
Ilya Biryukov02d58702017-08-01 15:51:38 +0000229ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000230 if (Action) {
231 Action->EndSourceFile();
232 }
233}
234
Ilya Biryukov02d58702017-08-01 15:51:38 +0000235ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
236
237const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000238 return Clang->getASTContext();
239}
240
Ilya Biryukov02d58702017-08-01 15:51:38 +0000241Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000242
Eric Liu76f6b442018-01-09 17:32:00 +0000243std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
244 return Clang->getPreprocessorPtr();
245}
246
Ilya Biryukov02d58702017-08-01 15:51:38 +0000247const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000248 return Clang->getPreprocessor();
249}
250
Ilya Biryukov02d58702017-08-01 15:51:38 +0000251ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000252 ensurePreambleDeclsDeserialized();
253 return TopLevelDecls;
254}
255
Ilya Biryukov71028b82018-03-12 15:28:22 +0000256const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000257
Ilya Biryukovdf842342018-01-25 14:32:21 +0000258std::size_t ParsedAST::getUsedBytes() const {
259 auto &AST = getASTContext();
260 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000261 // Message and Fixes inside each diagnostic.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000262 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
263 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
264}
265
Eric Liu155f5a42018-05-14 12:19:16 +0000266const std::vector<Inclusion> &ParsedAST::getInclusions() const {
267 return Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000268}
269
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000270PreambleData::PreambleData(PrecompiledPreamble Preamble,
271 std::vector<serialization::DeclID> TopLevelDeclIDs,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000272 std::vector<Diag> Diags,
Eric Liu155f5a42018-05-14 12:19:16 +0000273 std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000274 : Preamble(std::move(Preamble)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000275 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)),
Eric Liu155f5a42018-05-14 12:19:16 +0000276 Inclusions(std::move(Inclusions)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000277
278ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
279 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000280 std::unique_ptr<FrontendAction> Action,
281 std::vector<const Decl *> TopLevelDecls,
Eric Liu155f5a42018-05-14 12:19:16 +0000282 std::vector<Diag> Diags, std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000283 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
284 Action(std::move(Action)), Diags(std::move(Diags)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000285 TopLevelDecls(std::move(TopLevelDecls)), PreambleDeclsDeserialized(false),
Eric Liu155f5a42018-05-14 12:19:16 +0000286 Inclusions(std::move(Inclusions)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000287 assert(this->Clang);
288 assert(this->Action);
289}
290
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000291CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000292 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000293 PreambleParsedCallback PreambleCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000294 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000295 PCHs(std::move(PCHs)), PreambleCallback(std::move(PreambleCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000296 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000297}
298
Ilya Biryukov71028b82018-03-12 15:28:22 +0000299llvm::Optional<std::vector<Diag>> CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000300 log("Rebuilding file " + FileName + " with command [" +
301 Inputs.CompileCommand.Directory + "] " +
302 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000303
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000304 std::vector<const char *> ArgStrs;
305 for (const auto &S : Inputs.CompileCommand.CommandLine)
306 ArgStrs.push_back(S.c_str());
307
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000308 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
309 log("Couldn't set working directory");
310 // We run parsing anyway, our lit-tests rely on results for non-existing
311 // working dirs.
312 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000313
314 // Prepare CompilerInvocation.
315 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000316 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000317 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
318 // reporting them.
319 IgnoreDiagnostics IgnoreDiagnostics;
320 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
321 CompilerInstance::createDiagnostics(new DiagnosticOptions,
322 &IgnoreDiagnostics, false);
323 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
324 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000325 if (!CI) {
326 log("Could not build CompilerInvocation for file " + FileName);
327 AST = llvm::None;
328 Preamble = nullptr;
329 return llvm::None;
330 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000331 // createInvocationFromCommandLine sets DisableFree.
332 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000333 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000334 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000335
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000336 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
337 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000338
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000339 // Compute updated Preamble.
340 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000341 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000342
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000343 // Remove current AST to avoid wasting memory.
344 AST = llvm::None;
345 // Compute updated AST.
346 llvm::Optional<ParsedAST> NewAST;
347 {
348 trace::Span Tracer("Build");
349 SPAN_ATTACH(Tracer, "File", FileName);
350 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
351 std::move(ContentsBuffer), PCHs, Inputs.FS);
352 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000353
Ilya Biryukov71028b82018-03-12 15:28:22 +0000354 std::vector<Diag> Diagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000355 if (NewAST) {
356 // Collect diagnostics from both the preamble and the AST.
357 if (NewPreamble)
Ilya Biryukov71028b82018-03-12 15:28:22 +0000358 Diagnostics = NewPreamble->Diags;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000359 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
360 NewAST->getDiagnostics().end());
361 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000362
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000363 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000364 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000365 Preamble = std::move(NewPreamble);
366 AST = std::move(NewAST);
367 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000368}
369
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000370const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
371 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000372}
373
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000374ParsedAST *CppFile::getAST() const {
375 // We could add mutable to AST instead of const_cast here, but that would also
376 // allow writing to AST from const methods.
377 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000378}
379
Ilya Biryukovdf842342018-01-25 14:32:21 +0000380std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000381 std::size_t Total = 0;
382 if (AST)
383 Total += AST->getUsedBytes();
384 if (StorePreamblesInMemory && Preamble)
385 Total += Preamble->Preamble.getSize();
386 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000387}
388
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000389std::shared_ptr<const PreambleData>
390CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000391 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000392 IntrusiveRefCntPtr<vfs::FileSystem> FS,
393 llvm::MemoryBuffer &ContentsBuffer) const {
394 const auto &OldPreamble = this->Preamble;
395 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000396 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000397 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
398 log("Reusing preamble for file " + Twine(FileName));
399 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000400 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000401 log("Preamble for file " + Twine(FileName) +
402 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000404 trace::Span Tracer("Preamble");
405 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000406 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000407 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
408 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000409 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000410
411 // Skip function bodies when building the preamble to speed up building
412 // the preamble and make it smaller.
413 assert(!CI.getFrontendOpts().SkipFunctionBodies);
414 CI.getFrontendOpts().SkipFunctionBodies = true;
415
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000416 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000417 auto BuiltPreamble = PrecompiledPreamble::Build(
418 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
419 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
420
421 // When building the AST for the main file, we do want the function
422 // bodies.
423 CI.getFrontendOpts().SkipFunctionBodies = false;
424
425 if (BuiltPreamble) {
426 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
427 " for file " + Twine(FileName));
428
429 return std::make_shared<PreambleData>(
430 std::move(*BuiltPreamble),
431 SerializedDeclsCollector.takeTopLevelDeclIDs(),
Eric Liu155f5a42018-05-14 12:19:16 +0000432 PreambleDiagnostics.take(), SerializedDeclsCollector.takeInclusions());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000433 } else {
434 log("Could not build a preamble for file " + Twine(FileName));
435 return nullptr;
436 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000437}
Haojian Wu345099c2017-11-09 11:30:04 +0000438
439SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
440 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000441 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000442 const ASTContext &AST = Unit.getASTContext();
443 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000444 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
445 if (!Offset) {
446 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
447 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000448 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000449 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000450
Sam McCalla4962cc2018-04-27 11:59:28 +0000451 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
452 // if the cursor is at the end of the identifier.
453 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
454 // 1) at the beginning of an identifier, we'll be looking at something
455 // that isn't an identifier.
456 // 2) at the middle or end of an identifier, we get the identifier.
457 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
458 // We can't actually distinguish cases 1 and 3, but returning the original
459 // location is correct for both!
460 if (*Offset == 0) // Case 1 or 3.
461 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
462 SourceLocation Before =
463 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
464 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
465 Token Tok;
466 if (Before.isValid() &&
467 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
468 Tok.is(tok::raw_identifier))
469 return Before; // Case 2.
470 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000471}