Files
lucisv/crates/lucisv_server/src/completion/member.rs
T
Guoliang ChenandClaude Mythos 5.2 aa2259bfe1 Round 12: pure-move splits and hygiene
Splits resolve.rs, parser/item.rs, parser/instance.rs, format/stmt.rs and
lexer.rs (really 771 lines); moves 23 inline test modules of lucisv_server
to their own files; reasons on all 12 bare #[ignore]; the giant-line
references test times the real request; sites.py default root.
Output over 4,046 OpenTitan files byte-identical to a479faf.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:39:56 -08:00

383 lines
17 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The member answer: after a `.` or a `::`, the members of what stands
//! before it and nothing else.
//!
//! Exclusive, exactly as the backtick response is: a member name is the only
//! thing that may be written here. Two sources feed one list — the buffer's
//! own `Semantics` for the chain this file declares, the workspace index for
//! the rest — and one shape has no readable head at all: the `.` that opens a
//! connection or a parameter override inside an instantiation, which lists
//! the module's ports or parameters instead. See
//! `docs/features/class-member-access/README.md` and
//! `docs/features/completion-core/README.md`.
use std::collections::HashSet;
use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::connection::{self, Connection};
use super::site::balanced;
use super::tiers::innermost_scope;
use super::word::{Sep, Word};
use super::{completion_kind, declaration_detail, Items, FUZZY_MIN, TIER_MEMBER};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query, Score};
use crate::signature;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
/// **The member answer**: after a `.` or a `::`, the members of what stands
/// before it and nothing else.
///
/// Exclusive, exactly as the backtick response is, and for the same reason: a
/// member name is the only thing that may be written here, so a keyword, a
/// template or an identifier used three files away is not a worse answer but
/// a wrong one. Until this round the cursor after a dot got the whole-index
/// dump — 512 items of everything — which is what this replaces.
///
/// **One resolution walk.** The site comes from
/// [`vlog_semantic::Semantics::member_site`] (or `unit_site` for a `::`),
/// which is literally the prefix `resolve::member_of` runs before looking a
/// tail up; the in-file `extends` chain comes from `member_scopes`, which is
/// literally the walk `member_in_chain` runs; the cross-file list comes from
/// `WorkspaceIndex::members_of_chain`, which is literally the hop chain
/// `member_chain` walks. So every name offered here is a name hover and
/// go-to-definition resolve, and there is no second resolver to disagree.
///
/// `None` — **no popup at all** — when the head cannot be read (a call, a
/// cast, whitespace in the spine) or cannot be resolved (an untyped head, a
/// type this crate knows has no members, a chain it cannot finish). A guess
/// after a dot is worse than silence. A site that *is* resolved always
/// answers with a list, even an empty one, because an empty list is itself
/// the answer here.
pub(super) fn member_answer(
ws: &Workspace,
doc: &Document,
word: &Word,
offset: u32,
snippets: bool,
) -> Option<CompletionResponse> {
let members = match word.spine.as_ref() {
Some(spine) => {
let semantics = &doc.semantics;
let from = innermost_scope(semantics, word.start)?;
let site = match word.sep? {
Sep::Dot => semantics.member_site(from, &spine.head, &spine.mids),
Sep::Scope => semantics.unit_site(from, &spine.head),
}?;
members_at(semantics, doc, ws.index(), &site)
}
// Nothing readable before the dot. One shape is still a real
// question, and it is the commonest completion position in RTL there
// is: a `.` opening a connection or a parameter override.
None => match word.sep? {
Sep::Dot => connection_members(ws, doc, word, snippets)?,
Sep::Scope => return None,
},
};
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
// the same `Query` every other tier scores with.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let mut matched: Vec<Member> = match &fuzzy {
None => members
.into_iter()
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(Member, Score)> = members
.into_iter()
.filter_map(|member| {
let score = query.score(&member.name)?;
Some((member, score))
})
.collect();
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
hits.into_iter().map(|(member, _)| member).collect()
}
};
// A connection list's already-connected ports go after the rest, each
// group in the order it was matched in (`completion-ux`, TODO §68.1).
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
let mut items = Items::new(doc, word.range(offset));
for member in matched {
if items.full() {
break;
}
let kind = completion_kind(member.kind);
match member.connection {
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
}
}
// **The `isIncomplete` trap, in its member form.** The request that
// matters is the one the trigger character fires, with nothing typed
// after the separator: that answer is the whole member list, so it is
// complete, and VS Code filters it client-side for the rest of the name
// with its own subsequence matcher — which is the behaviour this feature
// wants. A 1- or 2-character answer is a *prefix* slice of that list, and
// the third keystroke would widen it to a subsequence match, so it must
// say so or the widening never reaches the client. Above the floor the
// ordinary rule stands: appending a character only shrinks a subsequence
// hit set, so only the cap can make the answer partial.
items.incomplete |= fuzzy.is_none() && !word.text.is_empty();
// An **empty** answer is always incomplete, whatever was typed. Two
// reasons, and the second is the one QA found (finding 2, 2026-09-02): an
// empty list is never a satisfying final answer, and a *cold* index — the
// scope ladder has not widened to the directory the declaring file is in
// yet — answers empty for a moment and correctly a moment later. Marked
// complete, VS Code would cache the emptiness and the user would have to
// retype the dot; marked incomplete, the next keystroke picks up the real
// list. It costs one extra request in the one case where the request is
// cheapest, because there was nothing to build.
items.incomplete |= items.items.is_empty();
Some(items.into_list())
}
/// One member of a site, as the list needs it: everything an item carries and
/// nothing that would cost a file read.
struct Member {
name: String,
kind: SymbolKind,
detail: String,
/// What a connection list's entry carries beyond its name; `None` for
/// every other member.
connection: Option<Connection>,
}
/// What a member declared **in another file** shows beside its name.
///
/// **Table-only, because it must be.** A `Def` in the index carries no text,
/// and reading the declaring file on a keystroke is the one thing no answer
/// here may do (completion-core, *Every tier is a table lookup*). So the card
/// is the kind label plus the declared type name, which is all the table
/// holds. A member of the **buffer being typed in** does better — see
/// [`declaration_detail`], which tier 1 has always used and which the in-file
/// half of every member list uses too.
fn indexed_detail(kind: SymbolKind, type_name: Option<&str>) -> String {
let label = kind_label(kind);
match type_name {
Some(ty) => format!("{label} — {ty}"),
None => label.to_string(),
}
}
/// Every member of a site, nearest declaration first, each name once.
///
/// A name declared in more than one place on the chain is offered by the
/// **nearest** — a subclass's override rather than the base's original, which
/// is the same first-hit-wins rule the lookup itself applies, so the item and
/// the declaration a lookup finds are the same declaration.
///
/// An in-file class whose `extends` leaves the file gets both halves: its own
/// scopes for as far as this file declares the chain, then the index's list
/// for the base and everything above it.
fn members_at(
semantics: &Semantics,
doc: &Document,
index: &WorkspaceIndex,
site: &MemberSite,
) -> Vec<Member> {
let mut members = Members::new();
// A cross-file site says which surface its own tail resolution reads, and
// the list follows it: behind `u_x.` in an *expression* that is the
// module's hierarchical surface — its nets, variables and instances as
// well as its ports and parameters — which is exactly what the in-file
// `MemberSite::Scope` half above offers for an instance this file
// declares. A connection list's `.` never arrives here; it is
// `connection_members` below, and it is the connection surface.
let mut surface = Surface::Connection;
let base = match site {
MemberSite::Scope(scope) => {
let (scopes, base) = semantics.member_scopes(*scope);
for id in scopes {
let Some(scope) = semantics.scope(id) else { continue };
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
// The index keys by the last `::` segment, exactly as the
// overlay's own inheritance chase does.
base.map(|path| last_segment(&path).to_string())
}
MemberSite::Unit { path, surface: reads } => {
surface = *reads;
Some(path.clone())
}
};
if let Some(unit) = base {
for (name, def) in index.members_of_chain_in(&unit, surface) {
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
members.into_vec()
}
/// The names that may be written after the `.` of a connection or a parameter
/// override: the instantiated module's **ports**, or its **parameters**.
///
/// This is the answer at the commonest completion position in RTL there is,
/// and until it existed the position got the whole-index dump. Three
/// deliberate choices:
///
/// * **The list is `signature.rs`'s.** [`signature::enclosing_list`] already
/// works out which module's `(…)` or `#(…)` the cursor sits in, for the
/// signature card that hangs above this very popup. A second answer to that
/// question would eventually disagree with the card.
/// * **The scope is `Target::Port`'s.** In-file it is
/// [`vlog_semantic::Semantics::instantiable_scope`], literally the call the
/// resolution makes; across files it is the module's member table, which
/// `member_chain` reads for the same use and which exports ports and
/// parameters and nothing else. Either/or, never merged — a module this
/// file declares has *answered*, exactly as the resolution has it.
/// * **Filtered to the kind the list admits.** A module scope also binds its
/// nets and its instances, and `.internal_sig(w)` is not a connection —
/// class-member-access's ruling, in the other direction. This narrows the
/// list to what may legally be written; it never offers a name the
/// resolution could not find.
///
/// Ports already connected elsewhere in the same list stay on offer, marked
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
/// popup — when the cursor is not in such a list at all, or is inside a
/// connected *expression* (`.clk(` opens a paren of its own).
fn connection_members(
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
) -> Option<Vec<Member>> {
let dot = word.start.checked_sub(1)?;
let list = signature::enclosing_list(&doc.tokens, word.start)?;
let open = doc.tokens.get(list.open)?.span.end;
// The dot has to stand directly in the list. Inside `.clk( … )` the
// parentheses since the list opened do not balance, and a port name is
// not what may be written there.
if !balanced(&doc.tokens, open, word.start) {
return None;
}
// `Param` and **not** `LocalParam`: this is the one place in the whole
// server where the two kinds part. A `localparam` in a header is derived
// inside the module and overriding it is illegal, so it may not be
// offered here — QA finding 1, 2026-09-02, on `prim_fifo_sync`'s
// `localparam int DepthW = prim_util_pkg::vbits(Depth+1)`. Everywhere
// else a localparam is a parameter: it is exported, hovered, iconed and
// highlighted the same, and `u_fifo.DepthW` resolves.
let wanted = match list.kind {
signature::Kind::Params => SymbolKind::Param,
signature::Kind::Ports => SymbolKind::Port,
};
let taken = connected_names(&doc.tokens, list.open, dot);
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
let mut members = Members::new();
let mut push = |name: &str, kind: SymbolKind, detail: String| {
let connection = entry.connection(name, taken.contains(name));
members.push_member(Member {
name: name.to_string(),
kind,
detail,
connection: Some(connection),
});
};
match doc.semantics.instantiable_scope(&list.module) {
// This file declares the module: its own scope is the whole answer,
// and no other file's module of the same name may override it.
Some(scope) => {
let scope = doc.semantics.scope(scope)?;
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
if symbol.kind == wanted {
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
}
None => {
for (name, defs) in ws.index().members_of(&list.module) {
let Some(def) = defs.first() else { continue };
if def.kind == wanted {
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
}
}
Some(members.into_vec())
}
/// Every `.name` already written at the top level of the list opened by the
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
/// typed, which must stay on offer.
///
/// In a sixty-port instantiation the fifty-five already connected are the ones
/// the user is *not* looking for, so they sort after the rest and say so; they
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
/// twice by mistake is exactly the one a user goes looking for. A re-edited
/// entry is not marked, because its own dot is the one `skip` names.
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
let mut taken = HashSet::new();
let mut depth = 0i32;
let mut dot: Option<u32> = None;
for token in tokens.iter().skip(open + 1) {
if token.kind == TokenKind::Symbol {
match token.text.as_str() {
"(" => depth += 1,
")" if depth == 0 => break,
")" => depth -= 1,
"." if depth == 0 => {
dot = Some(token.span.start);
continue;
}
_ => {}
}
}
if let Some(at) = dot.take() {
if at != skip && token.kind == TokenKind::Ident {
taken.insert(token.text.as_str());
}
}
}
taken
}
/// The members gathered so far, each name kept once — the **nearest**
/// declaration of a shadowed name, which is the first-hit-wins rule every
/// lookup on the same chain applies.
struct Members {
out: Vec<Member>,
seen: HashSet<String>,
}
impl Members {
fn new() -> Members {
Members { out: Vec::new(), seen: HashSet::new() }
}
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
}
fn push_member(&mut self, member: Member) {
if self.seen.insert(member.name.clone()) {
self.out.push(member);
}
}
fn into_vec(self) -> Vec<Member> {
self.out
}
}
/// The last `::` segment of a possibly-qualified path — the name the
/// workspace index's member and inheritance tables are keyed by, and the same
/// cut `vlog_semantic`'s own overlay makes before asking them.
fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}
#[cfg(test)]
mod tests;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com