kadircet updated this revision to Diff 200732.
kadircet marked 5 inline comments as done.
kadircet added a comment.
- Added tests, and went over implementation.
I am looking for input on:
- Behavior on lambdas, currently it just keeps the old behaviour. I believe
they should look more like functions. Do you think it is necessary for first
patch?
- Template classes/functions, what we have in definition is not great but I
don't think it is too much of a problem since semantic representation carries
all the useful information.
- Declared in #SOME_KIND# #SOME_PLACE#, currently we drop SOME_KIND and it
needs additional info to be propogated since it is not the type of the symbol
but rather it is immediate container. I don't think it is necessary for initial
version.
- Discrepencies between hovering over auto/decltype and explicitly spelled
types, again this keeps the existing behaviour. You can see details in
testcases.
Repository:
rG LLVM Github Monorepo
CHANGES SINCE LAST ACTION
https://reviews.llvm.org/D61497/new/
https://reviews.llvm.org/D61497
Files:
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/Protocol.cpp
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/XRefs.h
clang-tools-extra/clangd/test/hover.test
clang-tools-extra/clangd/unittests/TestTU.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===================================================================
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -9,6 +9,7 @@
#include "ClangdUnit.h"
#include "Compiler.h"
#include "Matchers.h"
+#include "Protocol.h"
#include "SyncAPI.h"
#include "TestFS.h"
#include "TestTU.h"
@@ -16,6 +17,7 @@
#include "index/FileIndex.h"
#include "index/SymbolCollector.h"
#include "clang/Index/IndexingAction.h"
+#include "llvm/ADT/None.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include "gmock/gmock.h"
@@ -558,6 +560,350 @@
HeaderNotInPreambleAnnotations.range())));
}
+TEST(Hover, Structured) {
+ struct {
+ const char *const Code;
+ const HoverInfo Expected;
+ } // namespace
+ Cases[] = {
+ // Global scope.
+ {R"cpp(
+ // Best foo ever.
+ void [[fo^o]]() {}
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Function,
+ /*Documentation=*/"Best foo ever.",
+ /*Definition=*/"void foo()",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/std::string("void"),
+ /*Parameters=*/std::vector<HoverInfo::Param>{},
+ /*TemplateParameters=*/llvm::None}},
+ // Inside namespace
+ {R"cpp(
+ namespace ns1 { namespace ns2 {
+ /// Best foo ever.
+ void [[fo^o]]() {}
+ }}
+ )cpp",
+ {/*NamespaceScope=*/std::string("ns1::ns2"),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Function,
+ /*Documentation=*/"Best foo ever.",
+ /*Definition=*/"void foo()",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/std::string("void"),
+ /*Parameters=*/std::vector<HoverInfo::Param>{},
+ /*TemplateParameters=*/llvm::None}},
+ // Field
+ {R"cpp(
+ namespace ns1 { namespace ns2 {
+ struct Foo {
+ int [[b^ar]];
+ };
+ }}
+ )cpp",
+ {/*NamespaceScope=*/std::string("ns1::ns2"),
+ /*LocalScope=*/std::string("Foo"),
+ /*Name=*/"bar",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Field,
+ /*Documentation=*/"",
+ /*Definition=*/"int bar",
+ /*Type=*/std::string("int"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // Local to class method.
+ {R"cpp(
+ namespace ns1 { namespace ns2 {
+ struct Foo {
+ void foo() {
+ int [[b^ar]];
+ }
+ };
+ }}
+ )cpp",
+ {/*NamespaceScope=*/std::string("ns1::ns2"),
+ /*LocalScope=*/std::string("Foo::foo"),
+ /*Name=*/"bar",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"int bar",
+ /*Type=*/std::string("int"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // Anon namespace and local scope.
+ {R"cpp(
+ namespace ns1 { namespace {
+ struct {
+ int [[b^ar]];
+ } T;
+ }}
+ )cpp",
+ {/*NamespaceScope=*/std::string("ns1::(anonymous)"),
+ /*LocalScope=*/std::string("(anonymous struct)"),
+ /*Name=*/"bar",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Field,
+ /*Documentation=*/"",
+ /*Definition=*/"int bar",
+ /*Type=*/std::string("int"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // Variable with template type
+ {R"cpp(
+ template <typename T, class... Ts> class Foo {};
+ Foo<int, char, bool> [[fo^o]];
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"Foo<int, char, bool> foo",
+ /*Type=*/std::string("Foo<int, char, bool>"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // Class template
+ {R"cpp(
+ template <template<typename, bool...> class C,
+ typename = char,
+ int = 0,
+ bool Q = false,
+ class... Ts> class Foo {};
+ template <template<typename, bool...> class T>
+ [[F^oo]]<T> foo;
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"Foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Class,
+ /*Documentation=*/"",
+ /*Definition=*/
+ "template <template <typename, bool ...> class C, typename = char, int "
+ "= 0, bool Q = false, class ...Ts> class Foo {}",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/
+ std::vector<HoverInfo::Param>({
+ {std::string("template <typename, bool...> class"),
+ std::string("C"), llvm::None},
+ {std::string("typename"), llvm::None, std::string("char")},
+ {std::string("int"), llvm::None, std::string("0")},
+ {std::string("bool"), std::string("Q"), std::string("false")},
+ {std::string("class..."), std::string("Ts"), llvm::None},
+ })}},
+ // Function template
+ {R"cpp(
+ template <template<typename, bool...> class C,
+ typename = char,
+ int = 0,
+ bool Q = false,
+ class... Ts> void foo();
+ template<typename, bool...> class Foo;
+
+ void bar() {
+ [[fo^o]]<Foo>();
+ }
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Function,
+ /*Documentation=*/"",
+ /*Definition=*/
+ "template <template <typename, bool ...> class C, typename = char, int "
+ "= 0, bool Q = false, class ...Ts> void foo()",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/std::string("void"),
+ /*Parameters=*/std::vector<HoverInfo::Param>(),
+ /*TemplateParameters=*/
+ std::vector<HoverInfo::Param>({
+ {std::string("template <typename, bool...> class"),
+ std::string("C"), llvm::None},
+ {std::string("typename"), llvm::None, std::string("char")},
+ {std::string("int"), llvm::None, std::string("0")},
+ {std::string("bool"), std::string("Q"), std::string("false")},
+ {std::string("class..."), std::string("Ts"), llvm::None},
+ })}},
+ // Function decl
+ {R"cpp(
+ template<typename, bool...> class Foo {};
+ Foo<bool, true, false> foo(int, bool T = false);
+
+ void bar() {
+ [[fo^o]](3);
+ }
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string(""),
+ /*Name=*/"foo",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Function,
+ /*Documentation=*/"",
+ /*Definition=*/"Foo<bool, true, false> foo(int, bool T = false)",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/std::string("Foo<bool, true, false>"),
+ /*Parameters=*/
+ std::vector<HoverInfo::Param>({
+ {std::string("int"), llvm::None, llvm::None},
+ {std::string("bool"), std::string("T"), std::string("false")},
+ }),
+ /*TemplateParameters=*/llvm::None}},
+ // Lambda variable
+ {R"cpp(
+ void foo() {
+ int bar = 5;
+ auto lamb = [&bar](int T, bool B) -> bool { return T && B && bar; };
+ bool res = [[lam^b]](bar, false);
+ }
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string("foo"),
+ /*Name=*/"lamb",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/
+ "auto lamb = [&bar](int T, bool B) -> bool {\n return T && B && "
+ "bar;\n}",
+ /*Type=*/std::string("class (lambda)"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // Local variable in lambda
+ {R"cpp(
+ void foo() {
+ auto lamb = []{int [[te^st]];};
+ }
+ )cpp",
+ {/*NamespaceScope=*/std::string(""),
+ /*LocalScope=*/std::string("foo::(anonymous class)::operator()"),
+ /*Name=*/"test",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"int test",
+ /*Type=*/std::string("int"),
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+
+ // auto on lambda
+ {R"cpp(
+ void foo() {
+ [[au^to]] lamb = []{};
+ }
+ )cpp",
+ {/*NamespaceScope=*/llvm::None,
+ /*LocalScope=*/llvm::None,
+ /*Name=*/"class (lambda)",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // auto on template instantiation
+ {R"cpp(
+ template<typename T> class Foo{};
+ void foo() {
+ [[au^to]] x = Foo<int>();
+ }
+ )cpp",
+ {/*NamespaceScope=*/llvm::None,
+ /*LocalScope=*/llvm::None,
+ /*Name=*/"class Foo<int>",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ // auto on specialized template
+ {R"cpp(
+ template<typename T> class Foo{};
+ template<> class Foo<int>{};
+ void foo() {
+ [[au^to]] x = Foo<int>();
+ }
+ )cpp",
+ {/*NamespaceScope=*/llvm::None,
+ /*LocalScope=*/llvm::None,
+ /*Name=*/"class Foo<int>",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::Variable,
+ /*Documentation=*/"",
+ /*Definition=*/"",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+
+ // macro
+ {R"cpp(
+ // Best MACRO ever.
+ #define MACRO(x,y,z) void foo(x, y, z);
+ [[MAC^RO]](int, double d, bool z = false);
+ )cpp",
+ {/*NamespaceScope=*/llvm::None,
+ /*LocalScope=*/llvm::None,
+ /*Name=*/"MACRO",
+ /*SymRange=*/llvm::None,
+ /*Kind=*/SymbolKind::String,
+ /*Documentation=*/"",
+ /*Definition=*/"#define MACRO(x,y,z) void foo(x, y, z);",
+ /*Type=*/llvm::None,
+ /*ReturnType=*/llvm::None,
+ /*Parameters=*/llvm::None,
+ /*TemplateParameters=*/llvm::None}},
+ };
+ for (const auto &Case : Cases) {
+ SCOPED_TRACE(Case.Code);
+
+ Annotations T(Case.Code);
+ TestTU TU = TestTU::withCode(T.code());
+ TU.ExtraArgs.push_back("-std=c++17");
+ auto AST = TU.build();
+ for (const auto &x : AST.getDiagnostics())
+ llvm::errs() << x;
+ ASSERT_TRUE(AST.getDiagnostics().empty());
+
+ auto H = getHover(AST, T.point());
+ ASSERT_TRUE(H);
+ EXPECT_EQ(H->NamespaceScope, Case.Expected.NamespaceScope);
+ EXPECT_EQ(H->LocalScope, Case.Expected.LocalScope);
+ EXPECT_EQ(H->Name, Case.Expected.Name);
+ EXPECT_EQ(H->Kind, Case.Expected.Kind);
+ EXPECT_EQ(H->Documentation, Case.Expected.Documentation);
+ EXPECT_EQ(H->Definition, Case.Expected.Definition);
+ EXPECT_EQ(H->Type, Case.Expected.Type);
+ EXPECT_EQ(H->ReturnType, Case.Expected.ReturnType);
+ EXPECT_EQ(H->Parameters, Case.Expected.Parameters);
+ EXPECT_EQ(H->TemplateParameters, Case.Expected.TemplateParameters);
+
+ EXPECT_EQ(H->SymRange, T.range());
+ }
+} // namespace clang
+
TEST(Hover, All) {
struct OneTest {
StringRef Input;
@@ -580,7 +926,7 @@
int test1 = bonjour;
}
)cpp",
- "Declared in function main\n\nint bonjour",
+ "Declared in main\n\nint bonjour",
},
{
R"cpp(// Local variable in method
@@ -591,7 +937,7 @@
}
};
)cpp",
- "Declared in function s::method\n\nint bonjour",
+ "Declared in s::method\n\nint bonjour",
},
{
R"cpp(// Struct
@@ -602,7 +948,7 @@
ns1::My^Class* Params;
}
)cpp",
- "Declared in namespace ns1\n\nstruct MyClass {}",
+ "Declared in ns1\n\nstruct MyClass {}",
},
{
R"cpp(// Class
@@ -613,7 +959,7 @@
ns1::My^Class* Params;
}
)cpp",
- "Declared in namespace ns1\n\nclass MyClass {}",
+ "Declared in ns1\n\nclass MyClass {}",
},
{
R"cpp(// Union
@@ -624,7 +970,7 @@
ns1::My^Union Params;
}
)cpp",
- "Declared in namespace ns1\n\nunion MyUnion {}",
+ "Declared in ns1\n\nunion MyUnion {}",
},
{
R"cpp(// Function definition via pointer
@@ -652,7 +998,7 @@
bar.^x;
}
)cpp",
- "Declared in struct Foo\n\nint x",
+ "Declared in Foo\n\nint x",
},
{
R"cpp(// Field with initialization
@@ -662,7 +1008,7 @@
bar.^x;
}
)cpp",
- "Declared in struct Foo\n\nint x = 5",
+ "Declared in Foo\n\nint x = 5",
},
{
R"cpp(// Static field
@@ -671,7 +1017,7 @@
Foo::^x;
}
)cpp",
- "Declared in struct Foo\n\nstatic int x",
+ "Declared in Foo\n\nstatic int x",
},
{
R"cpp(// Field, member initializer
@@ -680,7 +1026,7 @@
Foo() : ^x(0) {}
};
)cpp",
- "Declared in struct Foo\n\nint x",
+ "Declared in Foo\n\nint x",
},
{
R"cpp(// Field, GNU old-style field designator
@@ -689,7 +1035,7 @@
Foo bar = { ^x : 1 };
}
)cpp",
- "Declared in struct Foo\n\nint x",
+ "Declared in Foo\n\nint x",
},
{
R"cpp(// Field, field designator
@@ -698,7 +1044,7 @@
Foo bar = { .^x = 2 };
}
)cpp",
- "Declared in struct Foo\n\nint x",
+ "Declared in Foo\n\nint x",
},
{
R"cpp(// Method call
@@ -708,7 +1054,7 @@
bar.^x();
}
)cpp",
- "Declared in struct Foo\n\nint x()",
+ "Declared in Foo\n\nint x()",
},
{
R"cpp(// Static method call
@@ -717,7 +1063,7 @@
Foo::^x();
}
)cpp",
- "Declared in struct Foo\n\nstatic int x()",
+ "Declared in Foo\n\nstatic int x()",
},
{
R"cpp(// Typedef
@@ -746,7 +1092,7 @@
} // namespace ns
int main() { ns::f^oo++; }
)cpp",
- "Declared in namespace ns::(anonymous)\n\nint foo",
+ "Declared in ns::(anonymous)\n\nint foo",
},
{
R"cpp(// Macro
@@ -812,7 +1158,7 @@
Hello hello = O^NE;
}
)cpp",
- "Declared in enum Hello\n\nONE",
+ "Declared in Hello\n\nONE",
},
{
R"cpp(// Enumerator in anonymous enum
@@ -823,7 +1169,7 @@
int hello = O^NE;
}
)cpp",
- "Declared in enum (anonymous)\n\nONE",
+ "Declared in global namespace\n\nONE",
},
{
R"cpp(// Global variable
@@ -843,7 +1189,7 @@
ns1::he^y++;
}
)cpp",
- "Declared in namespace ns1\n\nstatic int hey = 10",
+ "Declared in ns1\n\nstatic int hey = 10",
},
{
R"cpp(// Field in anonymous struct
@@ -854,7 +1200,7 @@
s.he^llo++;
}
)cpp",
- "Declared in struct (anonymous)\n\nint hello",
+ "Declared in (anonymous struct)\n\nint hello",
},
{
R"cpp(// Templated function
@@ -875,7 +1221,7 @@
};
void g() { struct outer o; o.v.d^ef++; }
)cpp",
- "Declared in union outer::(anonymous)\n\nint def",
+ "Declared in outer::(anonymous union)\n\nint def",
},
{
R"cpp(// Nothing
@@ -1185,7 +1531,7 @@
auto AST = TU.build();
if (auto H = getHover(AST, T.point())) {
EXPECT_NE("", Test.ExpectedHover) << Test.Input;
- EXPECT_EQ(H->contents.value, Test.ExpectedHover.str()) << Test.Input;
+ EXPECT_EQ(H->render().value, Test.ExpectedHover.str()) << Test.Input;
} else
EXPECT_EQ("", Test.ExpectedHover.str()) << Test.Input;
}
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===================================================================
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -58,8 +58,7 @@
/*OldPreamble=*/nullptr,
/*OldCompileCommand=*/Inputs.CompileCommand, Inputs,
/*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
- auto AST = buildAST(FullFilename, createInvocationFromCommandLine(Cmd),
- Inputs, Preamble);
+ auto AST = buildAST(FullFilename, std::move(CI), Inputs, Preamble);
if (!AST.hasValue()) {
ADD_FAILURE() << "Failed to build code:\n" << Code;
llvm_unreachable("Failed to build TestTU!");
Index: clang-tools-extra/clangd/test/hover.test
===================================================================
--- clang-tools-extra/clangd/test/hover.test
+++ clang-tools-extra/clangd/test/hover.test
@@ -10,6 +10,16 @@
# CHECK-NEXT: "contents": {
# CHECK-NEXT: "kind": "plaintext",
# CHECK-NEXT: "value": "Declared in global namespace\n\nvoid foo()"
+# CHECK-NEXT: },
+# CHECK-NEXT: "range": {
+# CHECK-NEXT: "end": {
+# CHECK-NEXT: "character": 28,
+# CHECK-NEXT: "line": 0
+# CHECK-NEXT: },
+# CHECK-NEXT: "start": {
+# CHECK-NEXT: "character": 25,
+# CHECK-NEXT: "line": 0
+# CHECK-NEXT: }
# CHECK-NEXT: }
# CHECK-NEXT: }
# CHECK-NEXT:}
Index: clang-tools-extra/clangd/XRefs.h
===================================================================
--- clang-tools-extra/clangd/XRefs.h
+++ clang-tools-extra/clangd/XRefs.h
@@ -16,7 +16,10 @@
#include "ClangdUnit.h"
#include "Protocol.h"
#include "index/Index.h"
+#include "index/SymbolLocation.h"
+#include "clang/Index/IndexSymbol.h"
#include "llvm/ADT/Optional.h"
+#include "llvm/Support/raw_ostream.h"
#include <vector>
namespace clang {
@@ -46,8 +49,70 @@
std::vector<DocumentHighlight> findDocumentHighlights(ParsedAST &AST,
Position Pos);
+/// Contains detailed information about a Symbol. Especially useful when
+/// generating hover responses. It can be rendered as a hover panel, or
+/// embedding clients can use the structured information to provide their own
+/// UI.
+struct HoverInfo {
+ /// Represents parameters of a function, a template or a macro.
+ /// For example:
+ /// - void foo(ParamType Name = DefaultValue)
+ /// - #define FOO(Name)
+ /// - template <ParamType Name = DefaultType> class Foo {};
+ struct Param {
+ /// The pretty-printed parameter type, e.g. "int", or "typename" (in
+ /// TemplateParameters)
+ llvm::Optional<std::string> Type;
+ /// None for unnamed parameters.
+ llvm::Optional<std::string> Name;
+ /// None if no default is provided.
+ llvm::Optional<std::string> Default;
+ };
+
+ /// For a variable named Bar, declared in clang::clangd::Foo::getFoo the
+ /// following fields will hold:
+ /// - NamespaceScope: clang::clangd::
+ /// - LocalScope: Foo::getFoo::
+ /// - Name: Bar
+
+ /// Scopes might be None in cases where they don't make sense, e.g. macros and
+ /// auto/decltype.
+ /// Contains all of the enclosing namespaces.
+ llvm::Optional<std::string> NamespaceScope;
+ /// Remaining named contexts in symbol's qualified name.
+ llvm::Optional<std::string> LocalScope;
+ /// Name of the symbol, does not contain any "::".
+ std::string Name;
+ llvm::Optional<Range> SymRange;
+ /// Scope containing the symbol. e.g, "global namespace", "function x::Y"
+ /// - None for deduced types, e.g "auto", "decltype" keywords.
+ SymbolKind Kind;
+ std::string Documentation;
+ /// Source code containing the definition of the symbol.
+ std::string Definition;
+
+ /// Pretty-printed variable type.
+ /// Set only for variables.
+ llvm::Optional<std::string> Type;
+ /// Set for functions and lambadas.
+ llvm::Optional<std::string> ReturnType;
+ /// Set for functions, lambdas and macros with parameters.
+ llvm::Optional<std::vector<Param>> Parameters;
+ /// Set for all templates(function, class, variable).
+ llvm::Optional<std::vector<Param>> TemplateParameters;
+
+ /// Lower to LSP struct.
+ MarkupContent render() const;
+};
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const HoverInfo::Param &);
+inline bool operator==(const HoverInfo::Param &LHS,
+ const HoverInfo::Param &RHS) {
+ return std::tie(LHS.Type, LHS.Name, LHS.Default) ==
+ std::tie(RHS.Type, RHS.Name, RHS.Default);
+}
+
/// Get the hover information when hovering at \p Pos.
-llvm::Optional<Hover> getHover(ParsedAST &AST, Position Pos);
+llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos);
/// Returns reference locations of the symbol at a specified \p Pos.
/// \p Limit limits the number of results returned (0 means no limit).
Index: clang-tools-extra/clangd/XRefs.cpp
===================================================================
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -7,21 +7,37 @@
//===----------------------------------------------------------------------===//
#include "XRefs.h"
#include "AST.h"
+#include "CodeCompletionStrings.h"
#include "FindSymbols.h"
#include "Logger.h"
+#include "Protocol.h"
#include "SourceCode.h"
#include "URI.h"
#include "index/Merge.h"
#include "index/SymbolCollector.h"
#include "index/SymbolLocation.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Type.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
#include "clang/Index/IndexDataConsumer.h"
#include "clang/Index/IndexSymbol.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Index/USRGeneration.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
+#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace clangd {
@@ -241,17 +257,17 @@
return {DeclMacrosFinder.getFoundDecls(), DeclMacrosFinder.takeMacroInfos()};
}
-Range getTokenRange(ParsedAST &AST, SourceLocation TokLoc) {
- const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
- SourceLocation LocEnd = Lexer::getLocForEndOfToken(
- TokLoc, 0, SourceMgr, AST.getASTContext().getLangOpts());
+Range getTokenRange(ASTContext &AST, SourceLocation TokLoc) {
+ const SourceManager &SourceMgr = AST.getSourceManager();
+ SourceLocation LocEnd =
+ Lexer::getLocForEndOfToken(TokLoc, 0, SourceMgr, AST.getLangOpts());
return {sourceLocToPosition(SourceMgr, TokLoc),
sourceLocToPosition(SourceMgr, LocEnd)};
}
-llvm::Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc,
+llvm::Optional<Location> makeLocation(ASTContext &AST, SourceLocation TokLoc,
llvm::StringRef TUPath) {
- const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
+ const SourceManager &SourceMgr = AST.getSourceManager();
const FileEntry *F = SourceMgr.getFileEntryForID(SourceMgr.getFileID(TokLoc));
if (!F)
return None;
@@ -299,8 +315,8 @@
// As a consequence, there's no need to look them up in the index either.
std::vector<LocatedSymbol> Result;
for (auto M : Symbols.Macros) {
- if (auto Loc =
- makeLocation(AST, M.Info->getDefinitionLoc(), *MainFilePath)) {
+ if (auto Loc = makeLocation(AST.getASTContext(), M.Info->getDefinitionLoc(),
+ *MainFilePath)) {
LocatedSymbol Macro;
Macro.Name = M.Name;
Macro.PreferredDeclaration = *Loc;
@@ -320,7 +336,7 @@
// Emit all symbol locations (declaration or definition) from AST.
for (const Decl *D : Symbols.Decls) {
- auto Loc = makeLocation(AST, findNameLoc(D), *MainFilePath);
+ auto Loc = makeLocation(AST.getASTContext(), findNameLoc(D), *MainFilePath);
if (!Loc)
continue;
@@ -453,7 +469,7 @@
std::vector<DocumentHighlight> Result;
for (const auto &Ref : References) {
DocumentHighlight DH;
- DH.range = getTokenRange(AST, Ref.Loc);
+ DH.range = getTokenRange(AST.getASTContext(), Ref.Loc);
if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Write))
DH.kind = DocumentHighlightKind::Write;
else if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Read))
@@ -477,102 +493,223 @@
return Policy;
}
-/// Return a string representation (e.g. "class MyNamespace::MyClass") of
-/// the type declaration \p TD.
-static std::string typeDeclToString(const TypeDecl *TD) {
- QualType Type = TD->getASTContext().getTypeDeclType(TD);
+/// Given a declaration \p D, return a human-readable string representing the
+/// local scope in which it is declared, i.e. class(es) and method name. Returns
+/// an empty string if it is not local.
+static std::string getLocalScope(const Decl *D) {
+ std::vector<std::string> Scopes;
+ const DeclContext *DC = D->getDeclContext();
+ auto GetName = [](const Decl *D) {
+ const NamedDecl *ND = dyn_cast<NamedDecl>(D);
+ std::string Name = ND->getNameAsString();
+ if (!Name.empty())
+ return Name;
+ if (auto RD = dyn_cast<RecordDecl>(D))
+ return ("(anonymous " + RD->getKindName() + ")").str();
+ return std::string("");
+ };
+ while (DC) {
+ if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
+ Scopes.push_back(GetName(TD));
+ else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
+ Scopes.push_back(FD->getNameAsString());
+ DC = DC->getParent();
+ }
- PrintingPolicy Policy =
- printingPolicyForDecls(TD->getASTContext().getPrintingPolicy());
+ return llvm::join(llvm::reverse(Scopes), "::");
+}
- std::string Name;
- llvm::raw_string_ostream Stream(Name);
- Type.print(Stream, Policy);
+/// Returns the human-readable representation for namespace containing the
+/// declaration \p D. Returns empty if it is contained global namespace.
+static std::string getNamespaceScope(const Decl *D) {
+ const DeclContext *DC = D->getDeclContext();
+
+ if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
+ return getNamespaceScope(TD);
+ if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
+ return getNamespaceScope(FD);
+ if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
+ return ND->getQualifiedNameAsString();
- return Stream.str();
+ return "";
}
-/// Return a string representation (e.g. "namespace ns1::ns2") of
-/// the named declaration \p ND.
-static std::string namedDeclQualifiedName(const NamedDecl *ND,
- llvm::StringRef Prefix) {
+static std::string printDefinition(const Decl *D) {
+ std::string Definition;
+ llvm::raw_string_ostream OS(Definition);
PrintingPolicy Policy =
- printingPolicyForDecls(ND->getASTContext().getPrintingPolicy());
-
- std::string Name;
- llvm::raw_string_ostream Stream(Name);
- Stream << Prefix << ' ';
- ND->printQualifiedName(Stream, Policy);
+ printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
+ Policy.IncludeTagDefinition = false;
+ D->print(OS, Policy);
+ return Definition;
+}
- return Stream.str();
+static void printParams(llvm::raw_ostream &OS,
+ const std::vector<HoverInfo::Param> &Params) {
+ for (size_t I = 0, E = Params.size(); I != E; ++I) {
+ if (I)
+ OS << ", ";
+ OS << Params.at(I);
+ }
}
-/// Given a declaration \p D, return a human-readable string representing the
-/// scope in which it is declared. If the declaration is in the global scope,
-/// return the string "global namespace".
-static llvm::Optional<std::string> getScopeName(const Decl *D) {
- const DeclContext *DC = D->getDeclContext();
+static std::vector<HoverInfo::Param>
+fetchTemplateParameters(const TemplateParameterList *Params,
+ const PrintingPolicy &PP) {
+ assert(Params);
+ std::vector<HoverInfo::Param> TempParameters;
+
+ for (const Decl *Param : *Params) {
+ HoverInfo::Param P;
+ P.Type.emplace();
+ if (const auto TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
+ P.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
+ if (TTP->isParameterPack())
+ *P.Type += "...";
+
+ if (!TTP->getName().empty())
+ P.Name = TTP->getNameAsString();
+ if (TTP->hasDefaultArgument())
+ P.Default = TTP->getDefaultArgument().getAsString(PP);
+ } else if (const auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
+ if (IdentifierInfo *II = NTTP->getIdentifier())
+ P.Name = II->getName().str();
+
+ llvm::raw_string_ostream Out(*P.Type);
+ NTTP->getType().print(Out, PP);
+ if (NTTP->isParameterPack())
+ Out << "...";
+
+ if (NTTP->hasDefaultArgument()) {
+ P.Default.emplace();
+ llvm::raw_string_ostream Out(*P.Default);
+ NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
+ }
+ } else if (const auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
+ llvm::raw_string_ostream OS(*P.Type);
+ OS << "template <";
+ printParams(OS,
+ fetchTemplateParameters(TTPD->getTemplateParameters(), PP));
+ OS << "> class"; // FIXME: TemplateTemplateParameter doesn't store the
+ // info on whether this param was a "typename" or
+ // "class".
+ if (!TTPD->getName().empty())
+ P.Name = TTPD->getNameAsString();
+ if (TTPD->hasDefaultArgument()) {
+ P.Default.emplace();
+ llvm::raw_string_ostream Out(*P.Default);
+ TTPD->getDefaultArgument().getArgument().print(PP, Out);
+ }
+ }
+ TempParameters.push_back(std::move(P));
+ }
- if (isa<TranslationUnitDecl>(DC))
- return std::string("global namespace");
- if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
- return typeDeclToString(TD);
- else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
- return namedDeclQualifiedName(ND, "namespace");
- else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
- return namedDeclQualifiedName(FD, "function");
+ return TempParameters;
+}
- return None;
+static llvm::Optional<Range> getTokenRange(SourceLocation Loc,
+ const ASTContext &Ctx) {
+ if (!Loc.isValid())
+ return llvm::None;
+ SourceLocation End = Lexer::getLocForEndOfToken(
+ Loc, 0, Ctx.getSourceManager(), Ctx.getLangOpts());
+ if (!End.isValid())
+ return llvm::None;
+ return halfOpenToRange(Ctx.getSourceManager(),
+ CharSourceRange::getCharRange(Loc, End));
}
/// Generate a \p Hover object given the declaration \p D.
-static Hover getHoverContents(const Decl *D) {
- Hover H;
- llvm::Optional<std::string> NamedScope = getScopeName(D);
+static HoverInfo getHoverContents(const Decl *D) {
+ HoverInfo HI;
+ const ASTContext &Ctx = D->getASTContext();
- // Generate the "Declared in" section.
- if (NamedScope) {
- assert(!NamedScope->empty());
+ HI.NamespaceScope = getNamespaceScope(D);
+ HI.LocalScope = getLocalScope(D);
- H.contents.value += "Declared in ";
- H.contents.value += *NamedScope;
- H.contents.value += "\n\n";
+ PrintingPolicy Policy = printingPolicyForDecls(Ctx.getPrintingPolicy());
+ if (const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D)) {
+ HI.Documentation = getDeclComment(Ctx, *ND);
+ HI.Name = printName(Ctx, *ND);
}
- // We want to include the template in the Hover.
- if (TemplateDecl *TD = D->getDescribedTemplate())
- D = TD;
-
- std::string DeclText;
- llvm::raw_string_ostream OS(DeclText);
-
- PrintingPolicy Policy =
- printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
+ HI.Kind = indexSymbolKindToSymbolKind(index::getSymbolInfo(D).Kind);
- D->print(OS, Policy);
+ // Fill in template params.
+ if (const TemplateDecl *TD = D->getDescribedTemplate()) {
+ HI.TemplateParameters =
+ fetchTemplateParameters(TD->getTemplateParameters(), Policy);
+ D = TD;
+ } else if (const FunctionDecl *FD = D->getAsFunction()) {
+ if (const auto FTD = FD->getDescribedTemplate()) {
+ HI.TemplateParameters =
+ fetchTemplateParameters(FTD->getTemplateParameters(), Policy);
+ D = FTD;
+ }
+ }
- OS.flush();
+ // Fill in types and params.
+ if (const FunctionDecl *FD = D->getAsFunction()) {
+ HI.ReturnType.emplace();
+ llvm::raw_string_ostream OS(*HI.ReturnType);
+ FD->getReturnType().print(OS, Policy);
+
+ HI.Parameters.emplace();
+ for (const ParmVarDecl *PVD : FD->parameters()) {
+ HI.Parameters->emplace_back();
+ auto &P = HI.Parameters->back();
+ if (!PVD->getType().isNull()) {
+ P.Type.emplace();
+ llvm::raw_string_ostream OS(*P.Type);
+ PVD->getType().print(OS, Policy);
+ } else {
+ std::string Param;
+ llvm::raw_string_ostream OS(Param);
+ PVD->dump(OS);
+ OS.flush();
+ elog("Got param with null type: {0}", Param);
+ }
+ if (!PVD->getName().empty())
+ P.Name = PVD->getNameAsString();
+ if (PVD->hasDefaultArg()) {
+ P.Default.emplace();
+ llvm::raw_string_ostream Out(*P.Default);
+ PVD->getDefaultArg()->printPretty(Out, nullptr, Policy);
+ }
+ }
+ // FIXME: handle variadics.
+ } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
+ HI.Type.emplace();
+ llvm::raw_string_ostream OS(*HI.Type);
+ VD->getType().print(OS, Policy);
+ }
- H.contents.value += DeclText;
- return H;
+ HI.Definition = printDefinition(D);
+ return HI;
}
/// Generate a \p Hover object given the type \p T.
-static Hover getHoverContents(QualType T, ASTContext &ASTCtx) {
- Hover H;
- std::string TypeText;
- llvm::raw_string_ostream OS(TypeText);
+static HoverInfo getHoverContents(QualType T, const Decl *D,
+ ASTContext &ASTCtx) {
+ HoverInfo HI;
+ llvm::raw_string_ostream OS(HI.Name);
PrintingPolicy Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
T.print(OS, Policy);
- OS.flush();
- H.contents.value += TypeText;
- return H;
+
+ if (D)
+ HI.Kind = indexSymbolKindToSymbolKind(index::getSymbolInfo(D).Kind);
+ return HI;
}
/// Generate a \p Hover object given the macro \p MacroDecl.
-static Hover getHoverContents(MacroDecl Decl, ParsedAST &AST) {
+static HoverInfo getHoverContents(MacroDecl Decl, ParsedAST &AST) {
+ HoverInfo HI;
SourceManager &SM = AST.getASTContext().getSourceManager();
- std::string Definition = Decl.Name;
+ HI.Name = Decl.Name;
+ HI.Kind = indexSymbolKindToSymbolKind(
+ index::getSymbolInfoForMacro(*Decl.Info).Kind);
+ // FIXME: Populate documentation
+ // FIXME: Pupulate parameters
// Try to get the full definition, not just the name
SourceLocation StartLoc = Decl.Info->getDefinitionLoc();
@@ -586,14 +723,12 @@
unsigned StartOffset = SM.getFileOffset(StartLoc);
unsigned EndOffset = SM.getFileOffset(EndLoc);
if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
- Definition = Buffer.substr(StartOffset, EndOffset - StartOffset).str();
+ HI.Definition =
+ ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
+ .str();
}
}
-
- Hover H;
- H.contents.kind = MarkupKind::PlainText;
- H.contents.value = "#define " + Definition;
- return H;
+ return HI;
}
namespace {
@@ -607,14 +742,11 @@
/// a deduced type set. The AST should be improved to simplify this scenario.
class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
SourceLocation SearchedLocation;
- llvm::Optional<QualType> DeducedType;
public:
DeducedTypeVisitor(SourceLocation SearchedLocation)
: SearchedLocation(SearchedLocation) {}
- llvm::Optional<QualType> getDeducedType() { return DeducedType; }
-
// Handle auto initializers:
//- auto i = 1;
//- decltype(auto) i = 1;
@@ -626,8 +758,10 @@
return true;
if (auto *AT = D->getType()->getContainedAutoType()) {
- if (!AT->getDeducedType().isNull())
+ if (!AT->getDeducedType().isNull()) {
DeducedType = AT->getDeducedType();
+ this->D = D;
+ }
}
return true;
}
@@ -655,13 +789,17 @@
const AutoType *AT = D->getReturnType()->getContainedAutoType();
if (AT && !AT->getDeducedType().isNull()) {
DeducedType = AT->getDeducedType();
+ this->D = D;
} else if (auto DT = dyn_cast<DecltypeType>(D->getReturnType())) {
// auto in a trailing return type just points to a DecltypeType and
// getContainedAutoType does not unwrap it.
- if (!DT->getUnderlyingType().isNull())
+ if (!DT->getUnderlyingType().isNull()) {
DeducedType = DT->getUnderlyingType();
+ this->D = D;
+ }
} else if (!D->getReturnType().isNull()) {
DeducedType = D->getReturnType();
+ this->D = D;
}
return true;
}
@@ -680,16 +818,19 @@
const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr());
while (DT && !DT->getUnderlyingType().isNull()) {
DeducedType = DT->getUnderlyingType();
- DT = dyn_cast<DecltypeType>(DeducedType->getTypePtr());
+ D = DT->getAsTagDecl();
+ DT = dyn_cast<DecltypeType>(DeducedType.getTypePtr());
}
return true;
}
+
+ QualType DeducedType;
+ const Decl *D = nullptr;
};
} // namespace
/// Retrieves the deduced type at a given location (auto, decltype).
-llvm::Optional<QualType> getDeducedType(ParsedAST &AST,
- SourceLocation SourceLocationBeg) {
+bool hasDeducedType(ParsedAST &AST, SourceLocation SourceLocationBeg) {
Token Tok;
auto &ASTCtx = AST.getASTContext();
// Only try to find a deduced type if the token is auto or decltype.
@@ -697,18 +838,16 @@
Lexer::getRawToken(SourceLocationBeg, Tok, ASTCtx.getSourceManager(),
ASTCtx.getLangOpts(), false) ||
!Tok.is(tok::raw_identifier)) {
- return {};
+ return false;
}
AST.getPreprocessor().LookUpIdentifierInfo(Tok);
if (!(Tok.is(tok::kw_auto) || Tok.is(tok::kw_decltype)))
- return {};
-
- DeducedTypeVisitor V(SourceLocationBeg);
- V.TraverseAST(AST.getASTContext());
- return V.getDeducedType();
+ return false;
+ return true;
}
-llvm::Optional<Hover> getHover(ParsedAST &AST, Position Pos) {
+llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos) {
+ llvm::Optional<HoverInfo> HI;
const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
SourceLocation SourceLocationBeg =
getBeginningOfIdentifier(AST, Pos, SourceMgr.getMainFileID());
@@ -716,16 +855,23 @@
auto Symbols = getSymbolAtPosition(AST, SourceLocationBeg);
if (!Symbols.Macros.empty())
- return getHoverContents(Symbols.Macros[0], AST);
-
- if (!Symbols.Decls.empty())
- return getHoverContents(Symbols.Decls[0]);
-
- auto DeducedType = getDeducedType(AST, SourceLocationBeg);
- if (DeducedType && !DeducedType->isNull())
- return getHoverContents(*DeducedType, AST.getASTContext());
+ HI = getHoverContents(Symbols.Macros[0], AST);
+ else if (!Symbols.Decls.empty())
+ HI = getHoverContents(Symbols.Decls[0]);
+ else {
+ if (!hasDeducedType(AST, SourceLocationBeg))
+ return None;
+
+ DeducedTypeVisitor V(SourceLocationBeg);
+ V.TraverseAST(AST.getASTContext());
+ if (!V.DeducedType.isNull())
+ HI = getHoverContents(V.DeducedType, V.D, AST.getASTContext());
+ else
+ return None;
+ }
- return None;
+ HI->SymRange = getTokenRange(SourceLocationBeg, AST.getASTContext());
+ return HI;
}
std::vector<Location> findReferences(ParsedAST &AST, Position Pos,
@@ -748,7 +894,7 @@
auto MainFileRefs = findRefs(Symbols.Decls, AST);
for (const auto &Ref : MainFileRefs) {
Location Result;
- Result.range = getTokenRange(AST, Ref.Loc);
+ Result.range = getTokenRange(AST.getASTContext(), Ref.Loc);
Result.uri = URIForFile::canonicalize(*MainFilePath, *MainFilePath);
Results.push_back(std::move(Result));
}
@@ -991,5 +1137,47 @@
return Result;
}
+MarkupContent HoverInfo::render() const {
+ MarkupContent Content;
+ Content.kind = MarkupKind::PlainText;
+ std::vector<std::string> Output;
+
+ if (LocalScope && NamespaceScope) {
+ llvm::raw_string_ostream Out(Content.value);
+ Out << "Declared in ";
+ if (LocalScope->empty() && NamespaceScope->empty())
+ Out << "global namespace";
+ else if (NamespaceScope->empty())
+ Out << *LocalScope;
+ else if (LocalScope->empty())
+ Out << *NamespaceScope;
+ else
+ Out << *NamespaceScope << "::" << *LocalScope;
+ Out << "\n\n";
+ }
+
+ if (!Definition.empty()) {
+ Output.push_back(Definition);
+ } else {
+ // Builtin types
+ Output.push_back(Name);
+ }
+ Content.value += llvm::join(Output, " ");
+ return Content;
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+ const HoverInfo::Param &P) {
+ std::vector<llvm::StringRef> Output;
+ if (P.Type)
+ Output.push_back(*P.Type);
+ if (P.Name)
+ Output.push_back(*P.Name);
+ OS << llvm::join(Output, " ");
+ if (P.Default)
+ OS << " = " << *P.Default;
+ return OS;
+}
+
} // namespace clangd
} // namespace clang
Index: clang-tools-extra/clangd/Protocol.cpp
===================================================================
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -17,6 +17,7 @@
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/JSON.h"
Index: clang-tools-extra/clangd/ClangdServer.h
===================================================================
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -180,7 +180,7 @@
/// Get code hover for a given position.
void findHover(PathRef File, Position Pos,
- Callback<llvm::Optional<Hover>> CB);
+ Callback<llvm::Optional<HoverInfo>> CB);
/// Get information about type hierarchy for a given position.
void typeHierarchy(PathRef File, Position Pos, int Resolve,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===================================================================
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -456,8 +456,8 @@
}
void ClangdServer::findHover(PathRef File, Position Pos,
- Callback<llvm::Optional<Hover>> CB) {
- auto Action = [Pos](Callback<llvm::Optional<Hover>> CB,
+ Callback<llvm::Optional<HoverInfo>> CB) {
+ auto Action = [Pos](Callback<llvm::Optional<HoverInfo>> CB,
llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===================================================================
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -842,7 +842,20 @@
void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Callback<llvm::Optional<Hover>> Reply) {
Server->findHover(Params.textDocument.uri.file(), Params.position,
- std::move(Reply));
+ Bind(
+ [](decltype(Reply) Reply,
+ llvm::Expected<llvm::Optional<HoverInfo>> HIorErr) {
+ if (!HIorErr)
+ return Reply(HIorErr.takeError());
+ const auto &HI = HIorErr.get();
+ if (!HI)
+ return Reply(llvm::None);
+ Hover H;
+ H.range = HI->SymRange;
+ H.contents = HI->render();
+ return Reply(H);
+ },
+ std::move(Reply)));
}
void ClangdLSPServer::onTypeHierarchy(
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits