2019-09-04 15:35:00 +08:00
|
|
|
//===--- Preamble.cpp - Reusing expensive parts of the AST ----------------===//
|
|
|
|
//
|
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "Preamble.h"
|
2020-03-11 23:34:01 +08:00
|
|
|
#include "Compiler.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "Headers.h"
|
2020-04-23 23:44:51 +08:00
|
|
|
#include "SourceCode.h"
|
[clangd] Move non-clang base pieces into separate support/ lib. NFCI
Summary:
This enforces layering, reduces a sprawling clangd/ directory, and makes life
easier for embedders.
Reviewers: kbobyrev
Subscribers: mgorny, ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D79014
2020-04-28 23:49:17 +08:00
|
|
|
#include "support/Logger.h"
|
2020-06-17 17:53:32 +08:00
|
|
|
#include "support/ThreadsafeFS.h"
|
[clangd] Move non-clang base pieces into separate support/ lib. NFCI
Summary:
This enforces layering, reduces a sprawling clangd/ directory, and makes life
easier for embedders.
Reviewers: kbobyrev
Subscribers: mgorny, ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D79014
2020-04-28 23:49:17 +08:00
|
|
|
#include "support/Trace.h"
|
2020-06-09 21:46:35 +08:00
|
|
|
#include "clang/AST/DeclTemplate.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "clang/Basic/Diagnostic.h"
|
2021-04-15 01:28:14 +08:00
|
|
|
#include "clang/Basic/DiagnosticLex.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "clang/Basic/LangOptions.h"
|
2019-09-04 15:35:00 +08:00
|
|
|
#include "clang/Basic/SourceLocation.h"
|
2020-05-14 18:20:33 +08:00
|
|
|
#include "clang/Basic/SourceManager.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "clang/Basic/TokenKinds.h"
|
|
|
|
#include "clang/Frontend/CompilerInvocation.h"
|
|
|
|
#include "clang/Frontend/FrontendActions.h"
|
|
|
|
#include "clang/Lex/Lexer.h"
|
2019-09-04 15:35:00 +08:00
|
|
|
#include "clang/Lex/PPCallbacks.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "clang/Lex/Preprocessor.h"
|
2019-09-04 15:35:00 +08:00
|
|
|
#include "clang/Lex/PreprocessorOptions.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "clang/Tooling/CompilationDatabase.h"
|
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
2020-04-02 16:53:45 +08:00
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/DenseSet.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "llvm/ADT/IntrusiveRefCntPtr.h"
|
2020-06-16 18:16:24 +08:00
|
|
|
#include "llvm/ADT/None.h"
|
|
|
|
#include "llvm/ADT/Optional.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
|
|
|
#include "llvm/ADT/SmallString.h"
|
2020-04-23 23:44:51 +08:00
|
|
|
#include "llvm/ADT/StringExtras.h"
|
2020-04-02 16:53:23 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
|
|
|
#include "llvm/ADT/StringSet.h"
|
|
|
|
#include "llvm/Support/Error.h"
|
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
|
|
|
#include "llvm/Support/FormatVariadic.h"
|
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
|
|
|
#include "llvm/Support/Path.h"
|
|
|
|
#include "llvm/Support/VirtualFileSystem.h"
|
|
|
|
#include "llvm/Support/raw_ostream.h"
|
|
|
|
#include <iterator>
|
|
|
|
#include <memory>
|
|
|
|
#include <string>
|
|
|
|
#include <system_error>
|
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2019-09-04 15:35:00 +08:00
|
|
|
|
|
|
|
namespace clang {
|
|
|
|
namespace clangd {
|
|
|
|
namespace {
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
|
2019-09-04 15:35:00 +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);
|
|
|
|
}
|
|
|
|
|
|
|
|
class CppFilePreambleCallbacks : public PreambleCallbacks {
|
|
|
|
public:
|
|
|
|
CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
|
2019-09-24 19:14:06 +08:00
|
|
|
: File(File), ParsedCallback(ParsedCallback) {}
|
2019-09-04 15:35:00 +08:00
|
|
|
|
|
|
|
IncludeStructure takeIncludes() { return std::move(Includes); }
|
|
|
|
|
2019-09-24 19:14:06 +08:00
|
|
|
MainFileMacros takeMacros() { return std::move(Macros); }
|
2019-09-04 15:35:00 +08:00
|
|
|
|
|
|
|
CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
|
|
|
|
|
|
|
|
void AfterExecute(CompilerInstance &CI) override {
|
|
|
|
if (!ParsedCallback)
|
|
|
|
return;
|
|
|
|
trace::Span Tracer("Running PreambleCallback");
|
|
|
|
ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
|
|
|
|
}
|
|
|
|
|
|
|
|
void BeforeExecute(CompilerInstance &CI) override {
|
2019-09-09 23:32:51 +08:00
|
|
|
CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
|
2019-09-24 19:14:06 +08:00
|
|
|
LangOpts = &CI.getLangOpts();
|
2019-09-04 15:35:00 +08:00
|
|
|
SourceMgr = &CI.getSourceManager();
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<PPCallbacks> createPPCallbacks() override {
|
2019-09-24 19:14:06 +08:00
|
|
|
assert(SourceMgr && LangOpts &&
|
|
|
|
"SourceMgr and LangOpts must be set at this point");
|
|
|
|
|
2019-09-04 15:35:00 +08:00
|
|
|
return std::make_unique<PPChainedCallbacks>(
|
|
|
|
collectIncludeStructureCallback(*SourceMgr, &Includes),
|
2020-03-01 23:05:12 +08:00
|
|
|
std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros));
|
2019-09-04 15:35:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
CommentHandler *getCommentHandler() override {
|
|
|
|
IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes);
|
|
|
|
return IWYUHandler.get();
|
|
|
|
}
|
|
|
|
|
2020-06-09 21:46:35 +08:00
|
|
|
bool shouldSkipFunctionBody(Decl *D) override {
|
|
|
|
// Generally we skip function bodies in preambles for speed.
|
|
|
|
// We can make exceptions for functions that are cheap to parse and
|
|
|
|
// instantiate, widely used, and valuable (e.g. commonly produce errors).
|
|
|
|
if (const auto *FT = llvm::dyn_cast<clang::FunctionTemplateDecl>(D)) {
|
|
|
|
if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
|
|
|
|
// std::make_unique is trivial, and we diagnose bad constructor calls.
|
|
|
|
if (II->isStr("make_unique") && FT->isInStdNamespace())
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-09-04 15:35:00 +08:00
|
|
|
private:
|
|
|
|
PathRef File;
|
|
|
|
PreambleParsedCallback ParsedCallback;
|
|
|
|
IncludeStructure Includes;
|
|
|
|
CanonicalIncludes CanonIncludes;
|
2019-09-24 19:14:06 +08:00
|
|
|
MainFileMacros Macros;
|
2019-09-04 15:35:00 +08:00
|
|
|
std::unique_ptr<CommentHandler> IWYUHandler = nullptr;
|
2019-09-24 19:14:06 +08:00
|
|
|
const clang::LangOptions *LangOpts = nullptr;
|
|
|
|
const SourceManager *SourceMgr = nullptr;
|
2019-09-04 15:35:00 +08:00
|
|
|
};
|
|
|
|
|
2020-05-14 18:20:33 +08:00
|
|
|
// Represents directives other than includes, where basic textual information is
|
|
|
|
// enough.
|
|
|
|
struct TextualPPDirective {
|
|
|
|
unsigned DirectiveLine;
|
|
|
|
// Full text that's representing the directive, including the `#`.
|
|
|
|
std::string Text;
|
|
|
|
|
|
|
|
bool operator==(const TextualPPDirective &RHS) const {
|
|
|
|
return std::tie(DirectiveLine, Text) ==
|
|
|
|
std::tie(RHS.DirectiveLine, RHS.Text);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
// Formats a PP directive consisting of Prefix (e.g. "#define ") and Body ("X
|
|
|
|
// 10"). The formatting is copied so that the tokens in Body have PresumedLocs
|
|
|
|
// with correct columns and lines.
|
|
|
|
std::string spellDirective(llvm::StringRef Prefix,
|
|
|
|
CharSourceRange DirectiveRange,
|
|
|
|
const LangOptions &LangOpts, const SourceManager &SM,
|
|
|
|
unsigned &DirectiveLine) {
|
|
|
|
std::string SpelledDirective;
|
|
|
|
llvm::raw_string_ostream OS(SpelledDirective);
|
|
|
|
OS << Prefix;
|
|
|
|
|
|
|
|
// Make sure DirectiveRange is a char range and doesn't contain macro ids.
|
|
|
|
DirectiveRange = SM.getExpansionRange(DirectiveRange);
|
|
|
|
if (DirectiveRange.isTokenRange()) {
|
|
|
|
DirectiveRange.setEnd(
|
|
|
|
Lexer::getLocForEndOfToken(DirectiveRange.getEnd(), 0, SM, LangOpts));
|
|
|
|
}
|
|
|
|
|
|
|
|
auto DecompLoc = SM.getDecomposedLoc(DirectiveRange.getBegin());
|
|
|
|
DirectiveLine = SM.getLineNumber(DecompLoc.first, DecompLoc.second);
|
|
|
|
auto TargetColumn = SM.getColumnNumber(DecompLoc.first, DecompLoc.second) - 1;
|
|
|
|
|
|
|
|
// Pad with spaces before DirectiveRange to make sure it will be on right
|
|
|
|
// column when patched.
|
|
|
|
if (Prefix.size() <= TargetColumn) {
|
|
|
|
// There is enough space for Prefix and space before directive, use it.
|
|
|
|
// We try to squeeze the Prefix into the same line whenever we can, as
|
|
|
|
// putting onto a separate line won't work at the beginning of the file.
|
|
|
|
OS << std::string(TargetColumn - Prefix.size(), ' ');
|
|
|
|
} else {
|
|
|
|
// Prefix was longer than the space we had. We produce e.g.:
|
|
|
|
// #line N-1
|
|
|
|
// #define \
|
|
|
|
// X 10
|
|
|
|
OS << "\\\n" << std::string(TargetColumn, ' ');
|
|
|
|
// Decrement because we put an additional line break before
|
|
|
|
// DirectiveRange.begin().
|
|
|
|
--DirectiveLine;
|
|
|
|
}
|
|
|
|
OS << toSourceCode(SM, DirectiveRange.getAsRange());
|
|
|
|
return OS.str();
|
|
|
|
}
|
|
|
|
|
2020-05-14 18:20:33 +08:00
|
|
|
// Collects #define directives inside the main file.
|
|
|
|
struct DirectiveCollector : public PPCallbacks {
|
|
|
|
DirectiveCollector(const Preprocessor &PP,
|
|
|
|
std::vector<TextualPPDirective> &TextualDirectives)
|
|
|
|
: LangOpts(PP.getLangOpts()), SM(PP.getSourceManager()),
|
|
|
|
TextualDirectives(TextualDirectives) {}
|
|
|
|
|
|
|
|
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
|
|
|
|
SrcMgr::CharacteristicKind FileType,
|
|
|
|
FileID PrevFID) override {
|
|
|
|
InMainFile = SM.isWrittenInMainFile(Loc);
|
|
|
|
}
|
|
|
|
|
|
|
|
void MacroDefined(const Token &MacroNameTok,
|
|
|
|
const MacroDirective *MD) override {
|
|
|
|
if (!InMainFile)
|
|
|
|
return;
|
|
|
|
TextualDirectives.emplace_back();
|
|
|
|
TextualPPDirective &TD = TextualDirectives.back();
|
|
|
|
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
const auto *MI = MD->getMacroInfo();
|
|
|
|
TD.Text =
|
|
|
|
spellDirective("#define ",
|
|
|
|
CharSourceRange::getTokenRange(
|
|
|
|
MI->getDefinitionLoc(), MI->getDefinitionEndLoc()),
|
|
|
|
LangOpts, SM, TD.DirectiveLine);
|
2020-05-14 18:20:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
bool InMainFile = true;
|
|
|
|
const LangOptions &LangOpts;
|
|
|
|
const SourceManager &SM;
|
|
|
|
std::vector<TextualPPDirective> &TextualDirectives;
|
|
|
|
};
|
|
|
|
|
|
|
|
struct ScannedPreamble {
|
|
|
|
std::vector<Inclusion> Includes;
|
|
|
|
std::vector<TextualPPDirective> TextualDirectives;
|
2020-06-17 03:21:45 +08:00
|
|
|
PreambleBounds Bounds = {0, false};
|
2020-05-14 18:20:33 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
/// Scans the preprocessor directives in the preamble section of the file by
|
|
|
|
/// running preprocessor over \p Contents. Returned includes do not contain
|
2020-06-18 00:09:54 +08:00
|
|
|
/// resolved paths. \p Cmd is used to build the compiler invocation, which might
|
|
|
|
/// stat/read files.
|
2020-05-14 18:20:33 +08:00
|
|
|
llvm::Expected<ScannedPreamble>
|
2020-06-18 00:09:54 +08:00
|
|
|
scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
|
|
|
|
class EmptyFS : public ThreadsafeFS {
|
2020-06-30 01:52:09 +08:00
|
|
|
private:
|
|
|
|
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override {
|
2020-06-18 00:09:54 +08:00
|
|
|
return new llvm::vfs::InMemoryFileSystem;
|
|
|
|
}
|
2020-06-05 00:26:52 +08:00
|
|
|
};
|
2020-06-18 00:09:54 +08:00
|
|
|
EmptyFS FS;
|
2020-04-02 16:53:23 +08:00
|
|
|
// Build and run Preprocessor over the preamble.
|
|
|
|
ParseInputs PI;
|
|
|
|
PI.Contents = Contents.str();
|
2020-06-18 00:09:54 +08:00
|
|
|
PI.TFS = &FS;
|
2020-04-02 16:53:23 +08:00
|
|
|
PI.CompileCommand = Cmd;
|
|
|
|
IgnoringDiagConsumer IgnoreDiags;
|
|
|
|
auto CI = buildCompilerInvocation(PI, IgnoreDiags);
|
|
|
|
if (!CI)
|
2020-09-14 17:33:12 +08:00
|
|
|
return error("failed to create compiler invocation");
|
2020-04-02 16:53:23 +08:00
|
|
|
CI->getDiagnosticOpts().IgnoreWarnings = true;
|
|
|
|
auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
|
2020-05-05 23:55:11 +08:00
|
|
|
// This means we're scanning (though not preprocessing) the preamble section
|
|
|
|
// twice. However, it's important to precisely follow the preamble bounds used
|
|
|
|
// elsewhere.
|
2020-11-06 01:43:58 +08:00
|
|
|
auto Bounds = ComputePreambleBounds(*CI->getLangOpts(), *ContentsBuffer, 0);
|
2020-05-05 23:55:11 +08:00
|
|
|
auto PreambleContents =
|
|
|
|
llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size));
|
2020-04-02 16:53:23 +08:00
|
|
|
auto Clang = prepareCompilerInstance(
|
2020-05-05 23:55:11 +08:00
|
|
|
std::move(CI), nullptr, std::move(PreambleContents),
|
2020-04-02 16:53:23 +08:00
|
|
|
// Provide an empty FS to prevent preprocessor from performing IO. This
|
|
|
|
// also implies missing resolved paths for includes.
|
2020-06-18 00:09:54 +08:00
|
|
|
FS.view(llvm::None), IgnoreDiags);
|
2020-04-02 16:53:23 +08:00
|
|
|
if (Clang->getFrontendOpts().Inputs.empty())
|
2020-09-14 17:33:12 +08:00
|
|
|
return error("compiler instance had no inputs");
|
2020-04-02 16:53:23 +08:00
|
|
|
// We are only interested in main file includes.
|
|
|
|
Clang->getPreprocessorOpts().SingleFileParseMode = true;
|
2020-05-05 23:55:11 +08:00
|
|
|
PreprocessOnlyAction Action;
|
2020-04-02 16:53:23 +08:00
|
|
|
if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
|
2020-09-14 17:33:12 +08:00
|
|
|
return error("failed BeginSourceFile");
|
2020-05-14 18:20:33 +08:00
|
|
|
const auto &SM = Clang->getSourceManager();
|
2020-04-02 16:53:23 +08:00
|
|
|
Preprocessor &PP = Clang->getPreprocessor();
|
|
|
|
IncludeStructure Includes;
|
2020-05-14 18:20:33 +08:00
|
|
|
PP.addPPCallbacks(collectIncludeStructureCallback(SM, &Includes));
|
|
|
|
ScannedPreamble SP;
|
2020-06-17 03:21:45 +08:00
|
|
|
SP.Bounds = Bounds;
|
2020-04-02 16:53:23 +08:00
|
|
|
PP.addPPCallbacks(
|
2020-05-14 18:20:33 +08:00
|
|
|
std::make_unique<DirectiveCollector>(PP, SP.TextualDirectives));
|
2020-04-02 16:53:23 +08:00
|
|
|
if (llvm::Error Err = Action.Execute())
|
|
|
|
return std::move(Err);
|
|
|
|
Action.EndSourceFile();
|
2020-05-14 18:20:33 +08:00
|
|
|
SP.Includes = std::move(Includes.MainFileIncludes);
|
|
|
|
return SP;
|
2020-04-02 16:53:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) {
|
|
|
|
switch (IncludeDirective) {
|
|
|
|
case tok::pp_include:
|
|
|
|
return "include";
|
|
|
|
case tok::pp_import:
|
|
|
|
return "import";
|
|
|
|
case tok::pp_include_next:
|
|
|
|
return "include_next";
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
llvm_unreachable("not an include directive");
|
|
|
|
}
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
|
|
|
|
// Checks whether \p FileName is a valid spelling of main file.
|
|
|
|
bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
|
|
|
|
auto FE = SM.getFileManager().getFile(FileName);
|
|
|
|
return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
|
|
|
|
}
|
|
|
|
|
2019-09-04 15:35:00 +08:00
|
|
|
} // namespace
|
|
|
|
|
2020-03-11 23:34:01 +08:00
|
|
|
PreambleData::PreambleData(const ParseInputs &Inputs,
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
PrecompiledPreamble Preamble,
|
2019-09-04 15:35:00 +08:00
|
|
|
std::vector<Diag> Diags, IncludeStructure Includes,
|
2019-09-24 19:14:06 +08:00
|
|
|
MainFileMacros Macros,
|
2019-09-04 15:35:00 +08:00
|
|
|
std::unique_ptr<PreambleFileStatusCache> StatCache,
|
|
|
|
CanonicalIncludes CanonIncludes)
|
2020-03-11 23:34:01 +08:00
|
|
|
: Version(Inputs.Version), CompileCommand(Inputs.CompileCommand),
|
|
|
|
Preamble(std::move(Preamble)), Diags(std::move(Diags)),
|
2019-09-24 19:14:06 +08:00
|
|
|
Includes(std::move(Includes)), Macros(std::move(Macros)),
|
2019-09-04 15:35:00 +08:00
|
|
|
StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) {
|
|
|
|
}
|
|
|
|
|
|
|
|
std::shared_ptr<const PreambleData>
|
2020-03-13 18:52:19 +08:00
|
|
|
buildPreamble(PathRef FileName, CompilerInvocation CI,
|
2019-09-04 15:35:00 +08:00
|
|
|
const ParseInputs &Inputs, 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, FileName);
|
2020-11-06 01:43:58 +08:00
|
|
|
auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *ContentsBuffer, 0);
|
2019-09-04 15:35:00 +08:00
|
|
|
|
|
|
|
trace::Span Tracer("BuildPreamble");
|
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
2021-03-12 21:23:45 +08:00
|
|
|
std::vector<std::unique_ptr<FeatureModule::ASTListener>> ASTListeners;
|
|
|
|
if (Inputs.FeatureModules) {
|
|
|
|
for (auto &M : *Inputs.FeatureModules) {
|
|
|
|
if (auto Listener = M.astListeners())
|
|
|
|
ASTListeners.emplace_back(std::move(Listener));
|
|
|
|
}
|
|
|
|
}
|
2019-09-04 15:35:00 +08:00
|
|
|
StoreDiags PreambleDiagnostics;
|
2021-03-12 21:23:45 +08:00
|
|
|
PreambleDiagnostics.setDiagCallback(
|
|
|
|
[&ASTListeners](const clang::Diagnostic &D, clangd::Diag &Diag) {
|
|
|
|
llvm::for_each(ASTListeners,
|
|
|
|
[&](const auto &L) { L->sawDiagnostic(D, Diag); });
|
|
|
|
});
|
2019-09-04 15:35:00 +08:00
|
|
|
llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
|
|
|
|
CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
|
|
|
|
&PreambleDiagnostics, false);
|
2021-04-15 01:28:14 +08:00
|
|
|
PreambleDiagnostics.setLevelAdjuster(
|
|
|
|
[&](DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) {
|
|
|
|
switch (Info.getID()) {
|
|
|
|
case diag::warn_no_newline_eof:
|
|
|
|
case diag::warn_cxx98_compat_no_newline_eof:
|
|
|
|
case diag::ext_no_newline_eof:
|
|
|
|
// If the preamble doesn't span the whole file, drop the no newline at
|
|
|
|
// eof warnings.
|
|
|
|
return Bounds.Size != ContentsBuffer->getBufferSize()
|
|
|
|
? DiagnosticsEngine::Level::Ignored
|
|
|
|
: DiagLevel;
|
|
|
|
}
|
|
|
|
return DiagLevel;
|
|
|
|
});
|
2019-09-04 15:35:00 +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;
|
|
|
|
// 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;
|
|
|
|
|
|
|
|
CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
|
2020-06-18 00:09:54 +08:00
|
|
|
auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
|
2019-09-04 15:35:00 +08:00
|
|
|
llvm::SmallString<32> AbsFileName(FileName);
|
2020-06-05 00:26:52 +08:00
|
|
|
VFS->makeAbsolute(AbsFileName);
|
2019-09-04 15:35:00 +08:00
|
|
|
auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName);
|
|
|
|
auto BuiltPreamble = PrecompiledPreamble::Build(
|
|
|
|
CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
|
2020-06-05 00:26:52 +08:00
|
|
|
StatCache->getProducingFS(VFS),
|
2019-09-04 15:35:00 +08:00
|
|
|
std::make_shared<PCHContainerOperations>(), StoreInMemory,
|
|
|
|
SerializedDeclsCollector);
|
|
|
|
|
|
|
|
// When building the AST for the main file, we do want the function
|
|
|
|
// bodies.
|
|
|
|
CI.getFrontendOpts().SkipFunctionBodies = false;
|
|
|
|
|
|
|
|
if (BuiltPreamble) {
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
vlog("Built preamble of size {0} for file {1} version {2}",
|
|
|
|
BuiltPreamble->getSize(), FileName, Inputs.Version);
|
2019-09-04 15:35:00 +08:00
|
|
|
std::vector<Diag> Diags = PreambleDiagnostics.take();
|
|
|
|
return std::make_shared<PreambleData>(
|
2020-03-11 23:34:01 +08:00
|
|
|
Inputs, std::move(*BuiltPreamble), std::move(Diags),
|
2019-09-04 15:35:00 +08:00
|
|
|
SerializedDeclsCollector.takeIncludes(),
|
2019-09-24 19:14:06 +08:00
|
|
|
SerializedDeclsCollector.takeMacros(), std::move(StatCache),
|
2019-09-04 15:35:00 +08:00
|
|
|
SerializedDeclsCollector.takeCanonicalIncludes());
|
|
|
|
} else {
|
2020-03-19 22:09:28 +08:00
|
|
|
elog("Could not build a preamble for file {0} version {1}", FileName,
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
Inputs.Version);
|
2019-09-04 15:35:00 +08:00
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
bool isPreambleCompatible(const PreambleData &Preamble,
|
|
|
|
const ParseInputs &Inputs, PathRef FileName,
|
|
|
|
const CompilerInvocation &CI) {
|
|
|
|
auto ContentsBuffer =
|
|
|
|
llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
|
2020-11-06 01:43:58 +08:00
|
|
|
auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *ContentsBuffer, 0);
|
2020-06-18 00:09:54 +08:00
|
|
|
auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
|
2020-03-16 04:43:00 +08:00
|
|
|
return compileCommandsAreEqual(Inputs.CompileCommand,
|
|
|
|
Preamble.CompileCommand) &&
|
2020-11-10 23:54:03 +08:00
|
|
|
Preamble.Preamble.CanReuse(CI, *ContentsBuffer, Bounds, *VFS);
|
2020-03-16 04:43:00 +08:00
|
|
|
}
|
2020-04-02 16:53:23 +08:00
|
|
|
|
2020-04-23 23:44:51 +08:00
|
|
|
void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) {
|
|
|
|
for (char C : Text) {
|
|
|
|
switch (C) {
|
|
|
|
case '\\':
|
|
|
|
case '"':
|
|
|
|
OS << '\\';
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
OS << C;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-02 16:53:23 +08:00
|
|
|
PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
|
|
|
|
const ParseInputs &Modified,
|
|
|
|
const PreambleData &Baseline) {
|
2020-05-29 18:31:35 +08:00
|
|
|
trace::Span Tracer("CreatePreamblePatch");
|
|
|
|
SPAN_ATTACH(Tracer, "File", FileName);
|
2020-04-02 16:53:45 +08:00
|
|
|
assert(llvm::sys::path::is_absolute(FileName) && "relative FileName!");
|
2020-05-14 18:20:33 +08:00
|
|
|
// First scan preprocessor directives in Baseline and Modified. These will be
|
2020-04-02 16:53:23 +08:00
|
|
|
// used to figure out newly added directives in Modified. Scanning can fail,
|
|
|
|
// the code just bails out and creates an empty patch in such cases, as:
|
|
|
|
// - If scanning for Baseline fails, no knowledge of existing includes hence
|
|
|
|
// patch will contain all the includes in Modified. Leading to rebuild of
|
|
|
|
// whole preamble, which is terribly slow.
|
|
|
|
// - If scanning for Modified fails, cannot figure out newly added ones so
|
|
|
|
// there's nothing to do but generate an empty patch.
|
2020-05-14 18:20:33 +08:00
|
|
|
auto BaselineScan = scanPreamble(
|
2020-04-02 16:53:23 +08:00
|
|
|
// Contents needs to be null-terminated.
|
2020-06-18 00:09:54 +08:00
|
|
|
Baseline.Preamble.getContents().str(), Modified.CompileCommand);
|
2020-05-14 18:20:33 +08:00
|
|
|
if (!BaselineScan) {
|
|
|
|
elog("Failed to scan baseline of {0}: {1}", FileName,
|
|
|
|
BaselineScan.takeError());
|
|
|
|
return PreamblePatch::unmodified(Baseline);
|
2020-04-02 16:53:23 +08:00
|
|
|
}
|
2020-06-18 00:09:54 +08:00
|
|
|
auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand);
|
2020-05-14 18:20:33 +08:00
|
|
|
if (!ModifiedScan) {
|
|
|
|
elog("Failed to scan modified contents of {0}: {1}", FileName,
|
|
|
|
ModifiedScan.takeError());
|
|
|
|
return PreamblePatch::unmodified(Baseline);
|
2020-04-02 16:53:23 +08:00
|
|
|
}
|
2020-05-14 18:20:33 +08:00
|
|
|
|
|
|
|
bool IncludesChanged = BaselineScan->Includes != ModifiedScan->Includes;
|
|
|
|
bool DirectivesChanged =
|
|
|
|
BaselineScan->TextualDirectives != ModifiedScan->TextualDirectives;
|
|
|
|
if (!IncludesChanged && !DirectivesChanged)
|
2020-04-02 16:53:45 +08:00
|
|
|
return PreamblePatch::unmodified(Baseline);
|
2020-04-02 16:53:23 +08:00
|
|
|
|
|
|
|
PreamblePatch PP;
|
|
|
|
// This shouldn't coincide with any real file name.
|
|
|
|
llvm::SmallString<128> PatchName;
|
|
|
|
llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName),
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
PreamblePatchHeaderName);
|
2020-04-02 16:53:23 +08:00
|
|
|
PP.PatchFileName = PatchName.str().str();
|
2020-06-17 03:21:45 +08:00
|
|
|
PP.ModifiedBounds = ModifiedScan->Bounds;
|
2020-04-02 16:53:23 +08:00
|
|
|
|
|
|
|
llvm::raw_string_ostream Patch(PP.PatchContents);
|
2020-04-23 23:44:51 +08:00
|
|
|
// Set default filename for subsequent #line directives
|
|
|
|
Patch << "#line 0 \"";
|
|
|
|
// FileName part of a line directive is subject to backslash escaping, which
|
|
|
|
// might lead to problems on windows especially.
|
|
|
|
escapeBackslashAndQuotes(FileName, Patch);
|
|
|
|
Patch << "\"\n";
|
2020-05-14 18:20:33 +08:00
|
|
|
|
|
|
|
if (IncludesChanged) {
|
|
|
|
// We are only interested in newly added includes, record the ones in
|
|
|
|
// Baseline for exclusion.
|
|
|
|
llvm::DenseMap<std::pair<tok::PPKeywordKind, llvm::StringRef>,
|
|
|
|
/*Resolved=*/llvm::StringRef>
|
|
|
|
ExistingIncludes;
|
|
|
|
for (const auto &Inc : Baseline.Includes.MainFileIncludes)
|
|
|
|
ExistingIncludes[{Inc.Directive, Inc.Written}] = Inc.Resolved;
|
|
|
|
// There might be includes coming from disabled regions, record these for
|
|
|
|
// exclusion too. note that we don't have resolved paths for those.
|
|
|
|
for (const auto &Inc : BaselineScan->Includes)
|
|
|
|
ExistingIncludes.try_emplace({Inc.Directive, Inc.Written});
|
|
|
|
// Calculate extra includes that needs to be inserted.
|
|
|
|
for (auto &Inc : ModifiedScan->Includes) {
|
|
|
|
auto It = ExistingIncludes.find({Inc.Directive, Inc.Written});
|
|
|
|
// Include already present in the baseline preamble. Set resolved path and
|
|
|
|
// put into preamble includes.
|
|
|
|
if (It != ExistingIncludes.end()) {
|
|
|
|
Inc.Resolved = It->second.str();
|
|
|
|
PP.PreambleIncludes.push_back(Inc);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Include is new in the modified preamble. Inject it into the patch and
|
|
|
|
// use #line to set the presumed location to where it is spelled.
|
|
|
|
auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset);
|
|
|
|
Patch << llvm::formatv("#line {0}\n", LineCol.first);
|
|
|
|
Patch << llvm::formatv(
|
|
|
|
"#{0} {1}\n", spellingForIncDirective(Inc.Directive), Inc.Written);
|
2020-04-02 16:53:45 +08:00
|
|
|
}
|
2020-04-02 16:53:23 +08:00
|
|
|
}
|
|
|
|
|
2020-05-14 18:20:33 +08:00
|
|
|
if (DirectivesChanged) {
|
|
|
|
// We need to patch all the directives, since they are order dependent. e.g:
|
|
|
|
// #define BAR(X) NEW(X) // Newly introduced in Modified
|
|
|
|
// #define BAR(X) OLD(X) // Exists in the Baseline
|
|
|
|
//
|
|
|
|
// If we've patched only the first directive, the macro definition would've
|
|
|
|
// been wrong for the rest of the file, since patch is applied after the
|
|
|
|
// baseline preamble.
|
|
|
|
//
|
|
|
|
// Note that we deliberately ignore conditional directives and undefs to
|
|
|
|
// reduce complexity. The former might cause problems because scanning is
|
|
|
|
// imprecise and might pick directives from disabled regions.
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
for (const auto &TD : ModifiedScan->TextualDirectives) {
|
|
|
|
Patch << "#line " << TD.DirectiveLine << '\n';
|
2020-05-14 18:20:33 +08:00
|
|
|
Patch << TD.Text << '\n';
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
}
|
2020-05-14 18:20:33 +08:00
|
|
|
}
|
|
|
|
dlog("Created preamble patch: {0}", Patch.str());
|
|
|
|
Patch.flush();
|
2020-04-02 16:53:23 +08:00
|
|
|
return PP;
|
|
|
|
}
|
|
|
|
|
|
|
|
void PreamblePatch::apply(CompilerInvocation &CI) const {
|
|
|
|
// No need to map an empty file.
|
|
|
|
if (PatchContents.empty())
|
|
|
|
return;
|
|
|
|
auto &PPOpts = CI.getPreprocessorOpts();
|
|
|
|
auto PatchBuffer =
|
|
|
|
// we copy here to ensure contents are still valid if CI outlives the
|
|
|
|
// PreamblePatch.
|
|
|
|
llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName);
|
|
|
|
// CI will take care of the lifetime of the buffer.
|
|
|
|
PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release());
|
|
|
|
// The patch will be parsed after loading the preamble ast and before parsing
|
|
|
|
// the main file.
|
|
|
|
PPOpts.Includes.push_back(PatchFileName);
|
|
|
|
}
|
|
|
|
|
2020-04-02 16:53:45 +08:00
|
|
|
std::vector<Inclusion> PreamblePatch::preambleIncludes() const {
|
|
|
|
return PreambleIncludes;
|
|
|
|
}
|
|
|
|
|
|
|
|
PreamblePatch PreamblePatch::unmodified(const PreambleData &Preamble) {
|
|
|
|
PreamblePatch PP;
|
|
|
|
PP.PreambleIncludes = Preamble.Includes.MainFileIncludes;
|
2020-06-17 03:21:45 +08:00
|
|
|
PP.ModifiedBounds = Preamble.Preamble.getBounds();
|
2020-04-02 16:53:45 +08:00
|
|
|
return PP;
|
|
|
|
}
|
|
|
|
|
[clangd] locateMacroAt handles patched macros
Summary: Depends on D79992.
This patch changes locateMacroAt to perform #line directive substitution
for macro identifier locations.
We first check whether a location is inside a file included through
built-in header. If so we check whether line directive maps it back to
the main file, and afterwards use TokenBuffers to find exact location of
the identifier on the line.
Instead of performing the mapping in locateMacroAt, we could also store
a mapping inside the ParsedAST whenever we use a patched preamble. But
that would imply adding more responsibility to ParsedAST and paying for
the mapping even when it is not going to be used.
====
Go-To-Definition:
Later on these locations are used for serving go-to-definition requests,
this enables jumping to definition inside the preamble section in
presence of patched macros.
=====
Go-To-Refs:
Macro references in main file are collected separetely and stored as a
map from macro's symbol id to reference ranges. Those ranges are
computed inside PPCallbacks, hence we don't have access to TokenBuffer.
In presence of preamble patch, any reference to a macro inside the
preamble section will unfortunately have the wrong range. They'll point
into the patch rather than the main file. Hence during findReferences,
we won't get any ranges reported for those.
Fixing those requires:
- Lexing the preamble section to figure out "real range" of a patched
macro definition
- Postponing range/location calculations until a later step in which we
have access to tokenbuffers.
This patch trades some accuracy in favor of code complexity. We don't do
any patching for references inside the preamble patch but get any
reference inside the main file for free.
Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80198
2020-05-14 18:26:47 +08:00
|
|
|
SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
|
|
|
|
const SourceManager &SM) {
|
|
|
|
auto DefFile = SM.getFileID(Loc);
|
|
|
|
if (auto *FE = SM.getFileEntryForID(DefFile)) {
|
|
|
|
auto IncludeLoc = SM.getIncludeLoc(DefFile);
|
|
|
|
// Preamble patch is included inside the builtin file.
|
|
|
|
if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
|
|
|
|
FE->getName().endswith(PreamblePatchHeaderName)) {
|
|
|
|
auto Presumed = SM.getPresumedLoc(Loc);
|
|
|
|
// Check that line directive is pointing at main file.
|
|
|
|
if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
|
|
|
|
isMainFile(Presumed.getFilename(), SM)) {
|
|
|
|
Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
|
|
|
|
Presumed.getColumn());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Loc;
|
|
|
|
}
|
2019-09-04 15:35:00 +08:00
|
|
|
} // namespace clangd
|
|
|
|
} // namespace clang
|