2018-08-15 00:03:32 +08:00
|
|
|
//===--- ClangdUnit.cpp ------------------------------------------*- C++-*-===//
|
2017-05-16 17:38:59 +08:00
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
2018-08-15 00:03:32 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2017-05-16 17:38:59 +08:00
|
|
|
|
|
|
|
#include "ClangdUnit.h"
|
2017-12-04 21:49:59 +08:00
|
|
|
#include "Compiler.h"
|
2018-03-12 23:28:22 +08:00
|
|
|
#include "Diagnostics.h"
|
2017-09-20 18:46:58 +08:00
|
|
|
#include "Logger.h"
|
2018-03-12 23:28:22 +08:00
|
|
|
#include "SourceCode.h"
|
2017-11-02 17:21:51 +08:00
|
|
|
#include "Trace.h"
|
2018-05-24 23:50:15 +08:00
|
|
|
#include "clang/AST/ASTContext.h"
|
|
|
|
#include "clang/Basic/LangOptions.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"
|
2018-07-09 19:33:31 +08:00
|
|
|
#include "clang/Lex/PreprocessorOptions.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-02-20 02:18:49 +08:00
|
|
|
bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
|
|
|
|
const tooling::CompileCommand &RHS) {
|
|
|
|
// We don't check for Output, it should not matter to clangd.
|
|
|
|
return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
|
|
|
|
llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
|
|
|
|
}
|
|
|
|
|
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:
|
2018-06-06 00:30:25 +08:00
|
|
|
DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
|
2017-07-21 21:29:29 +08:00
|
|
|
: TopLevelDecls(TopLevelDecls) {}
|
|
|
|
|
|
|
|
bool HandleTopLevelDecl(DeclGroupRef DG) override {
|
2018-06-06 00:30:25 +08:00
|
|
|
for (Decl *D : DG) {
|
2017-07-21 21:29:29 +08:00
|
|
|
// ObjCMethodDecl are not actually top-level decls.
|
|
|
|
if (isa<ObjCMethodDecl>(D))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
TopLevelDecls.push_back(D);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2018-06-06 00:30:25 +08:00
|
|
|
std::vector<Decl *> &TopLevelDecls;
|
2017-07-21 21:29:29 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
class ClangdFrontendAction : public SyntaxOnlyAction {
|
|
|
|
public:
|
2018-06-06 00:30:25 +08:00
|
|
|
std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
|
2017-07-21 21:29:29 +08:00
|
|
|
|
|
|
|
protected:
|
|
|
|
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
|
|
|
|
StringRef InFile) override {
|
|
|
|
return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2018-06-06 00:30:25 +08:00
|
|
|
std::vector<Decl *> TopLevelDecls;
|
2017-07-21 21:29:29 +08:00
|
|
|
};
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
class CppFilePreambleCallbacks : public PreambleCallbacks {
|
2017-07-21 21:29:29 +08:00
|
|
|
public:
|
2018-05-24 23:50:15 +08:00
|
|
|
CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
|
|
|
|
: File(File), ParsedCallback(ParsedCallback) {}
|
|
|
|
|
2018-07-03 16:09:29 +08:00
|
|
|
IncludeStructure takeIncludes() { return std::move(Includes); }
|
2018-02-21 10:39:08 +08:00
|
|
|
|
2018-05-24 23:50:15 +08:00
|
|
|
void AfterExecute(CompilerInstance &CI) override {
|
|
|
|
if (!ParsedCallback)
|
|
|
|
return;
|
|
|
|
trace::Span Tracer("Running PreambleCallback");
|
2018-09-04 00:37:59 +08:00
|
|
|
ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr());
|
2018-05-24 23:50:15 +08:00
|
|
|
}
|
|
|
|
|
2018-02-21 10:39:08 +08:00
|
|
|
void BeforeExecute(CompilerInstance &CI) override {
|
|
|
|
SourceMgr = &CI.getSourceManager();
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<PPCallbacks> createPPCallbacks() override {
|
|
|
|
assert(SourceMgr && "SourceMgr must be set at this point");
|
2018-07-03 16:09:29 +08:00
|
|
|
return collectIncludeStructureCallback(*SourceMgr, &Includes);
|
2018-02-21 10:39:08 +08:00
|
|
|
}
|
|
|
|
|
2017-07-21 21:29:29 +08:00
|
|
|
private:
|
2018-05-24 23:50:15 +08:00
|
|
|
PathRef File;
|
|
|
|
PreambleParsedCallback ParsedCallback;
|
2018-07-03 16:09:29 +08:00
|
|
|
IncludeStructure Includes;
|
2018-02-21 10:39:08 +08:00
|
|
|
SourceManager *SourceMgr = nullptr;
|
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>
|
2018-07-26 20:05:31 +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) {
|
2018-05-28 20:11:37 +08:00
|
|
|
assert(CI);
|
|
|
|
// Command-line parsing sets DisableFree to true by default, but we don't want
|
|
|
|
// to leak memory in clangd.
|
|
|
|
CI->getFrontendOpts().DisableFree = false;
|
2017-11-24 21:04:21 +08:00
|
|
|
const PrecompiledPreamble *PreamblePCH =
|
|
|
|
Preamble ? &Preamble->Preamble : nullptr;
|
2018-03-12 23:28:22 +08:00
|
|
|
|
|
|
|
StoreDiags ASTDiags;
|
|
|
|
auto Clang =
|
|
|
|
prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
|
|
|
|
std::move(PCHs), std::move(VFS), ASTDiags);
|
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] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
log("BeginSourceFile() failed when building AST for {0}",
|
[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
|
|
|
MainInput.getFile());
|
2017-07-21 21:29:29 +08:00
|
|
|
return llvm::None;
|
|
|
|
}
|
2018-02-21 10:39:08 +08:00
|
|
|
|
|
|
|
// Copy over the includes from the preamble, then combine with the
|
|
|
|
// non-preamble includes below.
|
2018-07-03 16:09:29 +08:00
|
|
|
auto Includes = Preamble ? Preamble->Includes : IncludeStructure{};
|
|
|
|
Clang->getPreprocessor().addPPCallbacks(
|
|
|
|
collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
|
2018-02-21 10:39:08 +08:00
|
|
|
|
2017-09-20 15:24:15 +08:00
|
|
|
if (!Action->Execute())
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
log("Execute() failed when building AST for {0}", 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);
|
2018-03-12 23:28:22 +08:00
|
|
|
// CompilerInstance won't run this callback, do it directly.
|
|
|
|
ASTDiags.EndSourceFile();
|
2017-07-21 21:29:29 +08:00
|
|
|
|
2018-06-06 00:30:25 +08:00
|
|
|
std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::vector<Diag> Diags = ASTDiags.take();
|
|
|
|
// Add diagnostics from the preamble, if any.
|
|
|
|
if (Preamble)
|
|
|
|
Diags.insert(Diags.begin(), Preamble->Diags.begin(), Preamble->Diags.end());
|
2017-11-24 21:04:21 +08:00
|
|
|
return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::move(ParsedDecls), std::move(Diags),
|
2018-07-03 16:09:29 +08:00
|
|
|
std::move(Includes));
|
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();
|
|
|
|
}
|
|
|
|
|
2018-06-06 00:30:25 +08:00
|
|
|
ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
|
2018-05-28 20:23:17 +08:00
|
|
|
return LocalTopLevelDecls;
|
2017-07-21 21:29:29 +08:00
|
|
|
}
|
|
|
|
|
2018-03-12 23:28:22 +08:00
|
|
|
const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
|
2017-07-21 21:29:29 +08:00
|
|
|
|
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
|
2018-03-12 23:28:22 +08:00
|
|
|
// Message and Fixes inside each diagnostic.
|
2018-06-01 22:44:57 +08:00
|
|
|
std::size_t Total =
|
|
|
|
::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
|
|
|
|
|
|
|
|
// FIXME: the rest of the function is almost a direct copy-paste from
|
|
|
|
// libclang's clang_getCXTUResourceUsage. We could share the implementation.
|
|
|
|
|
|
|
|
// Sum up variaous allocators inside the ast context and the preprocessor.
|
|
|
|
Total += AST.getASTAllocatedMemory();
|
|
|
|
Total += AST.getSideTableAllocatedMemory();
|
|
|
|
Total += AST.Idents.getAllocator().getTotalMemory();
|
|
|
|
Total += AST.Selectors.getTotalMemory();
|
|
|
|
|
|
|
|
Total += AST.getSourceManager().getContentCacheSize();
|
|
|
|
Total += AST.getSourceManager().getDataStructureSizes();
|
|
|
|
Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
|
|
|
|
|
|
|
|
if (ExternalASTSource *Ext = AST.getExternalSource())
|
|
|
|
Total += Ext->getMemoryBufferSizes().malloc_bytes;
|
|
|
|
|
|
|
|
const Preprocessor &PP = getPreprocessor();
|
|
|
|
Total += PP.getTotalMemory();
|
|
|
|
if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
|
|
|
|
Total += PRec->getTotalMemory();
|
|
|
|
Total += PP.getHeaderSearchInfo().getTotalMemory();
|
|
|
|
|
|
|
|
return Total;
|
2018-01-25 22:32:21 +08:00
|
|
|
}
|
|
|
|
|
2018-07-03 16:09:29 +08:00
|
|
|
const IncludeStructure &ParsedAST::getIncludeStructure() const {
|
|
|
|
return Includes;
|
2018-02-21 10:39:08 +08:00
|
|
|
}
|
|
|
|
|
2017-11-24 21:04:21 +08:00
|
|
|
PreambleData::PreambleData(PrecompiledPreamble Preamble,
|
2018-07-03 16:09:29 +08:00
|
|
|
std::vector<Diag> Diags, IncludeStructure Includes)
|
2018-05-28 20:23:17 +08:00
|
|
|
: Preamble(std::move(Preamble)), Diags(std::move(Diags)),
|
2018-07-03 16:09:29 +08:00
|
|
|
Includes(std::move(Includes)) {}
|
2017-11-24 21:04:21 +08:00
|
|
|
|
|
|
|
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,
|
2018-06-06 00:30:25 +08:00
|
|
|
std::vector<Decl *> LocalTopLevelDecls,
|
2018-07-03 16:09:29 +08:00
|
|
|
std::vector<Diag> Diags, IncludeStructure Includes)
|
2017-11-24 21:04:21 +08:00
|
|
|
: Preamble(std::move(Preamble)), Clang(std::move(Clang)),
|
|
|
|
Action(std::move(Action)), Diags(std::move(Diags)),
|
2018-05-28 20:23:17 +08:00
|
|
|
LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
|
2018-07-03 16:09:29 +08:00
|
|
|
Includes(std::move(Includes)) {
|
2017-07-21 21:29:29 +08:00
|
|
|
assert(this->Clang);
|
|
|
|
assert(this->Action);
|
|
|
|
}
|
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::unique_ptr<CompilerInvocation>
|
|
|
|
clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
|
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-14 01:15:06 +08:00
|
|
|
if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
log("Couldn't set working directory when creating compiler invocation.");
|
|
|
|
// We proceed anyway, our lit-tests rely on results for non-existing working
|
|
|
|
// dirs.
|
2018-02-09 18:17:23 +08:00
|
|
|
}
|
2017-08-01 23:51:38 +08:00
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
// FIXME(ibiryukov): store diagnostics from CommandLine when we start
|
|
|
|
// reporting them.
|
|
|
|
IgnoreDiagnostics IgnoreDiagnostics;
|
|
|
|
IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
|
|
|
|
CompilerInstance::createDiagnostics(new DiagnosticOptions,
|
|
|
|
&IgnoreDiagnostics, false);
|
|
|
|
std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
|
|
|
|
ArgStrs, CommandLineDiagsEngine, Inputs.FS);
|
|
|
|
if (!CI)
|
|
|
|
return nullptr;
|
|
|
|
// createInvocationFromCommandLine sets DisableFree.
|
|
|
|
CI->getFrontendOpts().DisableFree = false;
|
|
|
|
CI->getLangOpts()->CommentOpts.ParseAllComments = true;
|
|
|
|
return CI;
|
2018-02-09 18:17:23 +08:00
|
|
|
}
|
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::shared_ptr<const PreambleData> clangd::buildPreamble(
|
|
|
|
PathRef FileName, CompilerInvocation &CI,
|
|
|
|
std::shared_ptr<const PreambleData> OldPreamble,
|
|
|
|
const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
|
|
|
|
std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
|
|
|
|
PreambleParsedCallback PreambleCallback) {
|
|
|
|
// Note that we don't need to copy the input contents, preamble can live
|
|
|
|
// without those.
|
|
|
|
auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
|
|
|
|
auto Bounds =
|
|
|
|
ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
|
|
|
|
|
|
|
|
if (OldPreamble &&
|
|
|
|
compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
|
|
|
|
OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
|
|
|
|
Inputs.FS.get())) {
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
vlog("Reusing preamble for file {0}", Twine(FileName));
|
2018-02-09 18:17:23 +08:00
|
|
|
return OldPreamble;
|
|
|
|
}
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
vlog("Preamble for file {0} cannot be reused. Attempting to rebuild it.",
|
|
|
|
FileName);
|
2018-02-09 18:17:23 +08:00
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
trace::Span Tracer("BuildPreamble");
|
2018-02-09 18:17:23 +08:00
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
2018-03-12 23:28:22 +08:00
|
|
|
StoreDiags PreambleDiagnostics;
|
2018-02-09 18:17:23 +08:00
|
|
|
IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
|
|
|
|
CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
|
2018-03-12 23:28:22 +08:00
|
|
|
&PreambleDiagnostics, false);
|
2018-02-09 18:17:23 +08:00
|
|
|
|
|
|
|
// 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;
|
2018-07-09 19:33:31 +08:00
|
|
|
// We don't want to write comment locations into PCH. They are racy and slow
|
|
|
|
// to read back. We rely on dynamic index for the comments instead.
|
|
|
|
CI.getPreprocessorOpts().WriteCommentListToPCH = false;
|
2018-02-09 18:17:23 +08:00
|
|
|
|
2018-05-24 23:50:15 +08:00
|
|
|
CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
|
|
|
|
log("Couldn't set working directory when building the preamble.");
|
|
|
|
// We proceed anyway, our lit-tests rely on results for non-existing working
|
|
|
|
// dirs.
|
|
|
|
}
|
2018-02-09 18:17:23 +08:00
|
|
|
auto BuiltPreamble = PrecompiledPreamble::Build(
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS, PCHs,
|
|
|
|
StoreInMemory, SerializedDeclsCollector);
|
2018-02-09 18:17:23 +08:00
|
|
|
|
|
|
|
// When building the AST for the main file, we do want the function
|
|
|
|
// bodies.
|
|
|
|
CI.getFrontendOpts().SkipFunctionBodies = false;
|
|
|
|
|
|
|
|
if (BuiltPreamble) {
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
vlog("Built preamble of size {0} for file {1}", BuiltPreamble->getSize(),
|
|
|
|
FileName);
|
2018-02-09 18:17:23 +08:00
|
|
|
return std::make_shared<PreambleData>(
|
2018-05-28 20:23:17 +08:00
|
|
|
std::move(*BuiltPreamble), PreambleDiagnostics.take(),
|
2018-07-03 16:09:29 +08:00
|
|
|
SerializedDeclsCollector.takeIncludes());
|
2017-08-01 23:51:38 +08:00
|
|
|
} else {
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
elog("Could not build a preamble for file {0}", FileName);
|
2018-02-09 18:17:23 +08:00
|
|
|
return nullptr;
|
2017-08-01 23:51:38 +08:00
|
|
|
}
|
|
|
|
}
|
2017-11-09 19:30:04 +08:00
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
llvm::Optional<ParsedAST> clangd::buildAST(
|
|
|
|
PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
|
|
|
|
const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
|
|
|
|
std::shared_ptr<PCHContainerOperations> PCHs) {
|
|
|
|
trace::Span Tracer("BuildAST");
|
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
|
|
|
|
|
|
|
if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
|
|
|
|
log("Couldn't set working directory when building the preamble.");
|
|
|
|
// We proceed anyway, our lit-tests rely on results for non-existing working
|
|
|
|
// dirs.
|
|
|
|
}
|
|
|
|
|
2018-07-26 20:05:31 +08:00
|
|
|
return ParsedAST::build(
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
|
|
|
|
llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
|
|
|
|
}
|
|
|
|
|
2017-11-09 19:30:04 +08:00
|
|
|
SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
|
|
|
|
const Position &Pos,
|
[clangd] Fix unicode handling, using UTF-16 where LSP requires it.
Summary:
The Language Server Protocol unfortunately mandates that locations in files
be represented by line/column pairs, where the "column" is actually an index
into the UTF-16-encoded text of the line.
(This is because VSCode is written in JavaScript, which is UTF-16-native).
Internally clangd treats source files at UTF-8, the One True Encoding, and
generally deals with byte offsets (though there are exceptions).
Before this patch, conversions between offsets and LSP Position pretended
that Position.character was UTF-8 bytes, which is only true for ASCII lines.
Now we examine the text to convert correctly (but don't actually need to
transcode it, due to some nice details of the encodings).
The updated functions in SourceCode are the blessed way to interact with
the Position.character field, and anything else is likely to be wrong.
So I also updated the other accesses:
- CodeComplete needs a "clang-style" line/column, with column in utf-8 bytes.
This is now converted via Position -> offset -> clang line/column
(a new function is added to SourceCode.h for the second conversion).
- getBeginningOfIdentifier skipped backwards in UTF-16 space, which is will
behave badly when it splits a surrogate pair. Skipping backwards in UTF-8
coordinates gives the lexer a fighting chance of getting this right.
While here, I clarified(?) the logic comments, fixed a bug with identifiers
containing digits, simplified the signature slightly and added a test.
This seems likely to cause problems with editors that have the same bug, and
treat the protocol as if columns are UTF-8 bytes. But we can find and fix those.
Reviewers: hokein
Subscribers: klimek, ilya-biryukov, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D46035
llvm-svn: 331029
2018-04-27 19:59:28 +08:00
|
|
|
const FileID FID) {
|
2017-11-09 19:30:04 +08:00
|
|
|
const ASTContext &AST = Unit.getASTContext();
|
|
|
|
const SourceManager &SourceMgr = AST.getSourceManager();
|
[clangd] Fix unicode handling, using UTF-16 where LSP requires it.
Summary:
The Language Server Protocol unfortunately mandates that locations in files
be represented by line/column pairs, where the "column" is actually an index
into the UTF-16-encoded text of the line.
(This is because VSCode is written in JavaScript, which is UTF-16-native).
Internally clangd treats source files at UTF-8, the One True Encoding, and
generally deals with byte offsets (though there are exceptions).
Before this patch, conversions between offsets and LSP Position pretended
that Position.character was UTF-8 bytes, which is only true for ASCII lines.
Now we examine the text to convert correctly (but don't actually need to
transcode it, due to some nice details of the encodings).
The updated functions in SourceCode are the blessed way to interact with
the Position.character field, and anything else is likely to be wrong.
So I also updated the other accesses:
- CodeComplete needs a "clang-style" line/column, with column in utf-8 bytes.
This is now converted via Position -> offset -> clang line/column
(a new function is added to SourceCode.h for the second conversion).
- getBeginningOfIdentifier skipped backwards in UTF-16 space, which is will
behave badly when it splits a surrogate pair. Skipping backwards in UTF-8
coordinates gives the lexer a fighting chance of getting this right.
While here, I clarified(?) the logic comments, fixed a bug with identifiers
containing digits, simplified the signature slightly and added a test.
This seems likely to cause problems with editors that have the same bug, and
treat the protocol as if columns are UTF-8 bytes. But we can find and fix those.
Reviewers: hokein
Subscribers: klimek, ilya-biryukov, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D46035
llvm-svn: 331029
2018-04-27 19:59:28 +08:00
|
|
|
auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
|
|
|
|
if (!Offset) {
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
log("getBeginningOfIdentifier: {0}", Offset.takeError());
|
[clangd] Fix unicode handling, using UTF-16 where LSP requires it.
Summary:
The Language Server Protocol unfortunately mandates that locations in files
be represented by line/column pairs, where the "column" is actually an index
into the UTF-16-encoded text of the line.
(This is because VSCode is written in JavaScript, which is UTF-16-native).
Internally clangd treats source files at UTF-8, the One True Encoding, and
generally deals with byte offsets (though there are exceptions).
Before this patch, conversions between offsets and LSP Position pretended
that Position.character was UTF-8 bytes, which is only true for ASCII lines.
Now we examine the text to convert correctly (but don't actually need to
transcode it, due to some nice details of the encodings).
The updated functions in SourceCode are the blessed way to interact with
the Position.character field, and anything else is likely to be wrong.
So I also updated the other accesses:
- CodeComplete needs a "clang-style" line/column, with column in utf-8 bytes.
This is now converted via Position -> offset -> clang line/column
(a new function is added to SourceCode.h for the second conversion).
- getBeginningOfIdentifier skipped backwards in UTF-16 space, which is will
behave badly when it splits a surrogate pair. Skipping backwards in UTF-8
coordinates gives the lexer a fighting chance of getting this right.
While here, I clarified(?) the logic comments, fixed a bug with identifiers
containing digits, simplified the signature slightly and added a test.
This seems likely to cause problems with editors that have the same bug, and
treat the protocol as if columns are UTF-8 bytes. But we can find and fix those.
Reviewers: hokein
Subscribers: klimek, ilya-biryukov, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D46035
llvm-svn: 331029
2018-04-27 19:59:28 +08:00
|
|
|
return SourceLocation();
|
2017-11-09 19:30:04 +08:00
|
|
|
}
|
[clangd] Fix unicode handling, using UTF-16 where LSP requires it.
Summary:
The Language Server Protocol unfortunately mandates that locations in files
be represented by line/column pairs, where the "column" is actually an index
into the UTF-16-encoded text of the line.
(This is because VSCode is written in JavaScript, which is UTF-16-native).
Internally clangd treats source files at UTF-8, the One True Encoding, and
generally deals with byte offsets (though there are exceptions).
Before this patch, conversions between offsets and LSP Position pretended
that Position.character was UTF-8 bytes, which is only true for ASCII lines.
Now we examine the text to convert correctly (but don't actually need to
transcode it, due to some nice details of the encodings).
The updated functions in SourceCode are the blessed way to interact with
the Position.character field, and anything else is likely to be wrong.
So I also updated the other accesses:
- CodeComplete needs a "clang-style" line/column, with column in utf-8 bytes.
This is now converted via Position -> offset -> clang line/column
(a new function is added to SourceCode.h for the second conversion).
- getBeginningOfIdentifier skipped backwards in UTF-16 space, which is will
behave badly when it splits a surrogate pair. Skipping backwards in UTF-8
coordinates gives the lexer a fighting chance of getting this right.
While here, I clarified(?) the logic comments, fixed a bug with identifiers
containing digits, simplified the signature slightly and added a test.
This seems likely to cause problems with editors that have the same bug, and
treat the protocol as if columns are UTF-8 bytes. But we can find and fix those.
Reviewers: hokein
Subscribers: klimek, ilya-biryukov, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D46035
llvm-svn: 331029
2018-04-27 19:59:28 +08:00
|
|
|
SourceLocation InputLoc = SourceMgr.getComposedLoc(FID, *Offset);
|
|
|
|
|
|
|
|
// GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
|
|
|
|
// if the cursor is at the end of the identifier.
|
|
|
|
// Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
|
|
|
|
// 1) at the beginning of an identifier, we'll be looking at something
|
|
|
|
// that isn't an identifier.
|
|
|
|
// 2) at the middle or end of an identifier, we get the identifier.
|
|
|
|
// 3) anywhere outside an identifier, we'll get some non-identifier thing.
|
|
|
|
// We can't actually distinguish cases 1 and 3, but returning the original
|
|
|
|
// location is correct for both!
|
|
|
|
if (*Offset == 0) // Case 1 or 3.
|
|
|
|
return SourceMgr.getMacroArgExpandedLocation(InputLoc);
|
|
|
|
SourceLocation Before =
|
|
|
|
SourceMgr.getMacroArgExpandedLocation(InputLoc.getLocWithOffset(-1));
|
|
|
|
Before = Lexer::GetBeginningOfToken(Before, SourceMgr, AST.getLangOpts());
|
|
|
|
Token Tok;
|
|
|
|
if (Before.isValid() &&
|
|
|
|
!Lexer::getRawToken(Before, Tok, SourceMgr, AST.getLangOpts(), false) &&
|
|
|
|
Tok.is(tok::raw_identifier))
|
|
|
|
return Before; // Case 2.
|
|
|
|
return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
|
2017-11-09 19:30:04 +08:00
|
|
|
}
|