Serve type hierarchy from observer class facts

Occurrences carry their result type uid, decoded types are retained per
editor entry, and a bounded core selects direct bases and inverse
subtypes. The server advertises typeHierarchyProvider and serves
prepareTypeHierarchy, supertypes and subtypes. Registered feature tests
cover the selection; a real stdio session prepared DerivedA and
returned Base as supertype and DerivedA/DerivedB as subtypes of Base.
This commit is contained in:
faumaray committed 2026-12-05 23:36:05 +03:00
1 parent b1c8a4a625
commit 86b9923532
14 files changed
+357 -15

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ add_library(vls_protocol STATIC src/Protocol/Framing.cpp src/Protocol/Json.cpp
src/Build/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp src/Build/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp
src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.cpp src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.cpp
src/semantic/Diagnostics.cpp src/semantic/SourceCatalog.cpp src/semantic/StockCompiler.cpp src/semantic/EditorDiagnostics.cpp src/semantic/Occurrences.cpp src/scheduler/Scheduler.cpp src/semantic/Diagnostics.cpp src/semantic/SourceCatalog.cpp src/semantic/StockCompiler.cpp src/semantic/EditorDiagnostics.cpp src/semantic/Occurrences.cpp src/scheduler/Scheduler.cpp
src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/features/SemanticTokens.cpp src/features/InlayHints.cpp src/features/FileOperations.cpp src/features/IncludeUpdate.cpp src/features/CallHierarchy.cpp src/features/CodeLens.cpp src/features/DocumentLinks.cpp src/features/Formatting.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/features/SemanticTokens.cpp src/features/InlayHints.cpp src/features/FileOperations.cpp src/features/IncludeUpdate.cpp src/features/CallHierarchy.cpp src/features/CodeLens.cpp src/features/DocumentLinks.cpp src/features/Formatting.cpp src/features/TypeHierarchy.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp)
target_include_directories(vls_protocol PUBLIC "${PROJECT_SOURCE_DIR}/include") target_include_directories(vls_protocol PUBLIC "${PROJECT_SOURCE_DIR}/include")
target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode Void::Text Void::Crypto Void::System) target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode Void::Text Void::Crypto Void::System)
target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic)
+3 -1
View File
@@ -80,6 +80,7 @@ void build(Void::Build::Project &project) {
"src/features/CodeLens.cpp", "src/features/CodeLens.cpp",
"src/features/DocumentLinks.cpp", "src/features/DocumentLinks.cpp",
"src/features/Formatting.cpp", "src/features/Formatting.cpp",
"src/features/TypeHierarchy.cpp",
"src/debug/live/LiveSession.cpp", "src/debug/live/LiveSession.cpp",
"src/modules/ModuleWorkQueue.cpp", "src/modules/ModuleWorkQueue.cpp",
"src/modules/GccScan.cpp", "src/modules/GccScan.cpp",
@@ -163,7 +164,8 @@ void build(Void::Build::Project &project) {
"tests/features/SemanticTokensTests.cpp", "tests/features/InlayHintsTests.cpp", "tests/features/SemanticTokensTests.cpp", "tests/features/InlayHintsTests.cpp",
"tests/features/FileOperationsTests.cpp", "tests/features/IncludeUpdateTests.cpp", "tests/features/FileOperationsTests.cpp", "tests/features/IncludeUpdateTests.cpp",
"tests/features/CallHierarchyTests.cpp", "tests/features/CodeLensTests.cpp", "tests/features/CallHierarchyTests.cpp", "tests/features/CodeLensTests.cpp",
"tests/features/DocumentLinksTests.cpp", "tests/features/FormattingTests.cpp"}); "tests/features/DocumentLinksTests.cpp", "tests/features/FormattingTests.cpp",
"tests/features/TypeHierarchyTests.cpp"});
auto live_worker = project.executable("vls_live_worker_fixture"); auto live_worker = project.executable("vls_live_worker_fixture");
live_worker.cxx_standard(CxxStandard::Cxx26) live_worker.cxx_standard(CxxStandard::Cxx26)
.sources({"tests/debug/LiveWorkerFixture.cpp"}) .sources({"tests/debug/LiveWorkerFixture.cpp"})
+17
View File
@@ -79,6 +79,23 @@ the upgraded snapshot (keeping `snapshot.prev.json`) and rewrites a legacy
about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then
passed 18/18. passed 18/18.
## December 5 type hierarchy over LSP
Occurrences now carry their result type uid, decoded types are retained per
editor entry, and the server serves `textDocument/prepareTypeHierarchy`,
`typeHierarchy/supertypes` and `typeHierarchy/subtypes` (advertised as
`typeHierarchyProvider`). A bounded core
(`vls/features/TypeHierarchy.hpp`) selects direct bases and inverse subtypes,
with registered `vls_feature_tests` cases (104 total).
Real stdio session with `Base`, two derived classes and two factory calls:
```
prepareTypeHierarchy: [('DerivedA', 5)]
supertypes: ['Base']
subtypes: ['DerivedA', 'DerivedB']
```
All 18 native suites and all 18 CMake tests passed.
## December 5 observer-reported type hierarchy facts ## December 5 observer-reported type hierarchy facts
The stock observer now records, for each call whose result is a class type, the The stock observer now records, for each call whose result is a class type, the
@@ -92,6 +92,7 @@ struct use_entry {
char type[max_type + 1]{}; char type[max_type + 1]{};
char canonical[max_type + 1]{}; char canonical[max_type + 1]{};
char signature[max_signature + 1]{}; char signature[max_signature + 1]{};
unsigned result_type_uid{};
bool conflict{}; bool conflict{};
}; };
@@ -729,6 +730,9 @@ void record_use(tree call, tree decl) {
} }
if (result_type && TYPE_P(result_type)) { if (result_type && TYPE_P(result_type)) {
record_type(result_type); record_type(result_type);
if (find_type(TYPE_UID(result_type))) {
entry.result_type_uid = TYPE_UID(result_type);
}
} }
const char *signature = decl_as_string(decl, TFF_SCOPE | TFF_RETURN_TYPE); const char *signature = decl_as_string(decl, TFF_SCOPE | TFF_RETURN_TYPE);
if (signature && std::strlen(signature) <= max_signature && utf8_valid(signature)) { if (signature && std::strlen(signature) <= max_signature && utf8_valid(signature)) {
@@ -858,6 +862,9 @@ void finish(void *, void *) {
json_string(out, use.type); json_string(out, use.type);
std::fputs(",\"canonicalType\":", out); std::fputs(",\"canonicalType\":", out);
json_string(out, use.canonical); json_string(out, use.canonical);
if (use.result_type_uid) {
std::fprintf(out, ",\"resultTypeUid\":%u", use.result_type_uid);
}
if (use.signature[0]) { if (use.signature[0]) {
std::fputs(",\"signature\":", out); std::fputs(",\"signature\":", out);
json_string(out, use.signature); json_string(out, use.signature);
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace vls::features::type_hierarchy {
struct Position {
std::uint32_t line{}, character{};
auto operator<=>(const Position &) const = default;
};
struct Range {
Position start, end;
auto operator<=>(const Range &) const = default;
};
// One compiler-proven type name occurrence.
struct TypeRef {
std::uint32_t uid{};
std::string name;
std::string path;
Range range;
auto operator<=>(const TypeRef &) const = default;
};
struct Type {
TypeRef self;
std::vector<TypeRef> bases;
};
struct Limits {
std::size_t items{256};
};
// Direct bases of TARGET, deduplicated by identity and bounded.
[[nodiscard]] std::vector<TypeRef> supertypes(std::span<const Type>, const TypeRef &target,
const Limits & = Limits{});
// Types whose direct bases contain TARGET, deduplicated by identity and bounded.
[[nodiscard]] std::vector<TypeRef> subtypes(std::span<const Type>, const TypeRef &target,
const Limits & = Limits{});
} // namespace vls::features::type_hierarchy
@@ -81,6 +81,13 @@ class EditorDiagnostics {
// Calls made inside a prepared item's function. // Calls made inside a prepared item's function.
[[nodiscard]] Void::LanguageServer::Protocol::Json [[nodiscard]] Void::LanguageServer::Protocol::Json
call_hierarchy_outgoing(const Void::LanguageServer::Protocol::Json &item) const; call_hierarchy_outgoing(const Void::LanguageServer::Protocol::Json &item) const;
// Type hierarchy at a call position and from a prepared item.
[[nodiscard]] Void::LanguageServer::Protocol::Json
prepare_type_hierarchy(std::string_view uri, Documents::Position position) const;
[[nodiscard]] Void::LanguageServer::Protocol::Json
type_hierarchy_supertypes(const Void::LanguageServer::Protocol::Json &item) const;
[[nodiscard]] Void::LanguageServer::Protocol::Json
type_hierarchy_subtypes(const Void::LanguageServer::Protocol::Json &item) const;
// Parameter-type hints from the compiler signature, within the range. // Parameter-type hints from the compiler signature, within the range.
[[nodiscard]] Void::LanguageServer::Protocol::Json inlay_hints(std::string_view uri, [[nodiscard]] Void::LanguageServer::Protocol::Json inlay_hints(std::string_view uri,
Documents::Range range) const; Documents::Range range) const;
+3
View File
@@ -22,6 +22,8 @@ struct Occurrence {
// Whole definition extent when the compiler reported one (function body // Whole definition extent when the compiler reported one (function body
// included). Call hierarchy uses it to attribute nested calls. // included). Call hierarchy uses it to attribute nested calls.
std::optional<Documents::Range> extent; std::optional<Documents::Range> extent;
// Uid of the reported class type of this call's result, when present.
std::uint32_t result_type_uid{};
[[nodiscard]] bool has_definition() const noexcept { return definition_file != nullptr; } [[nodiscard]] bool has_definition() const noexcept { return definition_file != nullptr; }
}; };
@@ -29,6 +31,7 @@ struct Occurrence {
struct TypeRef { struct TypeRef {
std::string name, path; std::string name, path;
Documents::Range range; Documents::Range range;
std::uint32_t uid{};
}; };
// A class observed as a call's result type and its direct bases. // A class observed as a call's result type and its direct bases.
struct ReflectedType { struct ReflectedType {
+22 -7
View File
@@ -332,6 +332,8 @@ DispatchResult Server::handle(std::string_view body) {
} }
if (diagnostics_ && diagnostics_->supports_occurrences()) if (diagnostics_ && diagnostics_->supports_occurrences())
capabilities.emplace("callHierarchyProvider", Json{true}); capabilities.emplace("callHierarchyProvider", Json{true});
if (diagnostics_ && diagnostics_->supports_occurrences())
capabilities.emplace("typeHierarchyProvider", Json{true});
if (diagnostics_ && diagnostics_->supports_occurrences()) { if (diagnostics_ && diagnostics_->supports_occurrences()) {
capabilities.emplace("codeLensProvider", capabilities.emplace("codeLensProvider",
Json{Json::Object{{"resolveProvider", Json{false}}}}); Json{Json::Object{{"resolveProvider", Json{false}}}});
@@ -434,7 +436,8 @@ DispatchResult Server::handle(std::string_view body) {
return reply(id, "result", std::move(result)); return reply(id, "result", std::move(result));
} }
if (*method == "textDocument/hover" || *method == "textDocument/definition" || if (*method == "textDocument/hover" || *method == "textDocument/definition" ||
*method == "textDocument/signatureHelp" || *method == "textDocument/documentHighlight") { *method == "textDocument/signatureHelp" || *method == "textDocument/documentHighlight" ||
*method == "textDocument/prepareTypeHierarchy") {
if (!diagnostics_ || !diagnostics_->supports_occurrences()) if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found"); return error(id, -32601, "Method not found");
const auto *uri = as_string(member(member(params, "textDocument"), "uri")); const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
@@ -451,12 +454,13 @@ DispatchResult Server::handle(std::string_view body) {
return error(id, -32602, "Expected textDocument.uri and a bounded position"); return error(id, -32602, "Expected textDocument.uri and a bounded position");
const Void::LanguageServer::Documents::Position selected{ const Void::LanguageServer::Documents::Position selected{
static_cast<std::uint32_t>(*line_value), static_cast<std::uint32_t>(*character_value)}; static_cast<std::uint32_t>(*line_value), static_cast<std::uint32_t>(*character_value)};
auto result = *method == "textDocument/hover" ? diagnostics_->hover(*uri, selected) auto result =
: *method == "textDocument/definition" *method == "textDocument/hover" ? diagnostics_->hover(*uri, selected)
? diagnostics_->definition(*uri, selected) : *method == "textDocument/definition" ? diagnostics_->definition(*uri, selected)
: *method == "textDocument/signatureHelp" : *method == "textDocument/signatureHelp" ? diagnostics_->signature_help(*uri, selected)
? diagnostics_->signature_help(*uri, selected) : *method == "textDocument/documentHighlight"
: diagnostics_->document_highlights(*uri, selected); ? diagnostics_->document_highlights(*uri, selected)
: diagnostics_->prepare_type_hierarchy(*uri, selected);
return reply(id, "result", std::move(result)); return reply(id, "result", std::move(result));
} }
if (*method == "completionItem/resolve") { if (*method == "completionItem/resolve") {
@@ -595,6 +599,17 @@ DispatchResult Server::handle(std::string_view body) {
*uri, {static_cast<std::uint32_t>(*line_value), *uri, {static_cast<std::uint32_t>(*line_value),
static_cast<std::uint32_t>(*character_value)})); static_cast<std::uint32_t>(*character_value)}));
} }
if (*method == "typeHierarchy/supertypes" || *method == "typeHierarchy/subtypes") {
if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found");
const auto *item = member(params, "item");
if (!item)
return error(id, -32602, "Expected a type hierarchy item");
return reply(id, "result",
*method == "typeHierarchy/supertypes"
? diagnostics_->type_hierarchy_supertypes(*item)
: diagnostics_->type_hierarchy_subtypes(*item));
}
if (*method == "callHierarchy/outgoingCalls") { if (*method == "callHierarchy/outgoingCalls") {
if (!diagnostics_ || !diagnostics_->supports_occurrences()) if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found"); return error(id, -32601, "Method not found");
+47
View File
@@ -0,0 +1,47 @@
#include <vls/features/TypeHierarchy.hpp>
#include <set>
#include <tuple>
namespace vls::features::type_hierarchy {
namespace {
using Key = std::tuple<std::string, std::string, std::uint32_t, std::uint32_t>;
Key key_of(const TypeRef &type) {
return {type.name, type.path, type.range.start.line, type.range.start.character};
}
void push_unique(std::vector<TypeRef> &out, std::set<Key> &seen, const TypeRef &type,
const Limits &limits) {
if (out.size() == limits.items)
return;
if (seen.insert(key_of(type)).second)
out.push_back(type);
}
} // namespace
std::vector<TypeRef> supertypes(std::span<const Type> types, const TypeRef &target,
const Limits &limits) {
std::vector<TypeRef> result;
std::set<Key> seen;
for (const auto &type : types) {
if (key_of(type.self) != key_of(target))
continue;
for (const auto &base : type.bases)
push_unique(result, seen, base, limits);
}
return result;
}
std::vector<TypeRef> subtypes(std::span<const Type> types, const TypeRef &target,
const Limits &limits) {
std::vector<TypeRef> result;
std::set<Key> seen;
for (const auto &type : types)
for (const auto &base : type.bases)
if (key_of(base) == key_of(target))
push_unique(result, seen, type.self, limits);
return result;
}
} // namespace vls::features::type_hierarchy
+136
View File
@@ -11,6 +11,7 @@
#include <vls/features/SemanticTokens.hpp> #include <vls/features/SemanticTokens.hpp>
#include <vls/features/SignatureHelp.hpp> #include <vls/features/SignatureHelp.hpp>
#include <vls/features/TextStructure.hpp> #include <vls/features/TextStructure.hpp>
#include <vls/features/TypeHierarchy.hpp>
#include <vls/index/SymbolIndex.hpp> #include <vls/index/SymbolIndex.hpp>
#include <vls/modules/ArtifactCache.hpp> #include <vls/modules/ArtifactCache.hpp>
#include <vls/modules/GccArtifacts.hpp> #include <vls/modules/GccArtifacts.hpp>
@@ -171,6 +172,7 @@ struct Entry {
std::shared_ptr<const Receipt> receipt; std::shared_ptr<const Receipt> receipt;
std::vector<PublishedDiagnostic> published; std::vector<PublishedDiagnostic> published;
std::shared_ptr<const std::vector<Occurrence>> occurrences; std::shared_ptr<const std::vector<Occurrence>> occurrences;
std::shared_ptr<const std::vector<ReflectedType>> types;
std::string occurrence_state{"disabled"}, occurrence_reason; std::string occurrence_state{"disabled"}, occurrence_reason;
std::string module_state{"disabled"}, module_detail; std::string module_state{"disabled"}, module_detail;
std::string module_artifact_state{"disabled"}, module_artifact_detail, std::string module_artifact_state{"disabled"}, module_artifact_detail,
@@ -365,6 +367,8 @@ struct EditorDiagnostics::State {
entry.other_messages = std::move(report.other_messages); entry.other_messages = std::move(report.other_messages);
entry.receipt = std::move(receipt); entry.receipt = std::move(receipt);
if (result->occurrences) { if (result->occurrences) {
entry.types = std::make_shared<const std::vector<ReflectedType>>(
std::move(result->occurrences->types));
entry.occurrences = std::make_shared<const std::vector<Occurrence>>( entry.occurrences = std::make_shared<const std::vector<Occurrence>>(
std::move(result->occurrences->occurrences)); std::move(result->occurrences->occurrences));
entry.occurrence_state = !result->occurrences->complete entry.occurrence_state = !result->occurrences->complete
@@ -1682,6 +1686,138 @@ Json EditorDiagnostics::call_hierarchy_outgoing(const Json &item) const {
return Json{std::move(result)}; return Json{std::move(result)};
} }
namespace {
Json hierarchy_item(const features::type_hierarchy::TypeRef &type) {
const auto range =
range_json(Documents::Range{{type.range.start.line, type.range.start.character},
{type.range.end.line, type.range.end.character}});
Json::Object data{{"uid", Json{static_cast<std::int64_t>(type.uid)}},
{"name", Json{type.name}},
{"path", Json{type.path}},
{"line", Json{static_cast<std::int64_t>(type.range.start.line)}},
{"character", Json{static_cast<std::int64_t>(type.range.start.character)}},
{"endLine", Json{static_cast<std::int64_t>(type.range.end.line)}},
{"endCharacter", Json{static_cast<std::int64_t>(type.range.end.character)}}};
Json::Object item{{"name", Json{type.name}},
{"kind", Json{std::int64_t{5}}},
{"uri", Json{Documents::path_to_file_uri(type.path)}},
{"range", range},
{"selectionRange", range},
{"data", Json{std::move(data)}}};
return Json{std::move(item)};
}
std::optional<features::type_hierarchy::TypeRef> hierarchy_target(const Json &item) {
const auto *fields = P::as_object(&item);
const auto *data = fields ? P::as_object(P::find_member(*fields, "data")) : nullptr;
const auto *name = data ? P::as_string(P::find_member(*data, "name")) : nullptr;
const auto *path = data ? P::as_string(P::find_member(*data, "path")) : nullptr;
const auto line = data ? P::as_int64(P::find_member(*data, "line")) : std::nullopt;
const auto character = data ? P::as_int64(P::find_member(*data, "character")) : std::nullopt;
const auto end_line = data ? P::as_int64(P::find_member(*data, "endLine")) : std::nullopt;
const auto end_character =
data ? P::as_int64(P::find_member(*data, "endCharacter")) : std::nullopt;
const auto uid = data ? P::as_int64(P::find_member(*data, "uid")) : std::nullopt;
if (!name || !path || !line || !character || !end_line || !end_character || !uid)
return std::nullopt;
return features::type_hierarchy::TypeRef{
static_cast<std::uint32_t>(*uid),
*name,
*path,
{{static_cast<std::uint32_t>(*line), static_cast<std::uint32_t>(*character)},
{static_cast<std::uint32_t>(*end_line), static_cast<std::uint32_t>(*end_character)}}};
}
std::vector<features::type_hierarchy::Type>
hierarchy_types(const std::shared_ptr<const std::vector<ReflectedType>> &types) {
std::vector<features::type_hierarchy::Type> result;
if (!types)
return result;
for (const auto &type : *types) {
features::type_hierarchy::Type entry;
entry.self = {type.self.uid,
type.self.name,
type.self.path,
{{type.self.range.start.line, type.self.range.start.character},
{type.self.range.end.line, type.self.range.end.character}}};
for (const auto &base : type.bases)
entry.bases.push_back({base.uid,
base.name,
base.path,
{{base.range.start.line, base.range.start.character},
{base.range.end.line, base.range.end.character}}});
result.push_back(std::move(entry));
}
return result;
}
} // namespace
Json EditorDiagnostics::prepare_type_hierarchy(std::string_view uri,
Documents::Position position) const {
auto &s = *state_;
auto key = Documents::client_uri_key(uri);
std::shared_ptr<const Receipt> receipt;
std::shared_ptr<const std::vector<Occurrence>> facts;
std::shared_ptr<const std::vector<ReflectedType>> types;
{
std::lock_guard lock{s.mutex};
const auto i = key ? s.entries.find(*key) : s.entries.end();
if (i == s.entries.end())
return Json{Json::Array{}};
receipt = i->second.receipt;
facts = i->second.occurrences;
types = i->second.types;
}
if (!receipt || !facts || !types || !s.valid(*receipt))
return Json{Json::Array{}};
const auto *match = covering(*receipt, *facts, *key, position);
if (!match || !match->result_type_uid)
return Json{Json::Array{}};
const auto found = std::ranges::find_if(
*types, [&](const ReflectedType &type) { return type.self.uid == match->result_type_uid; });
if (found == types->end())
return Json{Json::Array{}};
const auto target =
hierarchy_types(types)[static_cast<std::size_t>(found - types->begin())].self;
return Json{Json::Array{hierarchy_item(target)}};
}
Json EditorDiagnostics::type_hierarchy_supertypes(const Json &item) const {
auto &s = *state_;
const auto target = hierarchy_target(item);
if (!target)
return Json{Json::Array{}};
std::vector<features::type_hierarchy::Type> types;
{
std::lock_guard lock{s.mutex};
for (const auto &[key, entry] : s.entries)
for (const auto &type : hierarchy_types(entry.types))
types.push_back(type);
}
Json::Array result;
for (const auto &type : features::type_hierarchy::supertypes(types, *target))
result.push_back(hierarchy_item(type));
return Json{std::move(result)};
}
Json EditorDiagnostics::type_hierarchy_subtypes(const Json &item) const {
auto &s = *state_;
const auto target = hierarchy_target(item);
if (!target)
return Json{Json::Array{}};
std::vector<features::type_hierarchy::Type> types;
{
std::lock_guard lock{s.mutex};
for (const auto &[key, entry] : s.entries)
for (const auto &type : hierarchy_types(entry.types))
types.push_back(type);
}
Json::Array result;
for (const auto &type : features::type_hierarchy::subtypes(types, *target))
result.push_back(hierarchy_item(type));
return Json{std::move(result)};
}
Json EditorDiagnostics::hover(std::string_view uri, Documents::Position position) const { Json EditorDiagnostics::hover(std::string_view uri, Documents::Position position) const {
auto &s = *state_; auto &s = *state_;
auto key = Documents::client_uri_key(uri); auto key = Documents::client_uri_key(uri);
+12 -4
View File
@@ -217,8 +217,9 @@ decode_occurrences(std::string_view report, std::string_view nonce,
return std::unexpected{OccurrenceError::invalid_report}; return std::unexpected{OccurrenceError::invalid_report};
const auto read = [&](const Json *value) -> std::optional<TypeRef> { const auto read = [&](const Json *value) -> std::optional<TypeRef> {
const auto *fields = value ? P::as_object(value) : nullptr; const auto *fields = value ? P::as_object(value) : nullptr;
if (!fields || fields->size() != 6 || !integer(P::find_member(*fields, "uid")) || const auto uid = integer(P::find_member(*fields, "uid"));
!P::as_string(P::find_member(*fields, "name"))) const auto *type_name = P::as_string(P::find_member(*fields, "name"));
if (!fields || fields->size() != 6 || !uid || !type_name)
return std::nullopt; return std::nullopt;
Json::Object trimmed; Json::Object trimmed;
for (const auto *key : {"path", "line", "startByte", "endByte"}) { for (const auto *key : {"path", "line", "startByte", "endByte"}) {
@@ -234,7 +235,8 @@ decode_occurrences(std::string_view report, std::string_view nonce,
auto bound = bind_span(*raw, {}, capture); auto bound = bind_span(*raw, {}, capture);
if (!bound) if (!bound)
return std::nullopt; return std::nullopt;
return TypeRef{std::string{raw->path}, raw->path, bound->second}; return TypeRef{*type_name, raw->path, bound->second,
static_cast<std::uint32_t>(*uid)};
}; };
auto parsed_self = read(self); auto parsed_self = read(self);
if (!parsed_self) if (!parsed_self)
@@ -251,7 +253,7 @@ decode_occurrences(std::string_view report, std::string_view nonce,
std::set<std::tuple<const void *, std::uint32_t, std::uint32_t>> uses; std::set<std::tuple<const void *, std::uint32_t, std::uint32_t>> uses;
for (const auto &item : *items) { for (const auto &item : *items) {
const auto *fields = P::as_object(&item); const auto *fields = P::as_object(&item);
if (!fields || (fields->size() != 5 && fields->size() != 6)) if (!fields || (fields->size() != 5 && fields->size() != 6 && fields->size() != 7))
return std::unexpected{OccurrenceError::invalid_report}; return std::unexpected{OccurrenceError::invalid_report};
const auto *name = P::as_string(P::find_member(*fields, "name")); const auto *name = P::as_string(P::find_member(*fields, "name"));
const auto *type = P::as_string(P::find_member(*fields, "type")); const auto *type = P::as_string(P::find_member(*fields, "type"));
@@ -271,6 +273,12 @@ decode_occurrences(std::string_view report, std::string_view nonce,
.second) .second)
return std::unexpected{OccurrenceError::invalid_report}; return std::unexpected{OccurrenceError::invalid_report};
Occurrence occurrence; Occurrence occurrence;
if (const auto *result_type = P::find_member(*fields, "resultTypeUid")) {
const auto uid = integer(result_type);
if (!uid || *uid < 0 || *uid > std::numeric_limits<std::uint32_t>::max())
return std::unexpected{OccurrenceError::invalid_report};
occurrence.result_type_uid = static_cast<std::uint32_t>(*uid);
}
occurrence.name = *name; occurrence.name = *name;
occurrence.type = *type; occurrence.type = *type;
occurrence.canonical_type = *canonical; occurrence.canonical_type = *canonical;
+1 -1
View File
@@ -22,7 +22,7 @@ vls_test_suite(vls_scheduler_tests scheduler/SchedulerTests.cpp)
vls_test_suite(vls_index_tests index/SymbolIndexTests.cpp) vls_test_suite(vls_index_tests index/SymbolIndexTests.cpp)
vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp) vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp)
vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.cpp) vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.cpp)
vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp features/SemanticTokensTests.cpp features/InlayHintsTests.cpp features/FileOperationsTests.cpp features/IncludeUpdateTests.cpp features/CallHierarchyTests.cpp features/CodeLensTests.cpp features/DocumentLinksTests.cpp features/FormattingTests.cpp) vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp features/SemanticTokensTests.cpp features/InlayHintsTests.cpp features/FileOperationsTests.cpp features/IncludeUpdateTests.cpp features/CallHierarchyTests.cpp features/CodeLensTests.cpp features/DocumentLinksTests.cpp features/FormattingTests.cpp features/TypeHierarchyTests.cpp)
vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp) vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp)
target_link_libraries(vls_live_tests PRIVATE Void::System) target_link_libraries(vls_live_tests PRIVATE Void::System)
add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap) add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap)
@@ -134,13 +134,19 @@ def analyze(work, nonce, admitted, complete=True, partial=None):
check(isinstance(occurrence, dict), "occurrence is not an object") check(isinstance(occurrence, dict), "occurrence is not an object")
check({"name", "type", "canonicalType", "use", "definition"} <= set(occurrence) check({"name", "type", "canonicalType", "use", "definition"} <= set(occurrence)
and set(occurrence) <= {"name", "type", "canonicalType", "signature", and set(occurrence) <= {"name", "type", "canonicalType", "signature",
"use", "definition"}, "use", "definition", "resultTypeUid"},
f"unexpected occurrence keys {sorted(occurrence)}") f"unexpected occurrence keys {sorted(occurrence)}")
name = occurrence["name"] name = occurrence["name"]
check(re.fullmatch(r"[A-Za-z_]\w{0,63}", name, re.ASCII), f"bad name {name!r}") check(re.fullmatch(r"[A-Za-z_]\w{0,63}", name, re.ASCII), f"bad name {name!r}")
check(isinstance(occurrence["type"], str) and occurrence["type"], "bad type") check(isinstance(occurrence["type"], str) and occurrence["type"], "bad type")
check(isinstance(occurrence["canonicalType"], str) and occurrence["canonicalType"], check(isinstance(occurrence["canonicalType"], str) and occurrence["canonicalType"],
"bad canonical type") "bad canonical type")
if "resultTypeUid" in occurrence:
uid = occurrence["resultTypeUid"]
check(type(uid) is int and uid > 0, f"bad resultTypeUid {uid!r}")
check(any(reference["uid"] == uid
for entry in report["types"] for reference in [entry["self"]]),
f"resultTypeUid {uid} has no type entry")
if "signature" in occurrence: if "signature" in occurrence:
signature = occurrence["signature"] signature = occurrence["signature"]
check(isinstance(signature, str) and 0 < len(signature) <= 300, "bad signature") check(isinstance(signature, str) and 0 < len(signature) <= 300, "bad signature")
+50
View File
@@ -0,0 +1,50 @@
#include <vls/features/TypeHierarchy.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <vector>
namespace {
using namespace vls::features::type_hierarchy;
using Void::Testing::expect;
using Void::Testing::require;
TypeRef ref(std::uint32_t uid, std::string name) {
return {uid, std::move(name), "/p/a.cpp", {{0, 0}, {0, 4}}};
}
Type type(std::uint32_t uid, std::string name, std::vector<TypeRef> bases = {}) {
return {ref(uid, std::move(name)), std::move(bases)};
}
} // namespace
VOID_TEST(TypeHierarchy, supertypes_follow_direct_bases) {
const std::vector<Type> types{type(1, "Base"), type(2, "Derived", {ref(1, "Base")}),
type(3, "More", {ref(2, "Derived")})};
const auto result = supertypes(types, ref(2, "Derived"));
require(result.size() == 1);
expect(result.front().name == "Base");
expect(supertypes(types, ref(1, "Base")).empty());
expect(supertypes(types, ref(9, "Absent")).empty());
}
VOID_TEST(TypeHierarchy, subtypes_invert_the_base_relation) {
const std::vector<Type> types{type(1, "Base"), type(2, "Derived", {ref(1, "Base")}),
type(3, "Other", {ref(1, "Base")})};
const auto result = subtypes(types, ref(1, "Base"));
require(result.size() == 2);
expect(result[0].name == "Derived");
expect(result[1].name == "Other");
expect(subtypes(types, ref(2, "Derived")).empty());
}
VOID_TEST(TypeHierarchy, duplicates_are_removed_and_results_bounded) {
const std::vector<Type> types{type(1, "Base"),
type(2, "Derived", {ref(1, "Base"), ref(1, "Base")}),
type(3, "Other", {ref(1, "Base")})};
expect(subtypes(types, ref(1, "Base")).size() == 2);
expect(subtypes(types, ref(1, "Base"), Limits{.items = 1}).size() == 1);
const std::vector<Type> repeated{type(2, "Derived", {ref(1, "Base"), ref(1, "Base")})};
expect(supertypes(repeated, ref(2, "Derived")).size() == 1);
}