blob: fd8f1ec2765d936ee18ff0db19e3dcdee6087872 [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
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000086class InclusionLocationsCollector : public PPCallbacks {
87public:
88 InclusionLocationsCollector(SourceManager &SourceMgr,
89 InclusionLocations &IncLocations)
90 : SourceMgr(SourceMgr), IncLocations(IncLocations) {}
91
92 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
93 StringRef FileName, bool IsAngled,
94 CharSourceRange FilenameRange, const FileEntry *File,
95 StringRef SearchPath, StringRef RelativePath,
Julie Hockett546943f2018-05-10 19:13:14 +000096 const Module *Imported,
97 SrcMgr::CharacteristicKind FileType) override {
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000098 auto SR = FilenameRange.getAsRange();
99 if (SR.isInvalid() || !File || File->tryGetRealPathName().empty())
100 return;
101
102 if (SourceMgr.isInMainFile(SR.getBegin())) {
103 // Only inclusion directives in the main file make sense. The user cannot
104 // select directives not in the main file.
Ilya Biryukov71028b82018-03-12 15:28:22 +0000105 IncLocations.emplace_back(halfOpenToRange(SourceMgr, FilenameRange),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000106 File->tryGetRealPathName());
107 }
108 }
109
110private:
111 SourceManager &SourceMgr;
112 InclusionLocations &IncLocations;
113};
114
Ilya Biryukov02d58702017-08-01 15:51:38 +0000115class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000116public:
117 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
118 return std::move(TopLevelDeclIDs);
119 }
120
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000121 InclusionLocations takeInclusionLocations() {
122 return std::move(IncLocations);
123 }
124
Ilya Biryukov04db3682017-07-21 13:29:29 +0000125 void AfterPCHEmitted(ASTWriter &Writer) override {
126 TopLevelDeclIDs.reserve(TopLevelDecls.size());
127 for (Decl *D : TopLevelDecls) {
128 // Invalid top-level decls may not have been serialized.
129 if (D->isInvalidDecl())
130 continue;
131 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
132 }
133 }
134
135 void HandleTopLevelDecl(DeclGroupRef DG) override {
136 for (Decl *D : DG) {
137 if (isa<ObjCMethodDecl>(D))
138 continue;
139 TopLevelDecls.push_back(D);
140 }
141 }
142
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000143 void BeforeExecute(CompilerInstance &CI) override {
144 SourceMgr = &CI.getSourceManager();
145 }
146
147 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
148 assert(SourceMgr && "SourceMgr must be set at this point");
149 return llvm::make_unique<InclusionLocationsCollector>(*SourceMgr,
150 IncLocations);
151 }
152
Ilya Biryukov04db3682017-07-21 13:29:29 +0000153private:
154 std::vector<Decl *> TopLevelDecls;
155 std::vector<serialization::DeclID> TopLevelDeclIDs;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000156 InclusionLocations IncLocations;
157 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000158};
159
Ilya Biryukov04db3682017-07-21 13:29:29 +0000160} // namespace
161
Ilya Biryukov02d58702017-08-01 15:51:38 +0000162void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
163 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000164}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000165
Ilya Biryukov02d58702017-08-01 15:51:38 +0000166llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000167ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000168 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000169 std::unique_ptr<llvm::MemoryBuffer> Buffer,
170 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000171 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000172 const PrecompiledPreamble *PreamblePCH =
173 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000174
175 StoreDiags ASTDiags;
176 auto Clang =
177 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
178 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000179 if (!Clang)
180 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000181
182 // Recover resources if we crash before exiting this method.
183 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
184 Clang.get());
185
186 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000187 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
188 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000189 log("BeginSourceFile() failed when building AST for " +
190 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000191 return llvm::None;
192 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000193
194 InclusionLocations IncLocations;
195 // Copy over the includes from the preamble, then combine with the
196 // non-preamble includes below.
197 if (Preamble)
198 IncLocations = Preamble->IncLocations;
199
200 Clang->getPreprocessor().addPPCallbacks(
201 llvm::make_unique<InclusionLocationsCollector>(Clang->getSourceManager(),
202 IncLocations));
203
Ilya Biryukove5128f72017-09-20 07:24:15 +0000204 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000205 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000206
207 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
208 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000209 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000210 // CompilerInstance won't run this callback, do it directly.
211 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000212
213 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000214 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000215 std::move(ParsedDecls), ASTDiags.take(),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000216 std::move(IncLocations));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000217}
218
Ilya Biryukov02d58702017-08-01 15:51:38 +0000219void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000220 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000221 return;
222
223 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000224 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000225
226 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000227 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000228 // Resolve the declaration ID to an actual declaration, possibly
229 // deserializing the declaration in the process.
230 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
231 Resolved.push_back(D);
232 }
233
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000234 TopLevelDecls.reserve(TopLevelDecls.size() +
235 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000236 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
237
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000238 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000239}
240
Ilya Biryukov02d58702017-08-01 15:51:38 +0000241ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000242
Ilya Biryukov02d58702017-08-01 15:51:38 +0000243ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000244
Ilya Biryukov02d58702017-08-01 15:51:38 +0000245ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000246 if (Action) {
247 Action->EndSourceFile();
248 }
249}
250
Ilya Biryukov02d58702017-08-01 15:51:38 +0000251ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
252
253const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000254 return Clang->getASTContext();
255}
256
Ilya Biryukov02d58702017-08-01 15:51:38 +0000257Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000258
Eric Liu76f6b442018-01-09 17:32:00 +0000259std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
260 return Clang->getPreprocessorPtr();
261}
262
Ilya Biryukov02d58702017-08-01 15:51:38 +0000263const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000264 return Clang->getPreprocessor();
265}
266
Ilya Biryukov02d58702017-08-01 15:51:38 +0000267ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268 ensurePreambleDeclsDeserialized();
269 return TopLevelDecls;
270}
271
Ilya Biryukov71028b82018-03-12 15:28:22 +0000272const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000273
Ilya Biryukovdf842342018-01-25 14:32:21 +0000274std::size_t ParsedAST::getUsedBytes() const {
275 auto &AST = getASTContext();
276 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000277 // Message and Fixes inside each diagnostic.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000278 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
279 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
280}
281
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000282const InclusionLocations &ParsedAST::getInclusionLocations() const {
283 return IncLocations;
284}
285
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000286PreambleData::PreambleData(PrecompiledPreamble Preamble,
287 std::vector<serialization::DeclID> TopLevelDeclIDs,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000288 std::vector<Diag> Diags,
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000289 InclusionLocations IncLocations)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000290 : Preamble(std::move(Preamble)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000291 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)),
292 IncLocations(std::move(IncLocations)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000293
294ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
295 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000296 std::unique_ptr<FrontendAction> Action,
297 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000298 std::vector<Diag> Diags, InclusionLocations IncLocations)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000299 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
300 Action(std::move(Action)), Diags(std::move(Diags)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000301 TopLevelDecls(std::move(TopLevelDecls)), PreambleDeclsDeserialized(false),
302 IncLocations(std::move(IncLocations)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000303 assert(this->Clang);
304 assert(this->Action);
305}
306
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000307CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000308 std::shared_ptr<PCHContainerOperations> PCHs,
309 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000310 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000311 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000312 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000313}
314
Ilya Biryukov71028b82018-03-12 15:28:22 +0000315llvm::Optional<std::vector<Diag>> CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000316 log("Rebuilding file " + FileName + " with command [" +
317 Inputs.CompileCommand.Directory + "] " +
318 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000319
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000320 std::vector<const char *> ArgStrs;
321 for (const auto &S : Inputs.CompileCommand.CommandLine)
322 ArgStrs.push_back(S.c_str());
323
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000324 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
325 log("Couldn't set working directory");
326 // We run parsing anyway, our lit-tests rely on results for non-existing
327 // working dirs.
328 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000329
330 // Prepare CompilerInvocation.
331 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000332 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000333 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
334 // reporting them.
335 IgnoreDiagnostics IgnoreDiagnostics;
336 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
337 CompilerInstance::createDiagnostics(new DiagnosticOptions,
338 &IgnoreDiagnostics, false);
339 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
340 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000341 if (!CI) {
342 log("Could not build CompilerInvocation for file " + FileName);
343 AST = llvm::None;
344 Preamble = nullptr;
345 return llvm::None;
346 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000347 // createInvocationFromCommandLine sets DisableFree.
348 CI->getFrontendOpts().DisableFree = false;
349 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000350
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000351 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
352 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000354 // Compute updated Preamble.
355 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000356 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000357
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000358 // Remove current AST to avoid wasting memory.
359 AST = llvm::None;
360 // Compute updated AST.
361 llvm::Optional<ParsedAST> NewAST;
362 {
363 trace::Span Tracer("Build");
364 SPAN_ATTACH(Tracer, "File", FileName);
365 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
366 std::move(ContentsBuffer), PCHs, Inputs.FS);
367 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000368
Ilya Biryukov71028b82018-03-12 15:28:22 +0000369 std::vector<Diag> Diagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000370 if (NewAST) {
371 // Collect diagnostics from both the preamble and the AST.
372 if (NewPreamble)
Ilya Biryukov71028b82018-03-12 15:28:22 +0000373 Diagnostics = NewPreamble->Diags;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000374 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
375 NewAST->getDiagnostics().end());
376 }
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000377 if (ASTCallback && NewAST) {
378 trace::Span Tracer("Running ASTCallback");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000379 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000380 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000381
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000382 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000383 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000384 Preamble = std::move(NewPreamble);
385 AST = std::move(NewAST);
386 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000387}
388
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000389const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
390 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000391}
392
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000393ParsedAST *CppFile::getAST() const {
394 // We could add mutable to AST instead of const_cast here, but that would also
395 // allow writing to AST from const methods.
396 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397}
398
Ilya Biryukovdf842342018-01-25 14:32:21 +0000399std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000400 std::size_t Total = 0;
401 if (AST)
402 Total += AST->getUsedBytes();
403 if (StorePreamblesInMemory && Preamble)
404 Total += Preamble->Preamble.getSize();
405 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000406}
407
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000408std::shared_ptr<const PreambleData>
409CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000410 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000411 IntrusiveRefCntPtr<vfs::FileSystem> FS,
412 llvm::MemoryBuffer &ContentsBuffer) const {
413 const auto &OldPreamble = this->Preamble;
414 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000415 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000416 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
417 log("Reusing preamble for file " + Twine(FileName));
418 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000419 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000420 log("Preamble for file " + Twine(FileName) +
421 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000422
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000423 trace::Span Tracer("Preamble");
424 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000425 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000426 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
427 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000428 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000429
430 // Skip function bodies when building the preamble to speed up building
431 // the preamble and make it smaller.
432 assert(!CI.getFrontendOpts().SkipFunctionBodies);
433 CI.getFrontendOpts().SkipFunctionBodies = true;
434
435 CppFilePreambleCallbacks SerializedDeclsCollector;
436 auto BuiltPreamble = PrecompiledPreamble::Build(
437 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
438 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
439
440 // When building the AST for the main file, we do want the function
441 // bodies.
442 CI.getFrontendOpts().SkipFunctionBodies = false;
443
444 if (BuiltPreamble) {
445 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
446 " for file " + Twine(FileName));
447
448 return std::make_shared<PreambleData>(
449 std::move(*BuiltPreamble),
450 SerializedDeclsCollector.takeTopLevelDeclIDs(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000451 PreambleDiagnostics.take(),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000452 SerializedDeclsCollector.takeInclusionLocations());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000453 } else {
454 log("Could not build a preamble for file " + Twine(FileName));
455 return nullptr;
456 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000457}
Haojian Wu345099c2017-11-09 11:30:04 +0000458
459SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
460 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000461 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000462 const ASTContext &AST = Unit.getASTContext();
463 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000464 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
465 if (!Offset) {
466 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
467 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000468 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000469 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000470
Sam McCalla4962cc2018-04-27 11:59:28 +0000471 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
472 // if the cursor is at the end of the identifier.
473 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
474 // 1) at the beginning of an identifier, we'll be looking at something
475 // that isn't an identifier.
476 // 2) at the middle or end of an identifier, we get the identifier.
477 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
478 // We can't actually distinguish cases 1 and 3, but returning the original
479 // location is correct for both!
480 if (*Offset == 0) // Case 1 or 3.
481 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
482 SourceLocation Before =
483 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
484 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
485 Token Tok;
486 if (Before.isValid() &&
487 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
488 Tok.is(tok::raw_identifier))
489 return Before; // Case 2.
490 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000491}