blob: a6ec1937a366d442cce3f7ad3bbe6233b80780c1 [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
Sam McCall3f0243f2018-07-03 08:09:29 +000091 IncludeStructure takeIncludes() { return std::move(Includes); }
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");
Sam McCall3f0243f2018-07-03 08:09:29 +0000106 return collectIncludeStructureCallback(*SourceMgr, &Includes);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000107 }
108
Ilya Biryukov04db3682017-07-21 13:29:29 +0000109private:
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000110 PathRef File;
111 PreambleParsedCallback ParsedCallback;
Sam McCall3f0243f2018-07-03 08:09:29 +0000112 IncludeStructure Includes;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000113 SourceManager *SourceMgr = nullptr;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000114};
115
Ilya Biryukov04db3682017-07-21 13:29:29 +0000116} // namespace
117
Ilya Biryukov02d58702017-08-01 15:51:38 +0000118void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
119 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000120}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000121
Ilya Biryukov02d58702017-08-01 15:51:38 +0000122llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000123ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000124 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000125 std::unique_ptr<llvm::MemoryBuffer> Buffer,
126 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000127 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000128 assert(CI);
129 // Command-line parsing sets DisableFree to true by default, but we don't want
130 // to leak memory in clangd.
131 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000132 const PrecompiledPreamble *PreamblePCH =
133 Preamble ? &Preamble->Preamble : nullptr;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000134
135 StoreDiags ASTDiags;
136 auto Clang =
137 prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
138 std::move(PCHs), std::move(VFS), ASTDiags);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000139 if (!Clang)
140 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000141
142 // Recover resources if we crash before exiting this method.
143 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
144 Clang.get());
145
146 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000147 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
148 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000149 log("BeginSourceFile() failed when building AST for " +
150 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000151 return llvm::None;
152 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000153
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000154 // Copy over the includes from the preamble, then combine with the
155 // non-preamble includes below.
Sam McCall3f0243f2018-07-03 08:09:29 +0000156 auto Includes = Preamble ? Preamble->Includes : IncludeStructure{};
157 Clang->getPreprocessor().addPPCallbacks(
158 collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000159
Ilya Biryukove5128f72017-09-20 07:24:15 +0000160 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000161 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000162
163 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
164 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000165 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000166 // CompilerInstance won't run this callback, do it directly.
167 ASTDiags.EndSourceFile();
Ilya Biryukov04db3682017-07-21 13:29:29 +0000168
Sam McCalld9b54f02018-06-05 16:30:25 +0000169 std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov823b0562018-06-01 10:08:43 +0000170 std::vector<Diag> Diags = ASTDiags.take();
171 // Add diagnostics from the preamble, if any.
172 if (Preamble)
173 Diags.insert(Diags.begin(), Preamble->Diags.begin(), Preamble->Diags.end());
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000174 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
Ilya Biryukov823b0562018-06-01 10:08:43 +0000175 std::move(ParsedDecls), std::move(Diags),
Sam McCall3f0243f2018-07-03 08:09:29 +0000176 std::move(Includes));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000177}
178
Ilya Biryukov02d58702017-08-01 15:51:38 +0000179ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000180
Ilya Biryukov02d58702017-08-01 15:51:38 +0000181ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000182
Ilya Biryukov02d58702017-08-01 15:51:38 +0000183ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000184 if (Action) {
185 Action->EndSourceFile();
186 }
187}
188
Ilya Biryukov02d58702017-08-01 15:51:38 +0000189ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
190
191const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000192 return Clang->getASTContext();
193}
194
Ilya Biryukov02d58702017-08-01 15:51:38 +0000195Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000196
Eric Liu76f6b442018-01-09 17:32:00 +0000197std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
198 return Clang->getPreprocessorPtr();
199}
200
Ilya Biryukov02d58702017-08-01 15:51:38 +0000201const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000202 return Clang->getPreprocessor();
203}
204
Sam McCalld9b54f02018-06-05 16:30:25 +0000205ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000206 return LocalTopLevelDecls;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000207}
208
Ilya Biryukov71028b82018-03-12 15:28:22 +0000209const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000210
Ilya Biryukovdf842342018-01-25 14:32:21 +0000211std::size_t ParsedAST::getUsedBytes() const {
212 auto &AST = getASTContext();
213 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
Ilya Biryukov71028b82018-03-12 15:28:22 +0000214 // Message and Fixes inside each diagnostic.
Ilya Biryukov0da27c72018-06-01 14:44:57 +0000215 std::size_t Total =
216 ::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
217
218 // FIXME: the rest of the function is almost a direct copy-paste from
219 // libclang's clang_getCXTUResourceUsage. We could share the implementation.
220
221 // Sum up variaous allocators inside the ast context and the preprocessor.
222 Total += AST.getASTAllocatedMemory();
223 Total += AST.getSideTableAllocatedMemory();
224 Total += AST.Idents.getAllocator().getTotalMemory();
225 Total += AST.Selectors.getTotalMemory();
226
227 Total += AST.getSourceManager().getContentCacheSize();
228 Total += AST.getSourceManager().getDataStructureSizes();
229 Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
230
231 if (ExternalASTSource *Ext = AST.getExternalSource())
232 Total += Ext->getMemoryBufferSizes().malloc_bytes;
233
234 const Preprocessor &PP = getPreprocessor();
235 Total += PP.getTotalMemory();
236 if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
237 Total += PRec->getTotalMemory();
238 Total += PP.getHeaderSearchInfo().getTotalMemory();
239
240 return Total;
Ilya Biryukovdf842342018-01-25 14:32:21 +0000241}
242
Sam McCall3f0243f2018-07-03 08:09:29 +0000243const IncludeStructure &ParsedAST::getIncludeStructure() const {
244 return Includes;
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000245}
246
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000247PreambleData::PreambleData(PrecompiledPreamble Preamble,
Sam McCall3f0243f2018-07-03 08:09:29 +0000248 std::vector<Diag> Diags, IncludeStructure Includes)
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000249 : Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Sam McCall3f0243f2018-07-03 08:09:29 +0000250 Includes(std::move(Includes)) {}
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000251
252ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
253 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000254 std::unique_ptr<FrontendAction> Action,
Sam McCalld9b54f02018-06-05 16:30:25 +0000255 std::vector<Decl *> LocalTopLevelDecls,
Sam McCall3f0243f2018-07-03 08:09:29 +0000256 std::vector<Diag> Diags, IncludeStructure Includes)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000257 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
258 Action(std::move(Action)), Diags(std::move(Diags)),
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000259 LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
Sam McCall3f0243f2018-07-03 08:09:29 +0000260 Includes(std::move(Includes)) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000261 assert(this->Clang);
262 assert(this->Action);
263}
264
Ilya Biryukov823b0562018-06-01 10:08:43 +0000265std::unique_ptr<CompilerInvocation>
266clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000267 std::vector<const char *> ArgStrs;
268 for (const auto &S : Inputs.CompileCommand.CommandLine)
269 ArgStrs.push_back(S.c_str());
270
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000271 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Ilya Biryukov823b0562018-06-01 10:08:43 +0000272 log("Couldn't set working directory when creating compiler invocation.");
273 // We proceed anyway, our lit-tests rely on results for non-existing working
274 // dirs.
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000275 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000276
Ilya Biryukov823b0562018-06-01 10:08:43 +0000277 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
278 // reporting them.
279 IgnoreDiagnostics IgnoreDiagnostics;
280 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
281 CompilerInstance::createDiagnostics(new DiagnosticOptions,
282 &IgnoreDiagnostics, false);
283 std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
284 ArgStrs, CommandLineDiagsEngine, Inputs.FS);
285 if (!CI)
286 return nullptr;
287 // createInvocationFromCommandLine sets DisableFree.
288 CI->getFrontendOpts().DisableFree = false;
289 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
290 return CI;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000291}
292
Ilya Biryukov823b0562018-06-01 10:08:43 +0000293std::shared_ptr<const PreambleData> clangd::buildPreamble(
294 PathRef FileName, CompilerInvocation &CI,
295 std::shared_ptr<const PreambleData> OldPreamble,
296 const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
297 std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
298 PreambleParsedCallback PreambleCallback) {
299 // Note that we don't need to copy the input contents, preamble can live
300 // without those.
301 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
302 auto Bounds =
303 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000304
Ilya Biryukov823b0562018-06-01 10:08:43 +0000305 if (OldPreamble &&
306 compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
307 OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
308 Inputs.FS.get())) {
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000309 log("Reusing preamble for file " + Twine(FileName));
310 return OldPreamble;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000311 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000312 log("Preamble for file " + Twine(FileName) +
313 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000314
Ilya Biryukov823b0562018-06-01 10:08:43 +0000315 trace::Span Tracer("BuildPreamble");
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000316 SPAN_ATTACH(Tracer, "File", FileName);
Ilya Biryukov71028b82018-03-12 15:28:22 +0000317 StoreDiags PreambleDiagnostics;
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000318 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
319 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
Ilya Biryukov71028b82018-03-12 15:28:22 +0000320 &PreambleDiagnostics, false);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000321
322 // Skip function bodies when building the preamble to speed up building
323 // the preamble and make it smaller.
324 assert(!CI.getFrontendOpts().SkipFunctionBodies);
325 CI.getFrontendOpts().SkipFunctionBodies = true;
326
Ilya Biryukov6c5e99e2018-05-24 15:50:15 +0000327 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Ilya Biryukov823b0562018-06-01 10:08:43 +0000328 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
329 log("Couldn't set working directory when building the preamble.");
330 // We proceed anyway, our lit-tests rely on results for non-existing working
331 // dirs.
332 }
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000333 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov823b0562018-06-01 10:08:43 +0000334 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS, PCHs,
335 StoreInMemory, SerializedDeclsCollector);
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000336
337 // When building the AST for the main file, we do want the function
338 // bodies.
339 CI.getFrontendOpts().SkipFunctionBodies = false;
340
341 if (BuiltPreamble) {
342 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
343 " for file " + Twine(FileName));
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000344 return std::make_shared<PreambleData>(
Ilya Biryukovda0256f2018-05-28 12:23:17 +0000345 std::move(*BuiltPreamble), PreambleDiagnostics.take(),
Sam McCall3f0243f2018-07-03 08:09:29 +0000346 SerializedDeclsCollector.takeIncludes());
Ilya Biryukov44ba9e02018-02-09 10:17:23 +0000347 } else {
348 log("Could not build a preamble for file " + Twine(FileName));
349 return nullptr;
350 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000351}
Haojian Wu345099c2017-11-09 11:30:04 +0000352
Ilya Biryukov823b0562018-06-01 10:08:43 +0000353llvm::Optional<ParsedAST> clangd::buildAST(
354 PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
355 const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
356 std::shared_ptr<PCHContainerOperations> PCHs) {
357 trace::Span Tracer("BuildAST");
358 SPAN_ATTACH(Tracer, "File", FileName);
359
360 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
361 log("Couldn't set working directory when building the preamble.");
362 // We proceed anyway, our lit-tests rely on results for non-existing working
363 // dirs.
364 }
365
366 return ParsedAST::Build(
367 llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
368 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
369}
370
Haojian Wu345099c2017-11-09 11:30:04 +0000371SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
372 const Position &Pos,
Sam McCalla4962cc2018-04-27 11:59:28 +0000373 const FileID FID) {
Haojian Wu345099c2017-11-09 11:30:04 +0000374 const ASTContext &AST = Unit.getASTContext();
375 const SourceManager &SourceMgr = AST.getSourceManager();
Sam McCalla4962cc2018-04-27 11:59:28 +0000376 auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
377 if (!Offset) {
378 log("getBeginningOfIdentifier: " + toString(Offset.takeError()));
379 return SourceLocation();
Haojian Wu345099c2017-11-09 11:30:04 +0000380 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000381 SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
Haojian Wu345099c2017-11-09 11:30:04 +0000382
Sam McCalla4962cc2018-04-27 11:59:28 +0000383 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
384 // if the cursor is at the end of the identifier.
385 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
386 // 1) at the beginning of an identifier, we'll be looking at something
387 // that isn't an identifier.
388 // 2) at the middle or end of an identifier, we get the identifier.
389 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
390 // We can't actually distinguish cases 1 and 3, but returning the original
391 // location is correct for both!
392 if (*Offset == 0) // Case 1 or 3.
393 return SourceMgr.getMacroArgExpandedLocation(InputLoc);
394 SourceLocation Before =
395 SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
396 Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
397 Token Tok;
398 if (Before.isValid() &&
399 !Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
400 Tok.is(tok::raw_identifier))
401 return Before; // Case 2.
402 return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
Haojian Wu345099c2017-11-09 11:30:04 +0000403}