blob: cd4104c871f40fe917dbd6843e9504eff99d9d8a [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:
Sam McCalld9b54f02018-06-05 16:30:25 +000054 DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
Ilya Biryukov04db3682017-07-21 13:29:29 +000055 : TopLevelDecls(TopLevelDecls) {}
56
57 bool HandleTopLevelDecl(DeclGroupRef DG) override {
Sam McCalld9b54f02018-06-05 16:30:25 +000058 for (Decl *D : DG) {
Ilya Biryukov04db3682017-07-21 13:29:29 +000059 // 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:
Sam McCalld9b54f02018-06-05 16:30:25 +000069 std::vector<Decl *> &TopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +000070};
71
72class ClangdFrontendAction : public SyntaxOnlyAction {
73public:
Sam McCalld9b54f02018-06-05 16:30:25 +000074 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Ilya Biryukov04db3682017-07-21 13:29:29 +000075
76protected:
77 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
78 StringRef InFile) override {
79 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
80 }
81
82private:
Sam McCalld9b54f02018-06-05 16:30:25 +000083 std::vector<Decl *> TopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +000084};
85
Ilya Biryukov02d58702017-08-01 15:51:38 +000086class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000087public:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000088 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
89 : File(File), ParsedCallback(ParsedCallback) {}
90
Eric Liu155f5a42018-05-14 12:19:16 +000091 std::vector<Inclusion> takeInclusions() { return std::move(Inclusions); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000092
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000093 void AfterExecute(CompilerInstance &CI) override {
94 if (!ParsedCallback)
95 return;
96 trace::Span Tracer("Running PreambleCallback");
97 ParsedCallback(File, CI.getASTContext(), CI.getPreprocessorPtr());
98 }
99
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000100 void BeforeExecute(CompilerInstance &CI) override {
101 SourceMgr = &CI.getSourceManager();
102 }
103
104 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
105 assert(SourceMgr && "SourceMgr must be set at this point");
Eric Liu155f5a42018-05-14 12:19:16 +0000106 return collectInclusionsInMainFileCallback(
107 *SourceMgr,
108 [this](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); });
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000109 }
110
Ilya Biryukov04db3682017-07-21 13:29:29 +0000111private:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000112 PathRef File;
113 PreambleParsedCallback ParsedCallback;
Eric Liu155f5a42018-05-14 12:19:16 +0000114 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000115 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000116};
117
Ilya Biryukov04db3682017-07-21 13:29:29 +0000118} // namespace
119
Ilya Biryukov02d58702017-08-01 15:51:38 +0000120void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
121 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000122}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000123
Ilya Biryukov02d58702017-08-01 15:51:38 +0000124llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000125ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000126 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000127 std::unique_ptr<llvm::MemoryBuffer> Buffer,
128 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000129 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000130 assert(CI);
131 // Command-line parsing sets DisableFree to true by default, but we don't want
132 // to leak memory in clangd.
133 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000134 const PrecompiledPreamble *PreamblePCH =
135 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000136
137 StoreDiags ASTDiags;
138 auto Clang =
139 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
140 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000141 if (!Clang)
142 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000143
144 // Recover resources if we crash before exiting this method.
145 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
146 Clang.get());
147
148 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000149 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
150 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000151 log("BeginSourceFile() failed when building AST for " +
152 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000153 return llvm::None;
154 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000155
Eric Liu155f5a42018-05-14 12:19:16 +0000156 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000157 // Copy over the includes from the preamble, then combine with the
158 // non-preamble includes below.
159 if (Preamble)
Eric Liu155f5a42018-05-14 12:19:16 +0000160 Inclusions = Preamble->Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000161
Eric Liu155f5a42018-05-14 12:19:16 +0000162 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
163 Clang->getSourceManager(),
164 [&Inclusions](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); }));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000165
Ilya Biryukove5128f72017-09-20 07:24:15 +0000166 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000167 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000168
169 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
170 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000171 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000172 // CompilerInstance won't run this callback, do it directly.
173 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000174
Sam McCalld9b54f02018-06-05 16:30:25 +0000175 std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov823b0562018-06-01 10:08:43 +0000176 std::vector<Diag> Diags = ASTDiags.take();
177 // Add diagnostics from the preamble, if any.
178 if (Preamble)
179 Diags.insert(Diags.begin(), Preamble->Diags.begin(), Preamble->Diags.end());
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000180 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov823b0562018-06-01 10:08:43 +0000181 std::move(ParsedDecls), std::move(Diags),
Eric Liu155f5a42018-05-14 12:19:16 +0000182 std::move(Inclusions));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183}
184
Ilya Biryukov02d58702017-08-01 15:51:38 +0000185ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000186
Ilya Biryukov02d58702017-08-01 15:51:38 +0000187ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000188
Ilya Biryukov02d58702017-08-01 15:51:38 +0000189ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000190 if (Action) {
191 Action->EndSourceFile();
192 }
193}
194
Ilya Biryukov02d58702017-08-01 15:51:38 +0000195ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
196
197const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000198 return Clang->getASTContext();
199}
200
Ilya Biryukov02d58702017-08-01 15:51:38 +0000201Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000202
Eric Liu76f6b442018-01-09 17:32:00 +0000203std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
204 return Clang->getPreprocessorPtr();
205}
206
Ilya Biryukov02d58702017-08-01 15:51:38 +0000207const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000208 return Clang->getPreprocessor();
209}
210
Sam McCalld9b54f02018-06-05 16:30:25 +0000211ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000212 return LocalTopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000213}
214
Ilya Biryukov71028b82018-03-12 15:28:22 +0000215const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000216
Ilya Biryukovdf842342018-01-25 14:32:21 +0000217std::size_t ParsedAST::getUsedBytes() const {
218 auto &AST = getASTContext();
219 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000220 // Message and Fixes inside each diagnostic.
Ilya Biryukov0da27c72018-06-01 14:44:57 +0000221 std::size_t Total =
222 ::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
223
224 // FIXME: the rest of the function is almost a direct copy-paste from
225 // libclang's clang_getCXTUResourceUsage. We could share the implementation.
226
227 // Sum up variaous allocators inside the ast context and the preprocessor.
228 Total += AST.getASTAllocatedMemory();
229 Total += AST.getSideTableAllocatedMemory();
230 Total += AST.Idents.getAllocator().getTotalMemory();
231 Total += AST.Selectors.getTotalMemory();
232
233 Total += AST.getSourceManager().getContentCacheSize();
234 Total += AST.getSourceManager().getDataStructureSizes();
235 Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
236
237 if (ExternalASTSource *Ext = AST.getExternalSource())
238 Total += Ext->getMemoryBufferSizes().malloc_bytes;
239
240 const Preprocessor &PP = getPreprocessor();
241 Total += PP.getTotalMemory();
242 if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
243 Total += PRec->getTotalMemory();
244 Total += PP.getHeaderSearchInfo().getTotalMemory();
245
246 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000247}
248
Eric Liu155f5a42018-05-14 12:19:16 +0000249const std::vector<Inclusion> &ParsedAST::getInclusions() const {
250 return Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000251}
252
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000253PreambleData::PreambleData(PrecompiledPreamble Preamble,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000254 std::vector<Diag> Diags,
Eric Liu155f5a42018-05-14 12:19:16 +0000255 std::vector<Inclusion> Inclusions)
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000256 : Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Eric Liu155f5a42018-05-14 12:19:16 +0000257 Inclusions(std::move(Inclusions)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000258
259ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
260 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000261 std::unique_ptr<FrontendAction> Action,
Sam McCalld9b54f02018-06-05 16:30:25 +0000262 std::vector<Decl *> LocalTopLevelDecls,
Eric Liu155f5a42018-05-14 12:19:16 +0000263 std::vector<Diag> Diags, std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000264 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
265 Action(std::move(Action)), Diags(std::move(Diags)),
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000266 LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
Eric Liu155f5a42018-05-14 12:19:16 +0000267 Inclusions(std::move(Inclusions)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000268 assert(this->Clang);
269 assert(this->Action);
270}
271
Ilya Biryukov823b0562018-06-01 10:08:43 +0000272std::unique_ptr<CompilerInvocation>
273clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000274 std::vector<const char *> ArgStrs;
275 for (const auto &S : Inputs.CompileCommand.CommandLine)
276 ArgStrs.push_back(S.c_str());
277
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000278 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Ilya Biryukov823b0562018-06-01 10:08:43 +0000279 log("Couldn't set working directory when creating compiler invocation.");
280 // We proceed anyway, our lit-tests rely on results for non-existing working
281 // dirs.
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000282 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000283
Ilya Biryukov823b0562018-06-01 10:08:43 +0000284 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
285 // reporting them.
286 IgnoreDiagnostics IgnoreDiagnostics;
287 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
288 CompilerInstance::createDiagnostics(new DiagnosticOptions,
289 &IgnoreDiagnostics, false);
290 std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
291 ArgStrs, CommandLineDiagsEngine, Inputs.FS);
292 if (!CI)
293 return nullptr;
294 // createInvocationFromCommandLine sets DisableFree.
295 CI->getFrontendOpts().DisableFree = false;
296 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
297 return CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000298}
299
Ilya Biryukov823b0562018-06-01 10:08:43 +0000300std::shared_ptr<const PreambleData> clangd::buildPreamble(
301 PathRef FileName, CompilerInvocation &CI,
302 std::shared_ptr<const PreambleData> OldPreamble,
303 const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
304 std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
305 PreambleParsedCallback PreambleCallback) {
306 // Note that we don't need to copy the input contents, preamble can live
307 // without those.
308 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
309 auto Bounds =
310 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000311
Ilya Biryukov823b0562018-06-01 10:08:43 +0000312 if (OldPreamble &&
313 compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
314 OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
315 Inputs.FS.get())) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000316 log("Reusing preamble for file " + Twine(FileName));
317 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000318 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000319 log("Preamble for file " + Twine(FileName) +
320 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000321
Ilya Biryukov823b0562018-06-01 10:08:43 +0000322 trace::Span Tracer("BuildPreamble");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000323 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000324 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000325 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
326 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000327 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000328
329 // Skip function bodies when building the preamble to speed up building
330 // the preamble and make it smaller.
331 assert(!CI.getFrontendOpts().SkipFunctionBodies);
332 CI.getFrontendOpts().SkipFunctionBodies = true;
333
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000334 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Ilya Biryukov823b0562018-06-01 10:08:43 +0000335 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
336 log("Couldn't set working directory when building the preamble.");
337 // We proceed anyway, our lit-tests rely on results for non-existing working
338 // dirs.
339 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000340 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov823b0562018-06-01 10:08:43 +0000341 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS, PCHs,
342 StoreInMemory, SerializedDeclsCollector);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000343
344 // When building the AST for the main file, we do want the function
345 // bodies.
346 CI.getFrontendOpts().SkipFunctionBodies = false;
347
348 if (BuiltPreamble) {
349 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
350 " for file " + Twine(FileName));
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000351 return std::make_shared<PreambleData>(
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000352 std::move(*BuiltPreamble), PreambleDiagnostics.take(),
353 SerializedDeclsCollector.takeInclusions());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000354 } else {
355 log("Could not build a preamble for file " + Twine(FileName));
356 return nullptr;
357 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000358}
Haojian Wu345099c2017-11-09 11:30:04 +0000359
Ilya Biryukov823b0562018-06-01 10:08:43 +0000360llvm::Optional<ParsedAST> clangd::buildAST(
361 PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
362 const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
363 std::shared_ptr<PCHContainerOperations> PCHs) {
364 trace::Span Tracer("BuildAST");
365 SPAN_ATTACH(Tracer, "File", FileName);
366
367 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
368 log("Couldn't set working directory when building the preamble.");
369 // We proceed anyway, our lit-tests rely on results for non-existing working
370 // dirs.
371 }
372
373 return ParsedAST::Build(
374 llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
375 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
376}
377
Haojian Wu345099c2017-11-09 11:30:04 +0000378SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
379 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000380 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000381 const ASTContext &AST = Unit.getASTContext();
382 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000383 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
384 if (!Offset) {
385 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
386 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000387 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000388 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000389
Sam McCalla4962cc2018-04-27 11:59:28 +0000390 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
391 // if the cursor is at the end of the identifier.
392 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
393 // 1) at the beginning of an identifier, we'll be looking at something
394 // that isn't an identifier.
395 // 2) at the middle or end of an identifier, we get the identifier.
396 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
397 // We can't actually distinguish cases 1 and 3, but returning the original
398 // location is correct for both!
399 if (*Offset == 0) // Case 1 or 3.
400 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
401 SourceLocation Before =
402 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
403 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
404 Token Tok;
405 if (Before.isValid() &&
406 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
407 Tok.is(tok::raw_identifier))
408 return Before; // Case 2.
409 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000410}