2017-05-16 17:38:59 +08:00
|
|
|
//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===---------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "ClangdUnit.h"
|
2017-12-04 21:49:59 +08:00
|
|
|
#include "Compiler.h"
|
2017-09-20 18:46:58 +08:00
|
|
|
#include "Logger.h"
|
2017-11-02 17:21:51 +08:00
|
|
|
#include "Trace.h"
|
2017-05-16 17:38:59 +08:00
|
|
|
#include "clang/Frontend/CompilerInstance.h"
|
|
|
|
#include "clang/Frontend/CompilerInvocation.h"
|
2017-07-21 21:29:29 +08:00
|
|
|
#include "clang/Frontend/FrontendActions.h"
|
2017-05-26 20:26:51 +08:00
|
|
|
#include "clang/Frontend/Utils.h"
|
2017-06-29 00:12:10 +08:00
|
|
|
#include "clang/Index/IndexDataConsumer.h"
|
2017-07-21 21:29:29 +08:00
|
|
|
#include "clang/Index/IndexingAction.h"
|
2017-06-29 00:12:10 +08:00
|
|
|
#include "clang/Lex/Lexer.h"
|
|
|
|
#include "clang/Lex/MacroInfo.h"
|
|
|
|
#include "clang/Lex/Preprocessor.h"
|
2017-07-21 21:29:29 +08:00
|
|
|
#include "clang/Sema/Sema.h"
|
|
|
|
#include "clang/Serialization/ASTWriter.h"
|
2017-05-16 17:38:59 +08:00
|
|
|
#include "clang/Tooling/CompilationDatabase.h"
|
2017-07-21 21:29:29 +08:00
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
|
|
|
#include "llvm/ADT/SmallVector.h"
|
|
|
|
#include "llvm/Support/CrashRecoveryContext.h"
|
2018-02-02 03:06:45 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2017-06-29 00:12:10 +08:00
|
|
|
#include <algorithm>
|
|
|
|
|
2017-05-16 17:38:59 +08:00
|
|
|
using namespace clang::clangd;
|
|
|
|
using namespace clang;
|
|
|
|
|
2017-07-21 21:29:29 +08:00
|
|
|
namespace {
|
|
|
|
|
2018-01-25 22:32:21 +08:00
|
|
|
template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
|
|
|
|
return Vec.capacity() * sizeof(T);
|
|
|
|
}
|
|
|
|
|
2017-07-21 21:29:29 +08:00
|
|
|
class DeclTrackingASTConsumer : public ASTConsumer {
|
|
|
|
public:
|
|
|
|
DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
|
|
|
|
: TopLevelDecls(TopLevelDecls) {}
|
|
|
|
|
|
|
|
bool HandleTopLevelDecl(DeclGroupRef DG) override {
|
|
|
|
for (const Decl *D : DG) {
|
|
|
|
// ObjCMethodDecl are not actually top-level decls.
|
|
|
|
if (isa<ObjCMethodDecl>(D))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
TopLevelDecls.push_back(D);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::vector<const Decl *> &TopLevelDecls;
|
|
|
|
};
|
|
|
|
|
|
|
|
class ClangdFrontendAction : public SyntaxOnlyAction {
|
|
|
|
public:
|
|
|
|
std::vector<const Decl *> takeTopLevelDecls() {
|
|
|
|
return std::move(TopLevelDecls);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
|
|
|
|
StringRef InFile) override {
|
|
|
|
return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::vector<const Decl *> TopLevelDecls;
|
|
|
|
};
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
class CppFilePreambleCallbacks : public PreambleCallbacks {
|
2017-07-21 21:29:29 +08:00
|
|
|
public:
|
|
|
|
std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
|
|
|
|
return std::move(TopLevelDeclIDs);
|
|
|
|
}
|
|
|
|
|
|
|
|
void AfterPCHEmitted(ASTWriter &Writer) override {
|
|
|
|
TopLevelDeclIDs.reserve(TopLevelDecls.size());
|
|
|
|
for (Decl *D : TopLevelDecls) {
|
|
|
|
// Invalid top-level decls may not have been serialized.
|
|
|
|
if (D->isInvalidDecl())
|
|
|
|
continue;
|
|
|
|
TopLevelDeclIDs.push_back(Writer.getDeclID(D));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void HandleTopLevelDecl(DeclGroupRef DG) override {
|
|
|
|
for (Decl *D : DG) {
|
|
|
|
if (isa<ObjCMethodDecl>(D))
|
|
|
|
continue;
|
|
|
|
TopLevelDecls.push_back(D);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::vector<Decl *> TopLevelDecls;
|
|
|
|
std::vector<serialization::DeclID> TopLevelDeclIDs;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// Convert from clang diagnostic level to LSP severity.
|
|
|
|
static int getSeverity(DiagnosticsEngine::Level L) {
|
|
|
|
switch (L) {
|
|
|
|
case DiagnosticsEngine::Remark:
|
|
|
|
return 4;
|
|
|
|
case DiagnosticsEngine::Note:
|
|
|
|
return 3;
|
|
|
|
case DiagnosticsEngine::Warning:
|
|
|
|
return 2;
|
|
|
|
case DiagnosticsEngine::Fatal:
|
|
|
|
case DiagnosticsEngine::Error:
|
|
|
|
return 1;
|
|
|
|
case DiagnosticsEngine::Ignored:
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
llvm_unreachable("Unknown diagnostic level!");
|
|
|
|
}
|
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
// Checks whether a location is within a half-open range.
|
|
|
|
// Note that clang also uses closed source ranges, which this can't handle!
|
|
|
|
bool locationInRange(SourceLocation L, CharSourceRange R,
|
|
|
|
const SourceManager &M) {
|
|
|
|
assert(R.isCharRange());
|
|
|
|
if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
|
|
|
|
M.getFileID(R.getBegin()) != M.getFileID(L))
|
|
|
|
return false;
|
|
|
|
return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
|
|
|
|
}
|
2017-07-21 21:29:29 +08:00
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
// Converts a half-open clang source range to an LSP range.
|
|
|
|
// Note that clang also uses closed source ranges, which this can't handle!
|
|
|
|
Range toRange(CharSourceRange R, const SourceManager &M) {
|
|
|
|
// Clang is 1-based, LSP uses 0-based indexes.
|
|
|
|
return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
|
|
|
|
static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
|
|
|
|
{static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
|
|
|
|
static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
|
|
|
|
}
|
2017-07-21 21:29:29 +08:00
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
|
|
|
|
// LSP needs a single range.
|
|
|
|
Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
|
|
|
|
auto &M = D.getSourceManager();
|
|
|
|
auto Loc = M.getFileLoc(D.getLocation());
|
|
|
|
// Accept the first range that contains the location.
|
|
|
|
for (const auto &CR : D.getRanges()) {
|
|
|
|
auto R = Lexer::makeFileCharRange(CR, M, L);
|
|
|
|
if (locationInRange(Loc, R, M))
|
|
|
|
return toRange(R, M);
|
|
|
|
}
|
|
|
|
// The range may be given as a fixit hint instead.
|
|
|
|
for (const auto &F : D.getFixItHints()) {
|
|
|
|
auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
|
|
|
|
if (locationInRange(Loc, R, M))
|
|
|
|
return toRange(R, M);
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
// If no suitable range is found, just use the token at the location.
|
|
|
|
auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
|
|
|
|
if (!R.isValid()) // Fall back to location only, let the editor deal with it.
|
|
|
|
R = CharSourceRange::getCharRange(Loc);
|
|
|
|
return toRange(R, M);
|
|
|
|
}
|
|
|
|
|
|
|
|
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
|
|
|
|
const LangOptions &L) {
|
|
|
|
TextEdit Result;
|
|
|
|
Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
|
|
|
|
Result.newText = FixIt.CodeToInsert;
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
|
|
|
llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
|
|
|
|
DiagnosticsEngine::Level Level,
|
|
|
|
const LangOptions &LangOpts) {
|
|
|
|
if (!D.hasSourceManager() || !D.getLocation().isValid() ||
|
2018-02-02 03:06:45 +08:00
|
|
|
!D.getSourceManager().isInMainFile(D.getLocation())) {
|
2018-02-12 20:48:51 +08:00
|
|
|
IgnoreDiagnostics::log(Level, D);
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
return llvm::None;
|
2018-02-02 03:06:45 +08:00
|
|
|
}
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
|
2018-02-12 20:48:51 +08:00
|
|
|
SmallString<64> Message;
|
|
|
|
D.FormatDiagnostic(Message);
|
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
DiagWithFixIts Result;
|
|
|
|
Result.Diag.range = diagnosticRange(D, LangOpts);
|
|
|
|
Result.Diag.severity = getSeverity(Level);
|
|
|
|
Result.Diag.message = Message.str();
|
|
|
|
for (const FixItHint &Fix : D.getFixItHints())
|
|
|
|
Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
|
|
|
|
return std::move(Result);
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
class StoreDiagsConsumer : public DiagnosticConsumer {
|
|
|
|
public:
|
|
|
|
StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
|
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
// Track language options in case we need to expand token ranges.
|
|
|
|
void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
|
|
|
|
LangOpts = Opts;
|
|
|
|
}
|
|
|
|
|
|
|
|
void EndSourceFile() override { LangOpts = llvm::None; }
|
|
|
|
|
2017-07-21 21:29:29 +08:00
|
|
|
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
|
|
|
|
const clang::Diagnostic &Info) override {
|
|
|
|
DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
|
|
|
|
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
if (LangOpts)
|
|
|
|
if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
|
|
|
|
Output.push_back(std::move(*D));
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::vector<DiagWithFixIts> &Output;
|
[clangd] Emit ranges for clangd diagnostics, and fix off-by-one positions
Summary:
- when the diagnostic has an explicit range, we prefer that
- if the diagnostic has a fixit, its RemoveRange is our next choice
- otherwise we try to expand the diagnostic location into a whole token.
(inspired by VSCode, which does this client-side when given an empty range)
- if all else fails, we return the zero-width range as now.
(clients react in different ways to this, highlighting a token or a char)
- this includes the off-by-one fix from D40860, and borrows heavily from it
Reviewers: rwols, hokein
Subscribers: klimek, ilya-biryukov, cfe-commits
Differential Revision: https://reviews.llvm.org/D41118
llvm-svn: 320555
2017-12-13 16:48:42 +08:00
|
|
|
llvm::Optional<LangOptions> LangOpts;
|
2017-07-21 21:29:29 +08:00
|
|
|
};
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
} // namespace
|
2017-05-16 17:38:59 +08:00
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
|
|
|
|
AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
2017-05-23 21:42:59 +08:00
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
llvm::Optional<ParsedAST>
|
[clangd] Pass Context implicitly using TLS.
Summary:
Instead of passing Context explicitly around, we now have a thread-local
Context object `Context::current()` which is an implicit argument to
every function.
Most manipulation of this should use the WithContextValue helper, which
augments the current Context to add a single KV pair, and restores the
old context on destruction.
Advantages are:
- less boilerplate in functions that just propagate contexts
- reading most code doesn't require understanding context at all, and
using context as values in fewer places still
- fewer options to pass the "wrong" context when it changes within a
scope (e.g. when using Span)
- contexts pass through interfaces we can't modify, such as VFS
- propagating contexts across threads was slightly tricky (e.g.
copy vs move, no move-init in lambdas), and is now encapsulated in
the threadpool
Disadvantages are all the usual TLS stuff - hidden magic, and
potential for higher memory usage on threads that don't use the
context. (In practice, it's just one pointer)
Reviewers: ilya-biryukov
Subscribers: klimek, jkorous-apple, ioeric, cfe-commits
Differential Revision: https://reviews.llvm.org/D42517
llvm-svn: 323872
2018-01-31 21:40:48 +08:00
|
|
|
ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
|
2017-11-24 21:04:21 +08:00
|
|
|
std::shared_ptr<const PreambleData> Preamble,
|
2017-08-01 23:51:38 +08:00
|
|
|
std::unique_ptr<llvm::MemoryBuffer> Buffer,
|
|
|
|
std::shared_ptr<PCHContainerOperations> PCHs,
|
2017-12-13 20:51:22 +08:00
|
|
|
IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
|
2017-07-21 21:29:29 +08:00
|
|
|
std::vector<DiagWithFixIts> ASTDiags;
|
|
|
|
StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
|
|
|
|
|
2017-11-24 21:04:21 +08:00
|
|
|
const PrecompiledPreamble *PreamblePCH =
|
|
|
|
Preamble ? &Preamble->Preamble : nullptr;
|
2017-10-29 01:32:56 +08:00
|
|
|
auto Clang = prepareCompilerInstance(
|
2017-11-24 21:04:21 +08:00
|
|
|
std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
|
2017-10-29 01:32:56 +08:00
|
|
|
std::move(VFS), /*ref*/ UnitDiagsConsumer);
|
2018-01-29 22:30:28 +08:00
|
|
|
if (!Clang)
|
|
|
|
return llvm::None;
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
// Recover resources if we crash before exiting this method.
|
|
|
|
llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
|
|
|
|
Clang.get());
|
|
|
|
|
|
|
|
auto Action = llvm::make_unique<ClangdFrontendAction>();
|
2017-09-20 15:24:15 +08:00
|
|
|
const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
|
|
|
|
if (!Action->BeginSourceFile(*Clang, MainInput)) {
|
[clangd] Pass Context implicitly using TLS.
Summary:
Instead of passing Context explicitly around, we now have a thread-local
Context object `Context::current()` which is an implicit argument to
every function.
Most manipulation of this should use the WithContextValue helper, which
augments the current Context to add a single KV pair, and restores the
old context on destruction.
Advantages are:
- less boilerplate in functions that just propagate contexts
- reading most code doesn't require understanding context at all, and
using context as values in fewer places still
- fewer options to pass the "wrong" context when it changes within a
scope (e.g. when using Span)
- contexts pass through interfaces we can't modify, such as VFS
- propagating contexts across threads was slightly tricky (e.g.
copy vs move, no move-init in lambdas), and is now encapsulated in
the threadpool
Disadvantages are all the usual TLS stuff - hidden magic, and
potential for higher memory usage on threads that don't use the
context. (In practice, it's just one pointer)
Reviewers: ilya-biryukov
Subscribers: klimek, jkorous-apple, ioeric, cfe-commits
Differential Revision: https://reviews.llvm.org/D42517
llvm-svn: 323872
2018-01-31 21:40:48 +08:00
|
|
|
log("BeginSourceFile() failed when building AST for " +
|
|
|
|
MainInput.getFile());
|
2017-07-21 21:29:29 +08:00
|
|
|
return llvm::None;
|
|
|
|
}
|
2017-09-20 15:24:15 +08:00
|
|
|
if (!Action->Execute())
|
[clangd] Pass Context implicitly using TLS.
Summary:
Instead of passing Context explicitly around, we now have a thread-local
Context object `Context::current()` which is an implicit argument to
every function.
Most manipulation of this should use the WithContextValue helper, which
augments the current Context to add a single KV pair, and restores the
old context on destruction.
Advantages are:
- less boilerplate in functions that just propagate contexts
- reading most code doesn't require understanding context at all, and
using context as values in fewer places still
- fewer options to pass the "wrong" context when it changes within a
scope (e.g. when using Span)
- contexts pass through interfaces we can't modify, such as VFS
- propagating contexts across threads was slightly tricky (e.g.
copy vs move, no move-init in lambdas), and is now encapsulated in
the threadpool
Disadvantages are all the usual TLS stuff - hidden magic, and
potential for higher memory usage on threads that don't use the
context. (In practice, it's just one pointer)
Reviewers: ilya-biryukov
Subscribers: klimek, jkorous-apple, ioeric, cfe-commits
Differential Revision: https://reviews.llvm.org/D42517
llvm-svn: 323872
2018-01-31 21:40:48 +08:00
|
|
|
log("Execute() failed when building AST for " + MainInput.getFile());
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
// UnitDiagsConsumer is local, we can not store it in CompilerInstance that
|
|
|
|
// has a longer lifetime.
|
2017-12-04 21:49:59 +08:00
|
|
|
Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
|
2017-11-24 21:04:21 +08:00
|
|
|
return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
|
|
|
|
std::move(ParsedDecls), std::move(ASTDiags));
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
|
|
|
|
2017-06-29 00:12:10 +08:00
|
|
|
namespace {
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
|
|
|
|
const FileEntry *FE, Position Pos) {
|
|
|
|
SourceLocation InputLoc =
|
|
|
|
Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
|
|
|
|
return Mgr.getMacroArgExpandedLocation(InputLoc);
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
} // namespace
|
|
|
|
|
|
|
|
void ParsedAST::ensurePreambleDeclsDeserialized() {
|
2017-11-24 21:04:21 +08:00
|
|
|
if (PreambleDeclsDeserialized || !Preamble)
|
2017-07-21 21:29:29 +08:00
|
|
|
return;
|
|
|
|
|
|
|
|
std::vector<const Decl *> Resolved;
|
2017-11-24 21:04:21 +08:00
|
|
|
Resolved.reserve(Preamble->TopLevelDeclIDs.size());
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
ExternalASTSource &Source = *getASTContext().getExternalSource();
|
2017-11-24 21:04:21 +08:00
|
|
|
for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
|
2017-07-21 21:29:29 +08:00
|
|
|
// Resolve the declaration ID to an actual declaration, possibly
|
|
|
|
// deserializing the declaration in the process.
|
|
|
|
if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
|
|
|
|
Resolved.push_back(D);
|
|
|
|
}
|
|
|
|
|
2017-11-24 21:04:21 +08:00
|
|
|
TopLevelDecls.reserve(TopLevelDecls.size() +
|
|
|
|
Preamble->TopLevelDeclIDs.size());
|
2017-07-21 21:29:29 +08:00
|
|
|
TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
|
|
|
|
|
2017-11-24 21:04:21 +08:00
|
|
|
PreambleDeclsDeserialized = true;
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
ParsedAST::ParsedAST(ParsedAST &&Other) = default;
|
2017-07-21 21:29:29 +08:00
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
|
2017-07-21 21:29:29 +08:00
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
ParsedAST::~ParsedAST() {
|
2017-07-21 21:29:29 +08:00
|
|
|
if (Action) {
|
|
|
|
Action->EndSourceFile();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
|
2017-07-21 21:29:29 +08:00
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
const ASTContext &ParsedAST::getASTContext() const {
|
2017-07-21 21:29:29 +08:00
|
|
|
return Clang->getASTContext();
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
|
2017-07-21 21:29:29 +08:00
|
|
|
|
2018-01-10 01:32:00 +08:00
|
|
|
std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
|
|
|
|
return Clang->getPreprocessorPtr();
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
const Preprocessor &ParsedAST::getPreprocessor() const {
|
2017-07-21 21:29:29 +08:00
|
|
|
return Clang->getPreprocessor();
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
|
2017-07-21 21:29:29 +08:00
|
|
|
ensurePreambleDeclsDeserialized();
|
|
|
|
return TopLevelDecls;
|
|
|
|
}
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
|
2017-07-21 21:29:29 +08:00
|
|
|
return Diags;
|
|
|
|
}
|
|
|
|
|
2018-01-25 22:32:21 +08:00
|
|
|
std::size_t ParsedAST::getUsedBytes() const {
|
|
|
|
auto &AST = getASTContext();
|
|
|
|
// FIXME(ibiryukov): we do not account for the dynamically allocated part of
|
|
|
|
// SmallVector<FixIt> inside each Diag.
|
|
|
|
return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
|
|
|
|
::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
|
|
|
|
}
|
|
|
|
|
2017-11-24 21:04:21 +08:00
|
|
|
PreambleData::PreambleData(PrecompiledPreamble Preamble,
|
|
|
|
std::vector<serialization::DeclID> TopLevelDeclIDs,
|
|
|
|
std::vector<DiagWithFixIts> Diags)
|
|
|
|
: Preamble(std::move(Preamble)),
|
|
|
|
TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
|
|
|
|
|
|
|
|
ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
|
|
|
|
std::unique_ptr<CompilerInstance> Clang,
|
2017-08-01 23:51:38 +08:00
|
|
|
std::unique_ptr<FrontendAction> Action,
|
|
|
|
std::vector<const Decl *> TopLevelDecls,
|
|
|
|
std::vector<DiagWithFixIts> Diags)
|
2017-11-24 21:04:21 +08:00
|
|
|
: Preamble(std::move(Preamble)), Clang(std::move(Clang)),
|
|
|
|
Action(std::move(Action)), Diags(std::move(Diags)),
|
|
|
|
TopLevelDecls(std::move(TopLevelDecls)),
|
|
|
|
PreambleDeclsDeserialized(false) {
|
2017-07-21 21:29:29 +08:00
|
|
|
assert(this->Clang);
|
|
|
|
assert(this->Action);
|
|
|
|
}
|
|
|
|
|
2018-01-23 23:07:52 +08:00
|
|
|
CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
|
2017-12-20 02:00:37 +08:00
|
|
|
std::shared_ptr<PCHContainerOperations> PCHs,
|
|
|
|
ASTParsedCallback ASTCallback)
|
2018-01-23 23:07:52 +08:00
|
|
|
: FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
|
2018-02-09 18:17:23 +08:00
|
|
|
PCHs(std::move(PCHs)), ASTCallback(std::move(ASTCallback)) {
|
[clangd] Pass Context implicitly using TLS.
Summary:
Instead of passing Context explicitly around, we now have a thread-local
Context object `Context::current()` which is an implicit argument to
every function.
Most manipulation of this should use the WithContextValue helper, which
augments the current Context to add a single KV pair, and restores the
old context on destruction.
Advantages are:
- less boilerplate in functions that just propagate contexts
- reading most code doesn't require understanding context at all, and
using context as values in fewer places still
- fewer options to pass the "wrong" context when it changes within a
scope (e.g. when using Span)
- contexts pass through interfaces we can't modify, such as VFS
- propagating contexts across threads was slightly tricky (e.g.
copy vs move, no move-init in lambdas), and is now encapsulated in
the threadpool
Disadvantages are all the usual TLS stuff - hidden magic, and
potential for higher memory usage on threads that don't use the
context. (In practice, it's just one pointer)
Reviewers: ilya-biryukov
Subscribers: klimek, jkorous-apple, ioeric, cfe-commits
Differential Revision: https://reviews.llvm.org/D42517
llvm-svn: 323872
2018-01-31 21:40:48 +08:00
|
|
|
log("Created CppFile for " + FileName);
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
llvm::Optional<std::vector<DiagWithFixIts>>
|
[clangd] Pass Context implicitly using TLS.
Summary:
Instead of passing Context explicitly around, we now have a thread-local
Context object `Context::current()` which is an implicit argument to
every function.
Most manipulation of this should use the WithContextValue helper, which
augments the current Context to add a single KV pair, and restores the
old context on destruction.
Advantages are:
- less boilerplate in functions that just propagate contexts
- reading most code doesn't require understanding context at all, and
using context as values in fewer places still
- fewer options to pass the "wrong" context when it changes within a
scope (e.g. when using Span)
- contexts pass through interfaces we can't modify, such as VFS
- propagating contexts across threads was slightly tricky (e.g.
copy vs move, no move-init in lambdas), and is now encapsulated in
the threadpool
Disadvantages are all the usual TLS stuff - hidden magic, and
potential for higher memory usage on threads that don't use the
context. (In practice, it's just one pointer)
Reviewers: ilya-biryukov
Subscribers: klimek, jkorous-apple, ioeric, cfe-commits
Differential Revision: https://reviews.llvm.org/D42517
llvm-svn: 323872
2018-01-31 21:40:48 +08:00
|
|
|
CppFile::rebuild(ParseInputs &&Inputs) {
|
2018-02-09 18:17:23 +08:00
|
|
|
log("Rebuilding file " + FileName + " with command [" +
|
|
|
|
Inputs.CompileCommand.Directory + "] " +
|
|
|
|
llvm::join(Inputs.CompileCommand.CommandLine, " "));
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
std::vector<const char *> ArgStrs;
|
|
|
|
for (const auto &S : Inputs.CompileCommand.CommandLine)
|
|
|
|
ArgStrs.push_back(S.c_str());
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
// Prepare CompilerInvocation.
|
|
|
|
std::unique_ptr<CompilerInvocation> CI;
|
|
|
|
{
|
|
|
|
// FIXME(ibiryukov): store diagnostics from CommandLine when we start
|
|
|
|
// reporting them.
|
|
|
|
IgnoreDiagnostics IgnoreDiagnostics;
|
|
|
|
IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
|
|
|
|
CompilerInstance::createDiagnostics(new DiagnosticOptions,
|
|
|
|
&IgnoreDiagnostics, false);
|
|
|
|
CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
|
|
|
|
Inputs.FS);
|
2018-02-09 21:51:57 +08:00
|
|
|
if (!CI) {
|
|
|
|
log("Could not build CompilerInvocation for file " + FileName);
|
|
|
|
AST = llvm::None;
|
|
|
|
Preamble = nullptr;
|
|
|
|
return llvm::None;
|
|
|
|
}
|
2018-02-09 18:17:23 +08:00
|
|
|
// createInvocationFromCommandLine sets DisableFree.
|
|
|
|
CI->getFrontendOpts().DisableFree = false;
|
|
|
|
}
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
|
|
|
|
llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, FileName);
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
// Compute updated Preamble.
|
|
|
|
std::shared_ptr<const PreambleData> NewPreamble =
|
|
|
|
rebuildPreamble(*CI, Inputs.FS, *ContentsBuffer);
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
// Remove current AST to avoid wasting memory.
|
|
|
|
AST = llvm::None;
|
|
|
|
// Compute updated AST.
|
|
|
|
llvm::Optional<ParsedAST> NewAST;
|
|
|
|
{
|
|
|
|
trace::Span Tracer("Build");
|
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
|
|
|
NewAST = ParsedAST::Build(std::move(CI), NewPreamble,
|
|
|
|
std::move(ContentsBuffer), PCHs, Inputs.FS);
|
|
|
|
}
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
std::vector<DiagWithFixIts> Diagnostics;
|
|
|
|
if (NewAST) {
|
|
|
|
// Collect diagnostics from both the preamble and the AST.
|
|
|
|
if (NewPreamble)
|
|
|
|
Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
|
|
|
|
NewPreamble->Diags.end());
|
|
|
|
Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
|
|
|
|
NewAST->getDiagnostics().end());
|
|
|
|
}
|
|
|
|
if (ASTCallback && NewAST)
|
|
|
|
ASTCallback(FileName, NewAST.getPointer());
|
2017-08-01 23:51:38 +08:00
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
// Write the results of rebuild into class fields.
|
|
|
|
Preamble = std::move(NewPreamble);
|
|
|
|
AST = std::move(NewAST);
|
|
|
|
return Diagnostics;
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
const std::shared_ptr<const PreambleData> &CppFile::getPreamble() const {
|
|
|
|
return Preamble;
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
|
2018-02-09 18:17:23 +08:00
|
|
|
ParsedAST *CppFile::getAST() const {
|
|
|
|
// We could add mutable to AST instead of const_cast here, but that would also
|
|
|
|
// allow writing to AST from const methods.
|
|
|
|
return AST ? const_cast<ParsedAST *>(AST.getPointer()) : nullptr;
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
|
2018-01-25 22:32:21 +08:00
|
|
|
std::size_t CppFile::getUsedBytes() const {
|
2018-02-09 18:17:23 +08:00
|
|
|
std::size_t Total = 0;
|
|
|
|
if (AST)
|
|
|
|
Total += AST->getUsedBytes();
|
|
|
|
if (StorePreamblesInMemory && Preamble)
|
|
|
|
Total += Preamble->Preamble.getSize();
|
|
|
|
return Total;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::shared_ptr<const PreambleData>
|
|
|
|
CppFile::rebuildPreamble(CompilerInvocation &CI,
|
|
|
|
IntrusiveRefCntPtr<vfs::FileSystem> FS,
|
|
|
|
llvm::MemoryBuffer &ContentsBuffer) const {
|
|
|
|
const auto &OldPreamble = this->Preamble;
|
|
|
|
auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), &ContentsBuffer, 0);
|
|
|
|
if (OldPreamble &&
|
|
|
|
OldPreamble->Preamble.CanReuse(CI, &ContentsBuffer, Bounds, FS.get())) {
|
|
|
|
log("Reusing preamble for file " + Twine(FileName));
|
|
|
|
return OldPreamble;
|
|
|
|
}
|
|
|
|
log("Preamble for file " + Twine(FileName) +
|
|
|
|
" cannot be reused. Attempting to rebuild it.");
|
|
|
|
|
|
|
|
trace::Span Tracer("Preamble");
|
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
|
|
|
std::vector<DiagWithFixIts> PreambleDiags;
|
|
|
|
StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
|
|
|
|
IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
|
|
|
|
CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
|
|
|
|
&PreambleDiagnosticsConsumer, false);
|
|
|
|
|
|
|
|
// Skip function bodies when building the preamble to speed up building
|
|
|
|
// the preamble and make it smaller.
|
|
|
|
assert(!CI.getFrontendOpts().SkipFunctionBodies);
|
|
|
|
CI.getFrontendOpts().SkipFunctionBodies = true;
|
|
|
|
|
|
|
|
CppFilePreambleCallbacks SerializedDeclsCollector;
|
|
|
|
auto BuiltPreamble = PrecompiledPreamble::Build(
|
|
|
|
CI, &ContentsBuffer, Bounds, *PreambleDiagsEngine, FS, PCHs,
|
|
|
|
/*StoreInMemory=*/StorePreamblesInMemory, SerializedDeclsCollector);
|
|
|
|
|
|
|
|
// When building the AST for the main file, we do want the function
|
|
|
|
// bodies.
|
|
|
|
CI.getFrontendOpts().SkipFunctionBodies = false;
|
|
|
|
|
|
|
|
if (BuiltPreamble) {
|
|
|
|
log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
|
|
|
|
" for file " + Twine(FileName));
|
|
|
|
|
|
|
|
return std::make_shared<PreambleData>(
|
|
|
|
std::move(*BuiltPreamble),
|
|
|
|
SerializedDeclsCollector.takeTopLevelDeclIDs(),
|
|
|
|
std::move(PreambleDiags));
|
2017-08-01 23:51:38 +08:00
|
|
|
} else {
|
2018-02-09 18:17:23 +08:00
|
|
|
log("Could not build a preamble for file " + Twine(FileName));
|
|
|
|
return nullptr;
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
}
|
2017-11-09 19:30:04 +08:00
|
|
|
|
|
|
|
SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
|
|
|
|
const Position &Pos,
|
|
|
|
const FileEntry *FE) {
|
|
|
|
// The language server protocol uses zero-based line and column numbers.
|
|
|
|
// Clang uses one-based numbers.
|
|
|
|
|
|
|
|
const ASTContext &AST = Unit.getASTContext();
|
|
|
|
const SourceManager &SourceMgr = AST.getSourceManager();
|
|
|
|
|
|
|
|
SourceLocation InputLocation =
|
|
|
|
getMacroArgExpandedLocation(SourceMgr, FE, Pos);
|
|
|
|
if (Pos.character == 0) {
|
|
|
|
return InputLocation;
|
|
|
|
}
|
|
|
|
|
|
|
|
// This handle cases where the position is in the middle of a token or right
|
|
|
|
// after the end of a token. In theory we could just use GetBeginningOfToken
|
|
|
|
// to find the start of the token at the input position, but this doesn't
|
|
|
|
// work when right after the end, i.e. foo|.
|
2018-02-07 04:08:23 +08:00
|
|
|
// So try to go back by one and see if we're still inside an identifier
|
2017-11-09 19:30:04 +08:00
|
|
|
// token. If so, Take the beginning of this token.
|
|
|
|
// (It should be the same identifier because you can't have two adjacent
|
|
|
|
// identifiers without another token in between.)
|
|
|
|
SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
|
|
|
|
SourceMgr, FE, Position{Pos.line, Pos.character - 1});
|
|
|
|
Token Result;
|
|
|
|
if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
|
|
|
|
AST.getLangOpts(), false)) {
|
|
|
|
// getRawToken failed, just use InputLocation.
|
|
|
|
return InputLocation;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Result.is(tok::raw_identifier)) {
|
|
|
|
return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
|
|
|
|
AST.getLangOpts());
|
|
|
|
}
|
|
|
|
|
|
|
|
return InputLocation;
|
|
|
|
}
|