blob: 86e7497a3bf5946d040812926d653a491a9b8487 [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 Biryukov6f33b332018-07-09 11:33:31 +000027#include "clang/Lex/PreprocessorOptions.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000028#include "clang/Sema/Sema.h"
29#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000030#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000031#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/Support/CrashRecoveryContext.h"
Ilya Biryukovd14dc492018-02-01 19:06:45 +000034#include "llvm/Support/raw_ostream.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000035#include <algorithm>
36
Ilya Biryukov38d79772017-05-16 09:38:59 +000037using namespace clang::clangd;
38using namespace clang;
39
Ilya Biryukov04db3682017-07-21 13:29:29 +000040namespace {
41
Ilya Biryukov7fac6e92018-02-19 18:18:49 +000042bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
43 const tooling::CompileCommand &RHS) {
44 // We don't check for Output, it should not matter to clangd.
45 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
46 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
47}
48
Ilya Biryukovdf842342018-01-25 14:32:21 +000049template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
50 return Vec.capacity() * sizeof(T);
51}
52
Ilya Biryukov04db3682017-07-21 13:29:29 +000053class DeclTrackingASTConsumer : public ASTConsumer {
54public:
Sam McCalld9b54f02018-06-05 16:30:25 +000055 DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
Ilya Biryukov04db3682017-07-21 13:29:29 +000056 : TopLevelDecls(TopLevelDecls) {}
57
58 bool HandleTopLevelDecl(DeclGroupRef DG) override {
Sam McCalld9b54f02018-06-05 16:30:25 +000059 for (Decl *D : DG) {
Ilya Biryukov04db3682017-07-21 13:29:29 +000060 // ObjCMethodDecl are not actually top-level decls.
61 if (isa<ObjCMethodDecl>(D))
62 continue;
63
64 TopLevelDecls.push_back(D);
65 }
66 return true;
67 }
68
69private:
Sam McCalld9b54f02018-06-05 16:30:25 +000070 std::vector<Decl *> &TopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +000071};
72
73class ClangdFrontendAction : public SyntaxOnlyAction {
74public:
Sam McCalld9b54f02018-06-05 16:30:25 +000075 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Ilya Biryukov04db3682017-07-21 13:29:29 +000076
77protected:
78 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
79 StringRef InFile) override {
80 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
81 }
82
83private:
Sam McCalld9b54f02018-06-05 16:30:25 +000084 std::vector<Decl *> TopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +000085};
86
Ilya Biryukov02d58702017-08-01 15:51:38 +000087class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000088public:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000089 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
90 : File(File), ParsedCallback(ParsedCallback) {}
91
Sam McCall3f0243f2018-07-03 08:09:29 +000092 IncludeStructure takeIncludes() { return std::move(Includes); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000093
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000094 void AfterExecute(CompilerInstance &CI) override {
95 if (!ParsedCallback)
96 return;
97 trace::Span Tracer("Running PreambleCallback");
98 ParsedCallback(File, CI.getASTContext(), CI.getPreprocessorPtr());
99 }
100
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000101 void BeforeExecute(CompilerInstance &CI) override {
102 SourceMgr = &CI.getSourceManager();
103 }
104
105 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
106 assert(SourceMgr && "SourceMgr must be set at this point");
Sam McCall3f0243f2018-07-03 08:09:29 +0000107 return collectIncludeStructureCallback(*SourceMgr, &Includes);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000108 }
109
Ilya Biryukov04db3682017-07-21 13:29:29 +0000110private:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000111 PathRef File;
112 PreambleParsedCallback ParsedCallback;
Sam McCall3f0243f2018-07-03 08:09:29 +0000113 IncludeStructure Includes;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000114 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000115};
116
Ilya Biryukov04db3682017-07-21 13:29:29 +0000117} // namespace
118
Ilya Biryukov02d58702017-08-01 15:51:38 +0000119void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
120 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000121}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000122
Ilya Biryukov02d58702017-08-01 15:51:38 +0000123llvm::Optional<ParsedAST>
Ilya Biryukov74f26552018-07-26 12:05:31 +0000124ParsedAST::build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000125 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000126 std::unique_ptr<llvm::MemoryBuffer> Buffer,
127 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000128 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000129 assert(CI);
130 // Command-line parsing sets DisableFree to true by default, but we don't want
131 // to leak memory in clangd.
132 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000133 const PrecompiledPreamble *PreamblePCH =
134 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000135
136 StoreDiags ASTDiags;
137 auto Clang =
138 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
139 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000140 if (!Clang)
141 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000142
143 // Recover resources if we crash before exiting this method.
144 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
145 Clang.get());
146
147 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000148 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
149 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCallbed58852018-07-11 10:35:11 +0000150 log("BeginSourceFile() failed when building AST for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +0000151 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000152 return llvm::None;
153 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000154
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000155 // Copy over the includes from the preamble, then combine with the
156 // non-preamble includes below.
Sam McCall3f0243f2018-07-03 08:09:29 +0000157 auto Includes = Preamble ? Preamble->Includes : IncludeStructure{};
158 Clang->getPreprocessor().addPPCallbacks(
159 collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000160
Ilya Biryukove5128f72017-09-20 07:24:15 +0000161 if (!Action->Execute())
Sam McCallbed58852018-07-11 10:35:11 +0000162 log("Execute() failed when building AST for {0}", MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000163
164 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
165 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000166 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000167 // CompilerInstance won't run this callback, do it directly.
168 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000169
Sam McCalld9b54f02018-06-05 16:30:25 +0000170 std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov823b0562018-06-01 10:08:43 +0000171 std::vector<Diag> Diags = ASTDiags.take();
172 // Add diagnostics from the preamble, if any.
173 if (Preamble)
174 Diags.insert(Diags.begin(), Preamble->Diags.begin(), Preamble->Diags.end());
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000175 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov823b0562018-06-01 10:08:43 +0000176 std::move(ParsedDecls), std::move(Diags),
Sam McCall3f0243f2018-07-03 08:09:29 +0000177 std::move(Includes));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000178}
179
Ilya Biryukov02d58702017-08-01 15:51:38 +0000180ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000181
Ilya Biryukov02d58702017-08-01 15:51:38 +0000182ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183
Ilya Biryukov02d58702017-08-01 15:51:38 +0000184ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000185 if (Action) {
186 Action->EndSourceFile();
187 }
188}
189
Ilya Biryukov02d58702017-08-01 15:51:38 +0000190ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
191
192const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000193 return Clang->getASTContext();
194}
195
Ilya Biryukov02d58702017-08-01 15:51:38 +0000196Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000197
Eric Liu76f6b442018-01-09 17:32:00 +0000198std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
199 return Clang->getPreprocessorPtr();
200}
201
Ilya Biryukov02d58702017-08-01 15:51:38 +0000202const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000203 return Clang->getPreprocessor();
204}
205
Sam McCalld9b54f02018-06-05 16:30:25 +0000206ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000207 return LocalTopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000208}
209
Ilya Biryukov71028b82018-03-12 15:28:22 +0000210const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000211
Ilya Biryukovdf842342018-01-25 14:32:21 +0000212std::size_t ParsedAST::getUsedBytes() const {
213 auto &AST = getASTContext();
214 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000215 // Message and Fixes inside each diagnostic.
Ilya Biryukov0da27c72018-06-01 14:44:57 +0000216 std::size_t Total =
217 ::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
218
219 // FIXME: the rest of the function is almost a direct copy-paste from
220 // libclang's clang_getCXTUResourceUsage. We could share the implementation.
221
222 // Sum up variaous allocators inside the ast context and the preprocessor.
223 Total += AST.getASTAllocatedMemory();
224 Total += AST.getSideTableAllocatedMemory();
225 Total += AST.Idents.getAllocator().getTotalMemory();
226 Total += AST.Selectors.getTotalMemory();
227
228 Total += AST.getSourceManager().getContentCacheSize();
229 Total += AST.getSourceManager().getDataStructureSizes();
230 Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
231
232 if (ExternalASTSource *Ext = AST.getExternalSource())
233 Total += Ext->getMemoryBufferSizes().malloc_bytes;
234
235 const Preprocessor &PP = getPreprocessor();
236 Total += PP.getTotalMemory();
237 if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
238 Total += PRec->getTotalMemory();
239 Total += PP.getHeaderSearchInfo().getTotalMemory();
240
241 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000242}
243
Sam McCall3f0243f2018-07-03 08:09:29 +0000244const IncludeStructure &ParsedAST::getIncludeStructure() const {
245 return Includes;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000246}
247
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000248PreambleData::PreambleData(PrecompiledPreamble Preamble,
Sam McCall3f0243f2018-07-03 08:09:29 +0000249 std::vector<Diag> Diags, IncludeStructure Includes)
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000250 : Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Sam McCall3f0243f2018-07-03 08:09:29 +0000251 Includes(std::move(Includes)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000252
253ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
254 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000255 std::unique_ptr<FrontendAction> Action,
Sam McCalld9b54f02018-06-05 16:30:25 +0000256 std::vector<Decl *> LocalTopLevelDecls,
Sam McCall3f0243f2018-07-03 08:09:29 +0000257 std::vector<Diag> Diags, IncludeStructure Includes)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000258 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
259 Action(std::move(Action)), Diags(std::move(Diags)),
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000260 LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
Sam McCall3f0243f2018-07-03 08:09:29 +0000261 Includes(std::move(Includes)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000262 assert(this->Clang);
263 assert(this->Action);
264}
265
Ilya Biryukov823b0562018-06-01 10:08:43 +0000266std::unique_ptr<CompilerInvocation>
267clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000268 std::vector<const char *> ArgStrs;
269 for (const auto &S : Inputs.CompileCommand.CommandLine)
270 ArgStrs.push_back(S.c_str());
271
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000272 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Ilya Biryukov823b0562018-06-01 10:08:43 +0000273 log("Couldn't set working directory when creating compiler invocation.");
274 // We proceed anyway, our lit-tests rely on results for non-existing working
275 // dirs.
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000276 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000277
Ilya Biryukov823b0562018-06-01 10:08:43 +0000278 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
279 // reporting them.
280 IgnoreDiagnostics IgnoreDiagnostics;
281 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
282 CompilerInstance::createDiagnostics(new DiagnosticOptions,
283 &IgnoreDiagnostics, false);
284 std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
285 ArgStrs, CommandLineDiagsEngine, Inputs.FS);
286 if (!CI)
287 return nullptr;
288 // createInvocationFromCommandLine sets DisableFree.
289 CI->getFrontendOpts().DisableFree = false;
290 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
291 return CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000292}
293
Ilya Biryukov823b0562018-06-01 10:08:43 +0000294std::shared_ptr<const PreambleData> clangd::buildPreamble(
295 PathRef FileName, CompilerInvocation &CI,
296 std::shared_ptr<const PreambleData> OldPreamble,
297 const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
298 std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
299 PreambleParsedCallback PreambleCallback) {
300 // Note that we don't need to copy the input contents, preamble can live
301 // without those.
302 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
303 auto Bounds =
304 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000305
Ilya Biryukov823b0562018-06-01 10:08:43 +0000306 if (OldPreamble &&
307 compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
308 OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
309 Inputs.FS.get())) {
Sam McCallbed58852018-07-11 10:35:11 +0000310 vlog("Reusing preamble for file {0}", Twine(FileName));
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000311 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000312 }
Sam McCallbed58852018-07-11 10:35:11 +0000313 vlog("Preamble for file {0} cannot be reused. Attempting to rebuild it.",
314 FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000315
Ilya Biryukov823b0562018-06-01 10:08:43 +0000316 trace::Span Tracer("BuildPreamble");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000317 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000318 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000319 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
320 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000321 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000322
323 // Skip function bodies when building the preamble to speed up building
324 // the preamble and make it smaller.
325 assert(!CI.getFrontendOpts().SkipFunctionBodies);
326 CI.getFrontendOpts().SkipFunctionBodies = true;
Ilya Biryukov6f33b332018-07-09 11:33:31 +0000327 // We don't want to write comment locations into PCH. They are racy and slow
328 // to read back. We rely on dynamic index for the comments instead.
329 CI.getPreprocessorOpts().WriteCommentListToPCH = false;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000330
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000331 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Ilya Biryukov823b0562018-06-01 10:08:43 +0000332 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
333 log("Couldn't set working directory when building the preamble.");
334 // We proceed anyway, our lit-tests rely on results for non-existing working
335 // dirs.
336 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000337 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov823b0562018-06-01 10:08:43 +0000338 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS, PCHs,
339 StoreInMemory, SerializedDeclsCollector);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000340
341 // When building the AST for the main file, we do want the function
342 // bodies.
343 CI.getFrontendOpts().SkipFunctionBodies = false;
344
345 if (BuiltPreamble) {
Sam McCallbed58852018-07-11 10:35:11 +0000346 vlog("Built preamble of size {0} for file {1}", BuiltPreamble->getSize(),
347 FileName);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000348 return std::make_shared<PreambleData>(
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000349 std::move(*BuiltPreamble), PreambleDiagnostics.take(),
Sam McCall3f0243f2018-07-03 08:09:29 +0000350 SerializedDeclsCollector.takeIncludes());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000351 } else {
Sam McCallbed58852018-07-11 10:35:11 +0000352 elog("Could not build a preamble for file {0}", FileName);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000353 return nullptr;
354 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355}
Haojian Wu345099c2017-11-09 11:30:04 +0000356
Ilya Biryukov823b0562018-06-01 10:08:43 +0000357llvm::Optional<ParsedAST> clangd::buildAST(
358 PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
359 const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
360 std::shared_ptr<PCHContainerOperations> PCHs) {
361 trace::Span Tracer("BuildAST");
362 SPAN_ATTACH(Tracer, "File", FileName);
363
364 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
365 log("Couldn't set working directory when building the preamble.");
366 // We proceed anyway, our lit-tests rely on results for non-existing working
367 // dirs.
368 }
369
Ilya Biryukov74f26552018-07-26 12:05:31 +0000370 return ParsedAST::build(
Ilya Biryukov823b0562018-06-01 10:08:43 +0000371 llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
372 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
373}
374
Haojian Wu345099c2017-11-09 11:30:04 +0000375SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
376 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000377 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000378 const ASTContext &AST = Unit.getASTContext();
379 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000380 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
381 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +0000382 log("getBeginningOfIdentifier: {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +0000383 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000384 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000385 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000386
Sam McCalla4962cc2018-04-27 11:59:28 +0000387 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
388 // if the cursor is at the end of the identifier.
389 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
390 // 1) at the beginning of an identifier, we'll be looking at something
391 // that isn't an identifier.
392 // 2) at the middle or end of an identifier, we get the identifier.
393 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
394 // We can't actually distinguish cases 1 and 3, but returning the original
395 // location is correct for both!
396 if (*Offset == 0) // Case 1 or 3.
397 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
398 SourceLocation Before =
399 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
400 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
401 Token Tok;
402 if (Before.isValid() &&
403 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
404 Tok.is(tok::raw_identifier))
405 return Before; // Case 2.
406 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000407}