LSP §9c: type hierarchy over extends
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 21s

textDocument/prepareTypeHierarchy + typeHierarchy/supertypes/subtypes
for SystemVerilog classes. Supertypes is one computed offset into the
existing resolution machinery — the overlay promotion made cross-file
bare class names answerable, and the offset is the LAST byte of the
extends name span so pkg::base lands in the tail's reference, never
the package's. Subtypes is a workspace census on the callers_of_each
pattern (one sources() pass, prefilter, deterministic sort), matching
the base name as written — 0 of the corpus's 270 extends clauses are
qualified, and the asymmetry with supertypes is documented and pinned
from both directions, including the same-name/different-file
consequence. Ambiguous bases answer every declaration, like
definition. Modules stay on callHierarchy by scope ruling.

lsp-types 0.97 has no server-side typeHierarchyProvider field, so
initialize_value() inserts the one key into the serialized result —
QA's strip-and-compare test proves every other key survives with
identical values. QA also traced the parser to show the degenerate
extends spans the code guards against cannot be constructed, corrected
two README figures the lead applied (the 309 extends count did not
reproduce; 270 does), and pinned the generate-block walk gap as a
scoped choice. Interface classes stay blocked on the parser, pinned.

45 tests added (dev 33 + QA 12), including the real ibex UVM chain
and a 10-deep expansion. The inheritance-edge index want is filed
beside the instantiation-edge Handshake as one future round.

docs/features/type-hierarchy/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 21:35:36 -07:00
1 parent 24e8eab78b
commit bf17ddd1e5
7 files changed
+2028 -6

No files matched your search

