blob: bf5de6ac34e17f6da6ad97be3a5e69f5e7028263 [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:
54 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
55 : TopLevelDecls(TopLevelDecls) {}
56
57 bool HandleTopLevelDecl(DeclGroupRef DG) override {
58 for (const Decl *D : DG) {
59 // 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:
69 std::vector<const Decl *> &TopLevelDecls;
70};
71
72class ClangdFrontendAction : public SyntaxOnlyAction {
73public:
74 std::vector<const Decl *> takeTopLevelDecls() {
75 return std::move(TopLevelDecls);
76 }
77
78protected:
79 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
80 StringRef InFile) override {
81 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
82 }
83
84private:
85 std::vector<const Decl *> TopLevelDecls;
86};
87
Ilya Biryukov02d58702017-08-01 15:51:38 +000088class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000089public:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000090 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
91 : File(File), ParsedCallback(ParsedCallback) {}
92
Eric Liu155f5a42018-05-14 12:19:16 +000093 std::vector<Inclusion> takeInclusions() { return std::move(Inclusions); }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000094
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +000095 void AfterExecute(CompilerInstance &CI) override {
96 if (!ParsedCallback)
97 return;
98 trace::Span Tracer("Running PreambleCallback");
99 ParsedCallback(File, CI.getASTContext(), CI.getPreprocessorPtr());
100 }
101
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000102 void BeforeExecute(CompilerInstance &CI) override {
103 SourceMgr = &CI.getSourceManager();
104 }
105
106 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
107 assert(SourceMgr && "SourceMgr must be set at this point");
Eric Liu155f5a42018-05-14 12:19:16 +0000108 return collectInclusionsInMainFileCallback(
109 *SourceMgr,
110 [this](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); });
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000111 }
112
Ilya Biryukov04db3682017-07-21 13:29:29 +0000113private:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000114 PathRef File;
115 PreambleParsedCallback ParsedCallback;
Eric Liu155f5a42018-05-14 12:19:16 +0000116 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000117 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000118};
119
Ilya Biryukov04db3682017-07-21 13:29:29 +0000120} // namespace
121
Ilya Biryukov02d58702017-08-01 15:51:38 +0000122void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
123 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000124}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000125
Ilya Biryukov02d58702017-08-01 15:51:38 +0000126llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000127ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000128 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000129 std::unique_ptr<llvm::MemoryBuffer> Buffer,
130 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000131 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000132 assert(CI);
133 // Command-line parsing sets DisableFree to true by default, but we don't want
134 // to leak memory in clangd.
135 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000136 const PrecompiledPreamble *PreamblePCH =
137 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000138
139 StoreDiags ASTDiags;
140 auto Clang =
141 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
142 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000143 if (!Clang)
144 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000145
146 // Recover resources if we crash before exiting this method.
147 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
148 Clang.get());
149
150 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000151 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
152 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000153 log("BeginSourceFile() failed when building AST for " +
154 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000155 return llvm::None;
156 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000157
Eric Liu155f5a42018-05-14 12:19:16 +0000158 std::vector<Inclusion> Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000159 // Copy over the includes from the preamble, then combine with the
160 // non-preamble includes below.
161 if (Preamble)
Eric Liu155f5a42018-05-14 12:19:16 +0000162 Inclusions = Preamble->Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000163
Eric Liu155f5a42018-05-14 12:19:16 +0000164 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
165 Clang->getSourceManager(),
166 [&Inclusions](Inclusion Inc) { Inclusions.push_back(std::move(Inc)); }));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000167
Ilya Biryukove5128f72017-09-20 07:24:15 +0000168 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000169 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000170
171 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
172 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000173 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000174 // CompilerInstance won't run this callback, do it directly.
175 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000176
177 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov823b0562018-06-01 10:08:43 +0000178 std::vector<Diag> Diags = ASTDiags.take();
179 // Add diagnostics from the preamble, if any.
180 if (Preamble)
181 Diags.insert(Diags.begin(), Preamble->Diags.begin(), Preamble->Diags.end());
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000182 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov823b0562018-06-01 10:08:43 +0000183 std::move(ParsedDecls), std::move(Diags),
Eric Liu155f5a42018-05-14 12:19:16 +0000184 std::move(Inclusions));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000185}
186
Ilya Biryukov02d58702017-08-01 15:51:38 +0000187ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000188
Ilya Biryukov02d58702017-08-01 15:51:38 +0000189ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000190
Ilya Biryukov02d58702017-08-01 15:51:38 +0000191ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000192 if (Action) {
193 Action->EndSourceFile();
194 }
195}
196
Ilya Biryukov02d58702017-08-01 15:51:38 +0000197ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
198
199const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000200 return Clang->getASTContext();
201}
202
Ilya Biryukov02d58702017-08-01 15:51:38 +0000203Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000204
Eric Liu76f6b442018-01-09 17:32:00 +0000205std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
206 return Clang->getPreprocessorPtr();
207}
208
Ilya Biryukov02d58702017-08-01 15:51:38 +0000209const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000210 return Clang->getPreprocessor();
211}
212
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000213ArrayRef<const Decl *> ParsedAST::getLocalTopLevelDecls() {
214 return LocalTopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000215}
216
Ilya Biryukov71028b82018-03-12 15:28:22 +0000217const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000218
Ilya Biryukovdf842342018-01-25 14:32:21 +0000219std::size_t ParsedAST::getUsedBytes() const {
220 auto &AST = getASTContext();
221 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000222 // Message and Fixes inside each diagnostic.
Ilya Biryukov0da27c72018-06-01 14:44:57 +0000223 std::size_t Total =
224 ::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
225
226 // FIXME: the rest of the function is almost a direct copy-paste from
227 // libclang's clang_getCXTUResourceUsage. We could share the implementation.
228
229 // Sum up variaous allocators inside the ast context and the preprocessor.
230 Total += AST.getASTAllocatedMemory();
231 Total += AST.getSideTableAllocatedMemory();
232 Total += AST.Idents.getAllocator().getTotalMemory();
233 Total += AST.Selectors.getTotalMemory();
234
235 Total += AST.getSourceManager().getContentCacheSize();
236 Total += AST.getSourceManager().getDataStructureSizes();
237 Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
238
239 if (ExternalASTSource *Ext = AST.getExternalSource())
240 Total += Ext->getMemoryBufferSizes().malloc_bytes;
241
242 const Preprocessor &PP = getPreprocessor();
243 Total += PP.getTotalMemory();
244 if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
245 Total += PRec->getTotalMemory();
246 Total += PP.getHeaderSearchInfo().getTotalMemory();
247
248 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000249}
250
Eric Liu155f5a42018-05-14 12:19:16 +0000251const std::vector<Inclusion> &ParsedAST::getInclusions() const {
252 return Inclusions;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000253}
254
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000255PreambleData::PreambleData(PrecompiledPreamble Preamble,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000256 std::vector<Diag> Diags,
Eric Liu155f5a42018-05-14 12:19:16 +0000257 std::vector<Inclusion> Inclusions)
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000258 : Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Eric Liu155f5a42018-05-14 12:19:16 +0000259 Inclusions(std::move(Inclusions)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000260
261ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
262 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000263 std::unique_ptr<FrontendAction> Action,
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000264 std::vector<const Decl *> LocalTopLevelDecls,
Eric Liu155f5a42018-05-14 12:19:16 +0000265 std::vector<Diag> Diags, std::vector<Inclusion> Inclusions)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000266 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
267 Action(std::move(Action)), Diags(std::move(Diags)),
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000268 LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
Eric Liu155f5a42018-05-14 12:19:16 +0000269 Inclusions(std::move(Inclusions)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000270 assert(this->Clang);
271 assert(this->Action);
272}
273
Ilya Biryukov823b0562018-06-01 10:08:43 +0000274std::unique_ptr<CompilerInvocation>
275clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000276 std::vector<const char *> ArgStrs;
277 for (const auto &S : Inputs.CompileCommand.CommandLine)
278 ArgStrs.push_back(S.c_str());
279
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000280 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Ilya Biryukov823b0562018-06-01 10:08:43 +0000281 log("Couldn't set working directory when creating compiler invocation.");
282 // We proceed anyway, our lit-tests rely on results for non-existing working
283 // dirs.
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000284 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000285
Ilya Biryukov823b0562018-06-01 10:08:43 +0000286 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
287 // reporting them.
288 IgnoreDiagnostics IgnoreDiagnostics;
289 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
290 CompilerInstance::createDiagnostics(new DiagnosticOptions,
291 &IgnoreDiagnostics, false);
292 std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
293 ArgStrs, CommandLineDiagsEngine, Inputs.FS);
294 if (!CI)
295 return nullptr;
296 // createInvocationFromCommandLine sets DisableFree.
297 CI->getFrontendOpts().DisableFree = false;
298 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
299 return CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000300}
301
Ilya Biryukov823b0562018-06-01 10:08:43 +0000302std::shared_ptr<const PreambleData> clangd::buildPreamble(
303 PathRef FileName, CompilerInvocation &CI,
304 std::shared_ptr<const PreambleData> OldPreamble,
305 const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
306 std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
307 PreambleParsedCallback PreambleCallback) {
308 // Note that we don't need to copy the input contents, preamble can live
309 // without those.
310 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
311 auto Bounds =
312 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000313
Ilya Biryukov823b0562018-06-01 10:08:43 +0000314 if (OldPreamble &&
315 compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
316 OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
317 Inputs.FS.get())) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000318 log("Reusing preamble for file " + Twine(FileName));
319 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000320 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000321 log("Preamble for file " + Twine(FileName) +
322 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000323
Ilya Biryukov823b0562018-06-01 10:08:43 +0000324 trace::Span Tracer("BuildPreamble");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000325 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000326 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000327 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
328 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000329 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000330
331 // Skip function bodies when building the preamble to speed up building
332 // the preamble and make it smaller.
333 assert(!CI.getFrontendOpts().SkipFunctionBodies);
334 CI.getFrontendOpts().SkipFunctionBodies = true;
335
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000336 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Ilya Biryukov823b0562018-06-01 10:08:43 +0000337 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
338 log("Couldn't set working directory when building the preamble.");
339 // We proceed anyway, our lit-tests rely on results for non-existing working
340 // dirs.
341 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000342 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov823b0562018-06-01 10:08:43 +0000343 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS, PCHs,
344 StoreInMemory, SerializedDeclsCollector);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000345
346 // When building the AST for the main file, we do want the function
347 // bodies.
348 CI.getFrontendOpts().SkipFunctionBodies = false;
349
350 if (BuiltPreamble) {
351 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
352 " for file " + Twine(FileName));
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000353 return std::make_shared<PreambleData>(
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000354 std::move(*BuiltPreamble), PreambleDiagnostics.take(),
355 SerializedDeclsCollector.takeInclusions());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000356 } else {
357 log("Could not build a preamble for file " + Twine(FileName));
358 return nullptr;
359 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000360}
Haojian Wu345099c2017-11-09 11:30:04 +0000361
Ilya Biryukov823b0562018-06-01 10:08:43 +0000362llvm::Optional<ParsedAST> clangd::buildAST(
363 PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
364 const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
365 std::shared_ptr<PCHContainerOperations> PCHs) {
366 trace::Span Tracer("BuildAST");
367 SPAN_ATTACH(Tracer, "File", FileName);
368
369 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
370 log("Couldn't set working directory when building the preamble.");
371 // We proceed anyway, our lit-tests rely on results for non-existing working
372 // dirs.
373 }
374
375 return ParsedAST::Build(
376 llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
377 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
378}
379
Haojian Wu345099c2017-11-09 11:30:04 +0000380SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
381 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000382 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000383 const ASTContext &AST = Unit.getASTContext();
384 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000385 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
386 if (!Offset) {
387 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
388 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000389 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000390 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000391
Sam McCalla4962cc2018-04-27 11:59:28 +0000392 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
393 // if the cursor is at the end of the identifier.
394 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
395 // 1) at the beginning of an identifier, we'll be looking at something
396 // that isn't an identifier.
397 // 2) at the middle or end of an identifier, we get the identifier.
398 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
399 // We can't actually distinguish cases 1 and 3, but returning the original
400 // location is correct for both!
401 if (*Offset == 0) // Case 1 or 3.
402 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
403 SourceLocation Before =
404 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
405 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
406 Token Tok;
407 if (Before.isValid() &&
408 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
409 Tok.is(tok::raw_identifier))
410 return Before; // Case 2.
411 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000412}