blob: ab87463774c4ad68d39778c44504a1cd53dff8a4 [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 Biryukov04db3682017-07-21 13:29:29 +000028#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/Support/CrashRecoveryContext.h"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000031#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032#include <algorithm>
33
Ilya Biryukov38d79772017-05-16 09:38:59 +000034using namespace clang::clangd;
35using namespace clang;
36
Ilya Biryukov04db3682017-07-21 13:29:29 +000037namespace {
38
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000039bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
40 const tooling::CompileCommand &RHS) {
41 // We don't check for Output, it should not matter to clangd.
42 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
43 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
44}
45
Ilya Biryukovdf842342018-01-25 14:32:21 +000046template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
47 return Vec.capacity() * sizeof(T);
48}
49
Ilya Biryukov04db3682017-07-21 13:29:29 +000050class DeclTrackingASTConsumer : public ASTConsumer {
51public:
52 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
53 : TopLevelDecls(TopLevelDecls) {}
54
55 bool HandleTopLevelDecl(DeclGroupRef DG) override {
56 for (const Decl *D : DG) {
57 // ObjCMethodDecl are not actually top-level decls.
58 if (isa<ObjCMethodDecl>(D))
59 continue;
60
61 TopLevelDecls.push_back(D);
62 }
63 return true;
64 }
65
66private:
67 std::vector<const Decl *> &TopLevelDecls;
68};
69
70class ClangdFrontendAction : public SyntaxOnlyAction {
71public:
72 std::vector<const Decl *> takeTopLevelDecls() {
73 return std::move(TopLevelDecls);
74 }
75
76protected:
77 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
78 StringRef InFile) override {
79 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
80 }
81
82private:
83 std::vector<const Decl *> TopLevelDecls;
84};
85
Ilya Biryukov02d58702017-08-01 15:51:38 +000086class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000087public:
88 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
89 return std::move(TopLevelDeclIDs);
90 }
91
Eric Liu155f5a42018-05-14 12:19:16 +000092 std::vector<Inclusion> takeInclusions() { return std::move(Inclusions); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000093
Ilya Biryukov04db3682017-07-21 13:29:29 +000094 void AfterPCHEmitted(ASTWriter &Writer) override {
95 TopLevelDeclIDs.reserve(TopLevelDecls.size());
96 for (Decl *D : TopLevelDecls) {
97 // Invalid top-level decls may not have been serialized.
98 if (D->isInvalidDecl())
99 continue;
100 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
101 }
102 }
103
104 void HandleTopLevelDecl(DeclGroupRef DG) override {
105 for (Decl *D : DG) {
106 if (isa<ObjCMethodDecl>(D))
107 continue;
108 TopLevelDecls.push_back(D);
109 }
110 }
111
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000112 void BeforeExecute(CompilerInstance &CI) override {
113 SourceMgr = &CI.getSourceManager();
114 }
115
116 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
117 assert(SourceMgr && "SourceMgr must be set at this point");
Eric Liu155f5a42018-05-14 12:19:16 +0000118 return collectInclusionsInMainFileCallback(
119 *SourceMgr,
120 [this](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); });
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000121 }
122
Ilya Biryukov04db3682017-07-21 13:29:29 +0000123private:
124 std::vector<Decl *> TopLevelDecls;
125 std::vector<serialization::DeclID> TopLevelDeclIDs;
Eric Liu155f5a42018-05-14 12:19:16 +0000126 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000127 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000128};
129
Ilya Biryukov04db3682017-07-21 13:29:29 +0000130} // namespace
131
Ilya Biryukov02d58702017-08-01 15:51:38 +0000132void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
133 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000134}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000135
Ilya Biryukov02d58702017-08-01 15:51:38 +0000136llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000137ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000138 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000139 std::unique_ptr<llvm::MemoryBuffer> Buffer,
140 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000141 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000142 const PrecompiledPreamble *PreamblePCH =
143 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000144
145 StoreDiags ASTDiags;
146 auto Clang =
147 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
148 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000149 if (!Clang)
150 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000151
152 // Recover resources if we crash before exiting this method.
153 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
154 Clang.get());
155
156 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000157 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
158 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000159 log("BeginSourceFile() failed when building AST for " +
160 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000161 return llvm::None;
162 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000163
Eric Liu155f5a42018-05-14 12:19:16 +0000164 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000165 // Copy over the includes from the preamble, then combine with the
166 // non-preamble includes below.
167 if (Preamble)
Eric Liu155f5a42018-05-14 12:19:16 +0000168 Inclusions = Preamble->Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000169
Eric Liu155f5a42018-05-14 12:19:16 +0000170 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
171 Clang->getSourceManager(),
172 [&Inclusions](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); }));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000173
Ilya Biryukove5128f72017-09-20 07:24:15 +0000174 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000175 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000176
177 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
178 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000179 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000180 // CompilerInstance won't run this callback, do it directly.
181 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000182
183 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000184 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000185 std::move(ParsedDecls), ASTDiags.take(),
Eric Liu155f5a42018-05-14 12:19:16 +0000186 std::move(Inclusions));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000187}
188
Ilya Biryukov02d58702017-08-01 15:51:38 +0000189void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000190 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000191 return;
192
193 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000194 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000195
196 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000197 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000198 // Resolve the declaration ID to an actual declaration, possibly
199 // deserializing the declaration in the process.
200 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
201 Resolved.push_back(D);
202 }
203
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000204 TopLevelDecls.reserve(TopLevelDecls.size() +
205 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000206 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
207
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000208 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000209}
210
Ilya Biryukov02d58702017-08-01 15:51:38 +0000211ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000212
Ilya Biryukov02d58702017-08-01 15:51:38 +0000213ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000214
Ilya Biryukov02d58702017-08-01 15:51:38 +0000215ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000216 if (Action) {
217 Action->EndSourceFile();
218 }
219}
220
Ilya Biryukov02d58702017-08-01 15:51:38 +0000221ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
222
223const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000224 return Clang->getASTContext();
225}
226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000228
Eric Liu76f6b442018-01-09 17:32:00 +0000229std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
230 return Clang->getPreprocessorPtr();
231}
232
Ilya Biryukov02d58702017-08-01 15:51:38 +0000233const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000234 return Clang->getPreprocessor();
235}
236
Ilya Biryukov02d58702017-08-01 15:51:38 +0000237ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000238 ensurePreambleDeclsDeserialized();
239 return TopLevelDecls;
240}
241
Ilya Biryukov71028b82018-03-12 15:28:22 +0000242const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000243
Ilya Biryukovdf842342018-01-25 14:32:21 +0000244std::size_t ParsedAST::getUsedBytes() const {
245 auto &AST = getASTContext();
246 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000247 // Message and Fixes inside each diagnostic.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000248 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
249 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
250}
251
Eric Liu155f5a42018-05-14 12:19:16 +0000252const std::vector<Inclusion> &ParsedAST::getInclusions() const {
253 return Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000254}
255
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000256PreambleData::PreambleData(PrecompiledPreamble Preamble,
257 std::vector<serialization::DeclID> TopLevelDeclIDs,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000258 std::vector<Diag> Diags,
Eric Liu155f5a42018-05-14 12:19:16 +0000259 std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000260 : Preamble(std::move(Preamble)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000261 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)),
Eric Liu155f5a42018-05-14 12:19:16 +0000262 Inclusions(std::move(Inclusions)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000263
264ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
265 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000266 std::unique_ptr<FrontendAction> Action,
267 std::vector<const Decl *> TopLevelDecls,
Eric Liu155f5a42018-05-14 12:19:16 +0000268 std::vector<Diag> Diags, std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000269 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
270 Action(std::move(Action)), Diags(std::move(Diags)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000271 TopLevelDecls(std::move(TopLevelDecls)), PreambleDeclsDeserialized(false),
Eric Liu155f5a42018-05-14 12:19:16 +0000272 Inclusions(std::move(Inclusions)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000273 assert(this->Clang);
274 assert(this->Action);
275}
276
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000277CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000278 std::shared_ptr<PCHContainerOperations> PCHs,
279 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000280 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000281 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000282 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000283}
284
Ilya Biryukov71028b82018-03-12 15:28:22 +0000285llvm::Optional<std::vector<Diag>> CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000286 log("Rebuilding file " + FileName + " with command [" +
287 Inputs.CompileCommand.Directory + "] " +
288 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000289
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000290 std::vector<const char *> ArgStrs;
291 for (const auto &S : Inputs.CompileCommand.CommandLine)
292 ArgStrs.push_back(S.c_str());
293
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000294 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
295 log("Couldn't set working directory");
296 // We run parsing anyway, our lit-tests rely on results for non-existing
297 // working dirs.
298 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000299
300 // Prepare CompilerInvocation.
301 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000302 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000303 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
304 // reporting them.
305 IgnoreDiagnostics IgnoreDiagnostics;
306 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
307 CompilerInstance::createDiagnostics(new DiagnosticOptions,
308 &IgnoreDiagnostics, false);
309 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
310 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000311 if (!CI) {
312 log("Could not build CompilerInvocation for file " + FileName);
313 AST = llvm::None;
314 Preamble = nullptr;
315 return llvm::None;
316 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000317 // createInvocationFromCommandLine sets DisableFree.
318 CI->getFrontendOpts().DisableFree = false;
319 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000320
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000321 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
322 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000323
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000324 // Compute updated Preamble.
325 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000326 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000327
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000328 // Remove current AST to avoid wasting memory.
329 AST = llvm::None;
330 // Compute updated AST.
331 llvm::Optional<ParsedAST> NewAST;
332 {
333 trace::Span Tracer("Build");
334 SPAN_ATTACH(Tracer, "File", FileName);
335 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
336 std::move(ContentsBuffer), PCHs, Inputs.FS);
337 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000338
Ilya Biryukov71028b82018-03-12 15:28:22 +0000339 std::vector<Diag> Diagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000340 if (NewAST) {
341 // Collect diagnostics from both the preamble and the AST.
342 if (NewPreamble)
Ilya Biryukov71028b82018-03-12 15:28:22 +0000343 Diagnostics = NewPreamble->Diags;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000344 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
345 NewAST->getDiagnostics().end());
346 }
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000347 if (ASTCallback && NewAST) {
348 trace::Span Tracer("Running ASTCallback");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000349 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000350 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000351
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000352 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000353 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000354 Preamble = std::move(NewPreamble);
355 AST = std::move(NewAST);
356 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000357}
358
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000359const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
360 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000361}
362
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000363ParsedAST *CppFile::getAST() const {
364 // We could add mutable to AST instead of const_cast here, but that would also
365 // allow writing to AST from const methods.
366 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000367}
368
Ilya Biryukovdf842342018-01-25 14:32:21 +0000369std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000370 std::size_t Total = 0;
371 if (AST)
372 Total += AST->getUsedBytes();
373 if (StorePreamblesInMemory && Preamble)
374 Total += Preamble->Preamble.getSize();
375 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000376}
377
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000378std::shared_ptr<const PreambleData>
379CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000380 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000381 IntrusiveRefCntPtr<vfs::FileSystem> FS,
382 llvm::MemoryBuffer &ContentsBuffer) const {
383 const auto &OldPreamble = this->Preamble;
384 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000385 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000386 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
387 log("Reusing preamble for file " + Twine(FileName));
388 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000389 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000390 log("Preamble for file " + Twine(FileName) +
391 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000392
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000393 trace::Span Tracer("Preamble");
394 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000395 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000396 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
397 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000398 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000399
400 // Skip function bodies when building the preamble to speed up building
401 // the preamble and make it smaller.
402 assert(!CI.getFrontendOpts().SkipFunctionBodies);
403 CI.getFrontendOpts().SkipFunctionBodies = true;
404
405 CppFilePreambleCallbacks SerializedDeclsCollector;
406 auto BuiltPreamble = PrecompiledPreamble::Build(
407 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
408 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
409
410 // When building the AST for the main file, we do want the function
411 // bodies.
412 CI.getFrontendOpts().SkipFunctionBodies = false;
413
414 if (BuiltPreamble) {
415 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
416 " for file " + Twine(FileName));
417
418 return std::make_shared<PreambleData>(
419 std::move(*BuiltPreamble),
420 SerializedDeclsCollector.takeTopLevelDeclIDs(),
Eric Liu155f5a42018-05-14 12:19:16 +0000421 PreambleDiagnostics.take(), SerializedDeclsCollector.takeInclusions());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000422 } else {
423 log("Could not build a preamble for file " + Twine(FileName));
424 return nullptr;
425 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000426}
Haojian Wu345099c2017-11-09 11:30:04 +0000427
428SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
429 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000430 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000431 const ASTContext &AST = Unit.getASTContext();
432 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000433 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
434 if (!Offset) {
435 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
436 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000437 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000438 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000439
Sam McCalla4962cc2018-04-27 11:59:28 +0000440 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
441 // if the cursor is at the end of the identifier.
442 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
443 // 1) at the beginning of an identifier, we'll be looking at something
444 // that isn't an identifier.
445 // 2) at the middle or end of an identifier, we get the identifier.
446 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
447 // We can't actually distinguish cases 1 and 3, but returning the original
448 // location is correct for both!
449 if (*Offset == 0) // Case 1 or 3.
450 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
451 SourceLocation Before =
452 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
453 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
454 Token Tok;
455 if (Before.isValid() &&
456 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
457 Tok.is(tok::raw_identifier))
458 return Before; // Case 2.
459 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000460}