+63 -1
View File
@@ -39,6 +39,7 @@ mod sync;
mod templates;
mod tokens;
mod type_def;
mod type_hierarchy;
mod uri;
mod watch;
@@ -79,7 +80,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
code_lens_refresh: code_lens_refresh_support(&params),
show_document: show_document_support(&params),
};
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
connection.initialize_finish(id, initialize_value()?)?;
Server::new(connection, roots, abilities).run()?;
io_threads.join()?;
@@ -285,6 +286,22 @@ fn commands() -> Vec<String> {
commands
}
/// The `initialize` result exactly as it goes on the wire.
///
/// `typeHierarchyProvider` is written in here rather than in [`capabilities`]
/// because `lsp-types` 0.97 models type hierarchy on the *client* side only:
/// `ServerCapabilities` has no field for it, and `experimental` is a different
/// key that no client reads for this. So the one capability this server
/// advertises that the crate cannot spell is inserted into the serialized
/// object, which is the same JSON a field would have produced.
fn initialize_value() -> Result<serde_json::Value, serde_json::Error> {
let mut value = serde_json::to_value(initialize_result())?;
if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) {
caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true));
}
Ok(value)
}
fn initialize_result() -> lsp_types::InitializeResult {
lsp_types::InitializeResult {
capabilities: capabilities(),
@@ -434,6 +451,51 @@ mod tests {
assert!(caps.document_on_type_formatting_provider.is_some());
}
#[test]
fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() {
// `ServerCapabilities` has no `type_hierarchy_provider` field in
// lsp-types 0.97 — the crate models type hierarchy on the client side
// only — so the capability is written into the serialized object. A
// client keys entirely off this key: without it the three requests are
// never sent, however well they are implemented.
let value = initialize_value().expect("the initialize result serializes");
assert_eq!(
value["capabilities"]["typeHierarchyProvider"],
serde_json::json!(true),
"{value:#?}"
);
// And the rest of the object is untouched by the insertion.
assert_eq!(value["capabilities"]["callHierarchyProvider"], serde_json::json!(true));
assert_eq!(value["serverInfo"]["name"], serde_json::json!("lucisv-server"));
}
// QA (2026-08-26): the spot checks above name two fields; this pins the
// whole object instead. `initialize_result()` and `capabilities()` are
// untouched by this round (confirmed against `24e8eab`), so the only way
// the insertion could disturb anything is the one `caps.insert` call
// itself — this proves that byte-for-byte rather than by inspection: pull
// the one inserted key back out and what remains must equal the plain,
// uninserted serialization exactly. A future round that lets the
// insertion clobber an existing key, or that adds a field to
// `ServerCapabilities` under the same JSON name, fails this immediately.
#[test]
fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() {
let mut with_insertion = initialize_value().expect("the initialize result serializes");
let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too");
let caps =
with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object");
assert_eq!(
caps.remove("typeHierarchyProvider"),
Some(serde_json::json!(true)),
"the one key the insertion is supposed to add"
);
assert_eq!(
with_insertion, plain,
"removing the inserted key must restore exactly what capabilities() \
and initialize_result() produce on their own, key for key, value for value"
);
}
#[test]
fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() {
// The trigger set is the feature: a client sends this request on every
+29 -4
View File
@@ -27,8 +27,9 @@ use lsp_types::request::{
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, UnregisterCapability,
WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillSaveWaitUntil,
WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
@@ -48,7 +49,8 @@ use lsp_types::{
SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams,
TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri,
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri,
WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin,
WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams,
WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport,
@@ -62,7 +64,7 @@ use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay,
inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature,
symbols, sync, tokens, type_def, watch,
symbols, sync, tokens, type_def, type_hierarchy, watch,
};
/// What the client said it can do, read once at `initialize` because that is
@@ -585,6 +587,29 @@ impl Server {
to_value(hierarchy::outgoing(&self.workspace, &p.item))
})
}
// The class inheritance tree. Same contract as the call hierarchy
// above: `prepare` answers `null` for a position that is not a
// class name, and the two directions answer one hop each while the
// client drives the expansion.
TypeHierarchyPrepare::METHOD => {
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
})
}
TypeHierarchySupertypes::METHOD => {
decode(request).and_then(|p: TypeHierarchySupertypesParams| {
to_value(type_hierarchy::supertypes(&self.workspace, &p.item))
})
}
TypeHierarchySubtypes::METHOD => {
decode(request).and_then(|p: TypeHierarchySubtypesParams| {
to_value(type_hierarchy::subtypes(&self.workspace, &p.item))
})
}
WorkspaceSymbolRequest::METHOD => {
decode(request).and_then(|p: WorkspaceSymbolParams| {
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
File diff suppressed because it is too large. Load diff
+97
View File
@@ -3539,3 +3539,100 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
const TYPE_BASE: &str = "class type_base;\n int x;\nendclass\n";
const TYPE_MID: &str = "class type_mid extends type_base;\n int y;\nendclass\n";
const TYPE_LEAF: &str = "class type_leaf extends type_mid;\nendclass\n";
#[test]
fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
// What only an e2e test can check: that `typeHierarchyProvider` is
// advertised in the shape a client reads — `lsp-types` has no field for it,
// so it is written into the serialized capabilities by hand — and that an
// item the *client* sends back, rather than one this process still holds,
// is what the two directions are answered from.
let dir = temp_dir("type_hierarchy");
let base = dir.join("type_base.sv");
std::fs::write(&base, TYPE_BASE).expect("write");
let mid = dir.join("type_mid.sv");
std::fs::write(&mid, TYPE_MID).expect("write");
let leaf = dir.join("type_leaf.sv");
std::fs::write(&leaf, TYPE_LEAF).expect("write");
let root = format!("file://{}", dir.display());
let mid_uri = format!("file://{}", mid.display());
let base_uri = format!("file://{}", base.display());
let leaf_uri = format!("file://{}", leaf.display());
// The item a client holds after `prepareTypeHierarchy` and sends back for
// each direction: `type_mid`, declared on lines 0..2 of `type_mid.sv`.
let mid_item = format!(
r#"{{"name":"type_mid","kind":5,"uri":"{mid_uri}","range":{{"start":{{"line":0,"character":0}},"end":{{"line":2,"character":8}}}},"selectionRange":{{"start":{{"line":0,"character":6}},"end":{{"line":0,"character":14}}}}}}"#
);
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(TYPE_MID).expect("json")
)),
// The cursor on the `type_mid` of its own declaration.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":0,"character":8}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"typeHierarchy/supertypes","params":{{"item":{mid_item}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"typeHierarchy/subtypes","params":{{"item":{mid_item}}}}}"#
)),
// A property name is not a class, so there is no hierarchy to open.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":1,"character":7}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let response = |id: u32| -> &serde_json::Value {
messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}"))
};
let capabilities = &response(1)["result"]["capabilities"];
assert_eq!(capabilities["typeHierarchyProvider"], serde_json::json!(true));
let prepared = response(2)["result"].as_array().expect("a list of items");
assert_eq!(prepared.len(), 1, "{prepared:#?}");
assert_eq!(
prepared[0],
serde_json::from_str::<serde_json::Value>(&mid_item).expect("json"),
"the item the client will send back is exactly the one built here"
);
let supertypes = response(3)["result"].as_array().expect("a list of items");
assert_eq!(supertypes.len(), 1, "one base: {supertypes:#?}");
assert_eq!(supertypes[0]["name"], "type_base");
assert_eq!(supertypes[0]["uri"], base_uri.as_str());
assert_eq!(supertypes[0]["kind"], 5, "SymbolKind.Class");
assert_eq!(
supertypes[0]["selectionRange"],
serde_json::json!({
"start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 }
}),
"the base's own name span, in its own file"
);
let subtypes = response(4)["result"].as_array().expect("a list of items");
assert_eq!(subtypes.len(), 1, "one subtype: {subtypes:#?}");
assert_eq!(subtypes[0]["name"], "type_leaf");
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class");
let _ = std::fs::remove_dir_all(&dir);
}