blob: 4ad95c4dc5d863073427d15334423447ba5ad2e7 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9
10#include "ClangdUnit.h"
Sam McCall98775c52017-12-04 13:49:59 +000011#include "Compiler.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000029#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
31
Ilya Biryukov38d79772017-05-16 09:38:59 +000032using namespace clang::clangd;
33using namespace clang;
34
Ilya Biryukov04db3682017-07-21 13:29:29 +000035namespace {
36
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000037bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
38 const tooling::CompileCommand &RHS) {
39 // We don't check for Output, it should not matter to clangd.
40 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
41 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
42}
43
Ilya Biryukovdf842342018-01-25 14:32:21 +000044template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
45 return Vec.capacity() * sizeof(T);
46}
47
Ilya Biryukov04db3682017-07-21 13:29:29 +000048class DeclTrackingASTConsumer : public ASTConsumer {
49public:
50 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
51 : TopLevelDecls(TopLevelDecls) {}
52
53 bool HandleTopLevelDecl(DeclGroupRef DG) override {
54 for (const Decl *D : DG) {
55 // ObjCMethodDecl are not actually top-level decls.
56 if (isa<ObjCMethodDecl>(D))
57 continue;
58
59 TopLevelDecls.push_back(D);
60 }
61 return true;
62 }
63
64private:
65 std::vector<const Decl *> &TopLevelDecls;
66};
67
68class ClangdFrontendAction : public SyntaxOnlyAction {
69public:
70 std::vector<const Decl *> takeTopLevelDecls() {
71 return std::move(TopLevelDecls);
72 }
73
74protected:
75 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
76 StringRef InFile) override {
77 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
78 }
79
80private:
81 std::vector<const Decl *> TopLevelDecls;
82};
83
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000084// Converts a half-open clang source range to an LSP range.
85// Note that clang also uses closed source ranges, which this can't handle!
86Range toRange(CharSourceRange R, const SourceManager &M) {
87 // Clang is 1-based, LSP uses 0-based indexes.
88 Position Begin;
89 Begin.line = static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1;
90 Begin.character =
91 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1;
92
93 Position End;
94 End.line = static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1;
95 End.character = static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1;
96
97 return {Begin, End};
98}
99
100class InclusionLocationsCollector : public PPCallbacks {
101public:
102 InclusionLocationsCollector(SourceManager &SourceMgr,
103 InclusionLocations &IncLocations)
104 : SourceMgr(SourceMgr), IncLocations(IncLocations) {}
105
106 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
107 StringRef FileName, bool IsAngled,
108 CharSourceRange FilenameRange, const FileEntry *File,
109 StringRef SearchPath, StringRef RelativePath,
110 const Module *Imported) override {
111 auto SR = FilenameRange.getAsRange();
112 if (SR.isInvalid() || !File || File->tryGetRealPathName().empty())
113 return;
114
115 if (SourceMgr.isInMainFile(SR.getBegin())) {
116 // Only inclusion directives in the main file make sense. The user cannot
117 // select directives not in the main file.
118 IncLocations.emplace_back(toRange(FilenameRange, SourceMgr),
119 File->tryGetRealPathName());
120 }
121 }
122
123private:
124 SourceManager &SourceMgr;
125 InclusionLocations &IncLocations;
126};
127
Ilya Biryukov02d58702017-08-01 15:51:38 +0000128class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000129public:
130 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
131 return std::move(TopLevelDeclIDs);
132 }
133
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000134 InclusionLocations takeInclusionLocations() {
135 return std::move(IncLocations);
136 }
137
Ilya Biryukov04db3682017-07-21 13:29:29 +0000138 void AfterPCHEmitted(ASTWriter &Writer) override {
139 TopLevelDeclIDs.reserve(TopLevelDecls.size());
140 for (Decl *D : TopLevelDecls) {
141 // Invalid top-level decls may not have been serialized.
142 if (D->isInvalidDecl())
143 continue;
144 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
145 }
146 }
147
148 void HandleTopLevelDecl(DeclGroupRef DG) override {
149 for (Decl *D : DG) {
150 if (isa<ObjCMethodDecl>(D))
151 continue;
152 TopLevelDecls.push_back(D);
153 }
154 }
155
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000156 void BeforeExecute(CompilerInstance &CI) override {
157 SourceMgr = &CI.getSourceManager();
158 }
159
160 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
161 assert(SourceMgr && "SourceMgr must be set at this point");
162 return llvm::make_unique<InclusionLocationsCollector>(*SourceMgr,
163 IncLocations);
164 }
165
Ilya Biryukov04db3682017-07-21 13:29:29 +0000166private:
167 std::vector<Decl *> TopLevelDecls;
168 std::vector<serialization::DeclID> TopLevelDeclIDs;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000169 InclusionLocations IncLocations;
170 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000171};
172
173/// Convert from clang diagnostic level to LSP severity.
174static int getSeverity(DiagnosticsEngine::Level L) {
175 switch (L) {
176 case DiagnosticsEngine::Remark:
177 return 4;
178 case DiagnosticsEngine::Note:
179 return 3;
180 case DiagnosticsEngine::Warning:
181 return 2;
182 case DiagnosticsEngine::Fatal:
183 case DiagnosticsEngine::Error:
184 return 1;
185 case DiagnosticsEngine::Ignored:
186 return 0;
187 }
188 llvm_unreachable("Unknown diagnostic level!");
189}
190
Sam McCall8111d3b2017-12-13 08:48:42 +0000191// Checks whether a location is within a half-open range.
192// Note that clang also uses closed source ranges, which this can't handle!
193bool locationInRange(SourceLocation L, CharSourceRange R,
194 const SourceManager &M) {
195 assert(R.isCharRange());
196 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
197 M.getFileID(R.getBegin()) != M.getFileID(L))
198 return false;
199 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
200}
201
Sam McCall8111d3b2017-12-13 08:48:42 +0000202// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
203// LSP needs a single range.
204Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
205 auto &M = D.getSourceManager();
206 auto Loc = M.getFileLoc(D.getLocation());
207 // Accept the first range that contains the location.
208 for (const auto &CR : D.getRanges()) {
209 auto R = Lexer::makeFileCharRange(CR, M, L);
210 if (locationInRange(Loc, R, M))
211 return toRange(R, M);
212 }
213 // The range may be given as a fixit hint instead.
214 for (const auto &F : D.getFixItHints()) {
215 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
216 if (locationInRange(Loc, R, M))
217 return toRange(R, M);
218 }
219 // If no suitable range is found, just use the token at the location.
220 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
221 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
222 R = CharSourceRange::getCharRange(Loc);
223 return toRange(R, M);
224}
225
226TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
227 const LangOptions &L) {
228 TextEdit Result;
229 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
230 Result.newText = FixIt.CodeToInsert;
231 return Result;
232}
233
234llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
235 DiagnosticsEngine::Level Level,
236 const LangOptions &LangOpts) {
237 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000238 !D.getSourceManager().isInMainFile(D.getLocation())) {
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000239 IgnoreDiagnostics::log(Level, D);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000240 return llvm::None;
Ilya Biryukovd14dc492018-02-01 19:06:45 +0000241 }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000242
Ilya Biryukov2d4cdac2018-02-12 12:48:51 +0000243 SmallString<64> Message;
244 D.FormatDiagnostic(Message);
245
Sam McCall8111d3b2017-12-13 08:48:42 +0000246 DiagWithFixIts Result;
247 Result.Diag.range = diagnosticRange(D, LangOpts);
248 Result.Diag.severity = getSeverity(Level);
Sam McCall8111d3b2017-12-13 08:48:42 +0000249 Result.Diag.message = Message.str();
250 for (const FixItHint &Fix : D.getFixItHints())
251 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
252 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000253}
254
255class StoreDiagsConsumer : public DiagnosticConsumer {
256public:
257 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
258
Sam McCall8111d3b2017-12-13 08:48:42 +0000259 // Track language options in case we need to expand token ranges.
260 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
261 LangOpts = Opts;
262 }
263
264 void EndSourceFile() override { LangOpts = llvm::None; }
265
Ilya Biryukov04db3682017-07-21 13:29:29 +0000266 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
267 const clang::Diagnostic &Info) override {
268 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
269
Sam McCall8111d3b2017-12-13 08:48:42 +0000270 if (LangOpts)
271 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
272 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000273 }
274
275private:
276 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000277 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000278};
279
Ilya Biryukov04db3682017-07-21 13:29:29 +0000280} // namespace
281
Ilya Biryukov02d58702017-08-01 15:51:38 +0000282void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
283 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000284}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000285
Ilya Biryukov02d58702017-08-01 15:51:38 +0000286llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000287ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000288 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000289 std::unique_ptr<llvm::MemoryBuffer> Buffer,
290 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000291 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000292 std::vector<DiagWithFixIts> ASTDiags;
293 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
294
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000295 const PrecompiledPreamble *PreamblePCH =
296 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000297 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000298 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000299 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000300 if (!Clang)
301 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000302
303 // Recover resources if we crash before exiting this method.
304 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
305 Clang.get());
306
307 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000308 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
309 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000310 log("BeginSourceFile() failed when building AST for " +
311 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000312 return llvm::None;
313 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000314
315 InclusionLocations IncLocations;
316 // Copy over the includes from the preamble, then combine with the
317 // non-preamble includes below.
318 if (Preamble)
319 IncLocations = Preamble->IncLocations;
320
321 Clang->getPreprocessor().addPPCallbacks(
322 llvm::make_unique<InclusionLocationsCollector>(Clang->getSourceManager(),
323 IncLocations));
324
Ilya Biryukove5128f72017-09-20 07:24:15 +0000325 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000326 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000327
328 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
329 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000330 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000331
332 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000333 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000334 std::move(ParsedDecls), std::move(ASTDiags),
335 std::move(IncLocations));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000336}
337
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000338namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000339
340SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000341 const FileEntry *FE, Position Pos) {
342 SourceLocation InputLoc =
343 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
344 return Mgr.getMacroArgExpandedLocation(InputLoc);
345}
346
Ilya Biryukov02d58702017-08-01 15:51:38 +0000347} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000348
Ilya Biryukov02d58702017-08-01 15:51:38 +0000349void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000350 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000351 return;
352
353 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000354 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000355
356 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000357 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000358 // Resolve the declaration ID to an actual declaration, possibly
359 // deserializing the declaration in the process.
360 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
361 Resolved.push_back(D);
362 }
363
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000364 TopLevelDecls.reserve(TopLevelDecls.size() +
365 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000366 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
367
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000368 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000369}
370
Ilya Biryukov02d58702017-08-01 15:51:38 +0000371ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000372
Ilya Biryukov02d58702017-08-01 15:51:38 +0000373ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000374
Ilya Biryukov02d58702017-08-01 15:51:38 +0000375ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000376 if (Action) {
377 Action->EndSourceFile();
378 }
379}
380
Ilya Biryukov02d58702017-08-01 15:51:38 +0000381ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
382
383const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000384 return Clang->getASTContext();
385}
386
Ilya Biryukov02d58702017-08-01 15:51:38 +0000387Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000388
Eric Liu76f6b442018-01-09 17:32:00 +0000389std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
390 return Clang->getPreprocessorPtr();
391}
392
Ilya Biryukov02d58702017-08-01 15:51:38 +0000393const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000394 return Clang->getPreprocessor();
395}
396
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000398 ensurePreambleDeclsDeserialized();
399 return TopLevelDecls;
400}
401
Ilya Biryukov02d58702017-08-01 15:51:38 +0000402const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000403 return Diags;
404}
405
Ilya Biryukovdf842342018-01-25 14:32:21 +0000406std::size_t ParsedAST::getUsedBytes() const {
407 auto &AST = getASTContext();
408 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
409 // SmallVector<FixIt> inside each Diag.
410 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
411 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
412}
413
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000414const InclusionLocations &ParsedAST::getInclusionLocations() const {
415 return IncLocations;
416}
417
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000418PreambleData::PreambleData(PrecompiledPreamble Preamble,
419 std::vector<serialization::DeclID> TopLevelDeclIDs,
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000420 std::vector<DiagWithFixIts> Diags,
421 InclusionLocations IncLocations)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000422 : Preamble(std::move(Preamble)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000423 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)),
424 IncLocations(std::move(IncLocations)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000425
426ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
427 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000428 std::unique_ptr<FrontendAction> Action,
429 std::vector<const Decl *> TopLevelDecls,
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000430 std::vector<DiagWithFixIts> Diags,
431 InclusionLocations IncLocations)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000432 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
433 Action(std::move(Action)), Diags(std::move(Diags)),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000434 TopLevelDecls(std::move(TopLevelDecls)), PreambleDeclsDeserialized(false),
435 IncLocations(std::move(IncLocations)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000436 assert(this->Clang);
437 assert(this->Action);
438}
439
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000440CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000441 std::shared_ptr<PCHContainerOperations> PCHs,
442 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000443 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000444 PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000445 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000446}
447
448llvm::Optional<std::vector<DiagWithFixIts>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000449CppFile::rebuild(ParseInputs &&Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000450 log("Rebuilding file " + FileName + " with command [" +
451 Inputs.CompileCommand.Directory + "] " +
452 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000453
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000454 std::vector<const char *> ArgStrs;
455 for (const auto &S : Inputs.CompileCommand.CommandLine)
456 ArgStrs.push_back(S.c_str());
457
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000458 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
459 log("Couldn't set working directory");
460 // We run parsing anyway, our lit-tests rely on results for non-existing
461 // working dirs.
462 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000463
464 // Prepare CompilerInvocation.
465 std::unique_ptr<CompilerInvocation> CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000466 {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000467 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
468 // reporting them.
469 IgnoreDiagnostics IgnoreDiagnostics;
470 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
471 CompilerInstance::createDiagnostics(new DiagnosticOptions,
472 &IgnoreDiagnostics, false);
473 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
474 Inputs.FS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000475 if (!CI) {
476 log("Could not build CompilerInvocation for file " + FileName);
477 AST = llvm::None;
478 Preamble = nullptr;
479 return llvm::None;
480 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000481 // createInvocationFromCommandLine sets DisableFree.
482 CI->getFrontendOpts().DisableFree = false;
483 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000484
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000485 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
486 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000487
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000488 // Compute updated Preamble.
489 std::shared_ptr<const PreambleData> NewPreamble =
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000490 rebuildPreamble(*CI, Inputs.CompileCommand, Inputs.FS, *ContentsBuffer);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000491
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000492 // Remove current AST to avoid wasting memory.
493 AST = llvm::None;
494 // Compute updated AST.
495 llvm::Optional<ParsedAST> NewAST;
496 {
497 trace::Span Tracer("Build");
498 SPAN_ATTACH(Tracer, "File", FileName);
499 NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
500 std::move(ContentsBuffer), PCHs, Inputs.FS);
501 }
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000502
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000503 std::vector<DiagWithFixIts> Diagnostics;
504 if (NewAST) {
505 // Collect diagnostics from both the preamble and the AST.
506 if (NewPreamble)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000507 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
508 NewPreamble->Diags.end());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000509 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
510 NewAST->getDiagnostics().end());
511 }
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000512 if (ASTCallback && NewAST) {
513 trace::Span Tracer("Running ASTCallback");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000514 ASTCallback(FileName, NewAST.getPointer());
Ilya Biryukovbdbf49a2018-02-15 16:24:34 +0000515 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000516
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000517 // Write the results of rebuild into class fields.
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000518 Command = std::move(Inputs.CompileCommand);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000519 Preamble = std::move(NewPreamble);
520 AST = std::move(NewAST);
521 return Diagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000522}
523
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000524const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
525 return Preamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000526}
527
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000528ParsedAST *CppFile::getAST() const {
529 // We could add mutable to AST instead of const_cast here, but that would also
530 // allow writing to AST from const methods.
531 return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000532}
533
Ilya Biryukovdf842342018-01-25 14:32:21 +0000534std::size_t CppFile::getUsedBytes() const {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000535 std::size_t Total = 0;
536 if (AST)
537 Total += AST->getUsedBytes();
538 if (StorePreamblesInMemory && Preamble)
539 Total += Preamble->Preamble.getSize();
540 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000541}
542
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000543std::shared_ptr<const PreambleData>
544CppFile::rebuildPreamble(CompilerInvocation &CI,
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000545 const tooling::CompileCommand &Command,
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000546 IntrusiveRefCntPtr<vfs::FileSystem> FS,
547 llvm::MemoryBuffer &ContentsBuffer) const {
548 const auto &OldPreamble = this->Preamble;
549 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
Ilya Biryukov7fac6e92018-02-19 18:18:49 +0000550 if (OldPreamble && compileCommandsAreEqual(this->Command, Command) &&
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000551 OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
552 log("Reusing preamble for file " + Twine(FileName));
553 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000554 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000555 log("Preamble for file " + Twine(FileName) +
556 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000557
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000558 trace::Span Tracer("Preamble");
559 SPAN_ATTACH(Tracer, "File", FileName);
560 std::vector<DiagWithFixIts> PreambleDiags;
561 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
562 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
563 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
564 &PreambleDiagnosticsConsumer, false);
565
566 // Skip function bodies when building the preamble to speed up building
567 // the preamble and make it smaller.
568 assert(!CI.getFrontendOpts().SkipFunctionBodies);
569 CI.getFrontendOpts().SkipFunctionBodies = true;
570
571 CppFilePreambleCallbacks SerializedDeclsCollector;
572 auto BuiltPreamble = PrecompiledPreamble::Build(
573 CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
574 /*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
575
576 // When building the AST for the main file, we do want the function
577 // bodies.
578 CI.getFrontendOpts().SkipFunctionBodies = false;
579
580 if (BuiltPreamble) {
581 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
582 " for file " + Twine(FileName));
583
584 return std::make_shared<PreambleData>(
585 std::move(*BuiltPreamble),
586 SerializedDeclsCollector.takeTopLevelDeclIDs(),
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000587 std::move(PreambleDiags),
588 SerializedDeclsCollector.takeInclusionLocations());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000589 } else {
590 log("Could not build a preamble for file " + Twine(FileName));
591 return nullptr;
592 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000593}
Haojian Wu345099c2017-11-09 11:30:04 +0000594
595SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
596 const Position &Pos,
597 const FileEntry *FE) {
598 // The language server protocol uses zero-based line and column numbers.
599 // Clang uses one-based numbers.
600
601 const ASTContext &AST = Unit.getASTContext();
602 const SourceManager &SourceMgr = AST.getSourceManager();
603
604 SourceLocation InputLocation =
605 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
606 if (Pos.character == 0) {
607 return InputLocation;
608 }
609
610 // This handle cases where the position is in the middle of a token or right
611 // after the end of a token. In theory we could just use GetBeginningOfToken
612 // to find the start of the token at the input position, but this doesn't
613 // work when right after the end, i.e. foo|.
Benjamin Kramer5eb6a282018-02-06 20:08:23 +0000614 // So try to go back by one and see if we're still inside an identifier
Haojian Wu345099c2017-11-09 11:30:04 +0000615 // token. If so, Take the beginning of this token.
616 // (It should be the same identifier because you can't have two adjacent
617 // identifiers without another token in between.)
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000618 Position PosCharBehind = Pos;
619 --PosCharBehind.character;
620
621 SourceLocation PeekBeforeLocation =
622 getMacroArgExpandedLocation(SourceMgr, FE, PosCharBehind);
Haojian Wu345099c2017-11-09 11:30:04 +0000623 Token Result;
624 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
625 AST.getLangOpts(), false)) {
626 // getRawToken failed, just use InputLocation.
627 return InputLocation;
628 }
629
630 if (Result.is(tok::raw_identifier)) {
631 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
632 AST.getLangOpts());
633 }
634
635 return InputLocation;
636}