TODO §50 (docs/features/expand-wildcard), the first §8 refactoring. `vlog_refactor::expand_wildcard` (ports/expand.rs): at the cursor's instantiation, every port not explicitly connected becomes `.p(p)` when a same-named net, variable or port is declared in the instance's scope (generate block → parents → module; IEEE 1800 §23.3.2.4 read strictly — a parameter, genvar, type, instance or tf argument does not bind) and `.p()` plus a warning otherwise, in declaration order, replacing the `.*` element through the ports engine's splice and verifier. Refusals: no `.*`, two, a positional list, a `bind` directive, a multi-instance statement, a parse diagnostic in either file, compiler directives in either list, an unknown or twice-declared module, and a `.*` that binds nothing. Server: the lazy code action `lucisv: expand .* (N connections)` and the command `lucisv.expandWildcard`; a title-rewrite bug in the lazy offer path (`counted`) fixed on the way. Corpus: 11 of 21 sites expand (the rest refused honestly); opentitan `hw/`: 9 of 66 (50 are `bind`), each verified, two surfacing real FPV-wrapper drift. 0 of 854 corpus files differ. Dev-dependency vlog_refactor → vlog_formatter (tests). Co-Authored-By: Claude Fable 5.1 <[email protected]>
1004 lines
40 KiB
Rust
1004 lines
40 KiB
Rust
//! Module hinting: the facts an instantiation skeleton is made of, and the
|
|
//! skeleton itself as plain text.
|
|
//!
|
|
//! This is rope's "type hinting drives completion" translated to Verilog. The
|
|
//! workspace index knows which file declares a module; that file's own header
|
|
//! says what the module's parameters and ports are; and the semantics of the
|
|
//! file the user is typing in say which of those ports already have a
|
|
//! same-named signal to bind to. Put together, they are everything a
|
|
//! `sub #( ... ) u_sub ( ... );` needs.
|
|
//!
|
|
//! Nothing here speaks LSP and nothing here does I/O. The caller passes the
|
|
//! defining file's text — it already had to read it — and gets an
|
|
//! [`InstantiationPlan`] whose [`InstantiationPlan::render`] writes plain
|
|
//! Verilog. Tabstops, snippet escaping and completion items are the server's
|
|
//! business; [`InstantiationPlan::render_with`] is the seam it renders through,
|
|
//! so both spellings of the skeleton come out of one layout.
|
|
//!
|
|
//! See `docs/features/refactor-instantiate/README.md`.
|
|
|
|
use std::path::Path;
|
|
|
|
use vlog_parser::ast::{AnsiPort, ItemKind, ListElem, Module, ParamPort, PortList};
|
|
use vlog_parser::parse_source_tolerant;
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_semantic::{Semantics, WorkspaceIndex};
|
|
|
|
use crate::ports::{find_module, visible_in};
|
|
|
|
/// One parameter an instantiation may override, in declaration order.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct PlanParam {
|
|
/// The parameter's name.
|
|
pub name: String,
|
|
/// Its default as the declaration writes it (`8`, `logic [3:0]`), or an
|
|
/// empty string when the declaration gives none.
|
|
pub default: String,
|
|
}
|
|
|
|
/// One port of the module, in declaration order.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct PlanPort {
|
|
/// The port's name.
|
|
pub name: String,
|
|
/// `input`, `output` or `inout`; empty when the declaration writes none
|
|
/// and none is inherited.
|
|
pub dir: String,
|
|
/// Whatever the declaration writes between the direction and the name
|
|
/// (`logic [7:0]`, `wire`, `my_pkg::word_t`); empty for an implicit type.
|
|
///
|
|
/// **Display text**: runs of whitespace are collapsed to one space so that
|
|
/// a port typed with a multi-line anonymous `struct` still reads as one
|
|
/// line in a signature. Nothing writes it into a buffer.
|
|
pub ty: String,
|
|
/// True when a signal of the same name is visible where the instantiation
|
|
/// is being written — the test that decides between `.p(p)` and a
|
|
/// placeholder. Always false when the caller named no site.
|
|
pub auto_connect: bool,
|
|
}
|
|
|
|
impl PlanPort {
|
|
/// The port as a reader wants to see it: `input logic [7:0] data`.
|
|
pub fn label(&self) -> String {
|
|
let mut out = String::new();
|
|
for part in [self.dir.as_str(), self.ty.as_str(), self.name.as_str()] {
|
|
if part.is_empty() {
|
|
continue;
|
|
}
|
|
if !out.is_empty() {
|
|
out.push(' ');
|
|
}
|
|
out.push_str(part);
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
/// Everything an instantiation of one module is written from.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub struct InstantiationPlan {
|
|
/// The module being instantiated.
|
|
pub module: String,
|
|
/// Its overridable parameters, in declaration order.
|
|
pub params: Vec<PlanParam>,
|
|
/// Its ports, in declaration order.
|
|
pub ports: Vec<PlanPort>,
|
|
/// Sentences for the user about what the plan could not be sure of.
|
|
/// Informational: a plan with warnings still renders.
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
/// How the skeleton is laid out where it lands.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Layout {
|
|
/// The whitespace every line after the first begins with — the
|
|
/// indentation of the line the instantiation is written on. The first line
|
|
/// gets none: the caller is already at the cursor.
|
|
pub base: String,
|
|
/// One indentation level, as the buffer's settings spell it.
|
|
pub step: String,
|
|
}
|
|
|
|
impl Default for Layout {
|
|
/// Column zero, two-space steps — `vlog_formatter::Config::default`'s own
|
|
/// indent width, so an untouched skeleton survives a format-on-save.
|
|
fn default() -> Layout {
|
|
Layout { base: String::new(), step: " ".to_string() }
|
|
}
|
|
}
|
|
|
|
/// The file that declares `module`, or why the question has no single answer.
|
|
///
|
|
/// The index is the only thing consulted, so this is a map lookup: it is what
|
|
/// keeps a completion request off the disk for every module the user is *not*
|
|
/// completing.
|
|
pub fn module_definition<'i>(index: &'i WorkspaceIndex, module: &str) -> Result<&'i Path, String> {
|
|
let defs: Vec<_> =
|
|
index.units(module).iter().filter(|def| def.kind.is_instantiable()).collect();
|
|
let [def] = defs.as_slice() else {
|
|
return Err(match defs.len() {
|
|
0 => format!("lucisv indexes no module named `{module}`."),
|
|
_ => format!(
|
|
"`{module}` is declared in more than one indexed file; lucisv will not guess which one to instantiate."
|
|
),
|
|
});
|
|
};
|
|
index.path(def.file).ok_or_else(|| format!("`{module}`'s declaring file is not in scope."))
|
|
}
|
|
|
|
/// Where an instantiation is being written, for the auto-connect question.
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct Site<'a> {
|
|
/// The analysis of the file being typed in — the server already holds one
|
|
/// per open buffer, so this costs nothing.
|
|
pub semantics: &'a Semantics,
|
|
/// The byte offset the instantiation would go at.
|
|
pub offset: u32,
|
|
}
|
|
|
|
/// The plan for instantiating `module`, read from the text of the file that
|
|
/// declares it.
|
|
///
|
|
/// `site` is what makes a port auto-connect; pass `None` where the question
|
|
/// does not arise (signature help asks only what the ports *are*).
|
|
pub fn instantiation_plan(
|
|
module: &str,
|
|
definition: &str,
|
|
site: Option<Site<'_>>,
|
|
) -> Result<InstantiationPlan, String> {
|
|
let (tree, diagnostics) = parse_source_tolerant(definition);
|
|
let Some((declaration, _)) = find_module(&tree, module) else {
|
|
// Two very different stories end here, and telling them apart is the
|
|
// difference between "someone edited the file out from under the
|
|
// index" and "lucisv's parser does not support this syntax" — the
|
|
// second is what an interface-typed ANSI port produces today (see the
|
|
// feature README's Handshakes).
|
|
return Err(match diagnostics.first() {
|
|
Some(problem) => format!(
|
|
"lucisv cannot read `{module}`'s declaration: its file does not parse ({} at line {}), so no instantiation was written.",
|
|
problem.message, problem.line
|
|
),
|
|
None => format!(
|
|
"the file that declared `{module}` no longer declares it, so lucisv cannot write an instantiation of it."
|
|
),
|
|
});
|
|
};
|
|
let mut plan = InstantiationPlan {
|
|
module: module.to_string(),
|
|
params: params(declaration, definition),
|
|
ports: ports(declaration, definition),
|
|
warnings: Vec::new(),
|
|
};
|
|
// lucisv does not preprocess, so a port list split across `` `ifdef`` arms is
|
|
// read straight through: every arm's ports are in the list. That is the
|
|
// honest answer for a *skeleton* — it is a suggestion the user edits, not
|
|
// an edit to code they already wrote — but it is only honest if it is said
|
|
// out loud, because no configuration ever has all of them at once.
|
|
if !declaration.port_directives.is_empty() {
|
|
plan.warnings.push(directive_warning(module, "port list"));
|
|
}
|
|
if !declaration.param_directives.is_empty() {
|
|
plan.warnings.push(directive_warning(module, "parameter list"));
|
|
}
|
|
if let Some(site) = site {
|
|
for port in &mut plan.ports {
|
|
port.auto_connect = visible_in(site.semantics, site.offset, &port.name);
|
|
}
|
|
}
|
|
Ok(plan)
|
|
}
|
|
|
|
fn directive_warning(module: &str, list: &str) -> String {
|
|
format!(
|
|
"`{module}`'s {list} carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm."
|
|
)
|
|
}
|
|
|
|
impl InstantiationPlan {
|
|
/// The instance name the skeleton proposes: `u_` and the module's name,
|
|
/// the convention every RTL style guide in the wild agrees on.
|
|
///
|
|
/// An escaped module name yields an escaped instance name — `u_` glued in
|
|
/// front of a `\name` is not an identifier at all, whereas `\u_name` is.
|
|
pub fn instance_name(&self) -> String {
|
|
match self.module.strip_prefix('\\') {
|
|
Some(bare) => format!("\\u_{bare}"),
|
|
None => format!("u_{}", self.module),
|
|
}
|
|
}
|
|
|
|
/// Whether any name in the plan is an **escaped identifier** (`\my-port`).
|
|
///
|
|
/// Callers that encode the skeleton into a grammar of their own need to
|
|
/// know: an escaped identifier may legally contain `$`, `}` and `\`
|
|
/// (`\cost$`, `\a}b`), which are exactly the metacharacters of LSP's
|
|
/// snippet syntax, and the names are written by the layout rather than
|
|
/// through `hole`, so no per-hole escaping can reach them. The server
|
|
/// answers such a plan with a plain-text insert instead — see
|
|
/// `docs/features/refactor-instantiate/README.md`.
|
|
pub fn has_escaped_identifier(&self) -> bool {
|
|
is_escaped(&self.module)
|
|
|| self.params.iter().any(|p| is_escaped(&p.name) || p.default.contains('\\'))
|
|
|| self.ports.iter().any(|p| is_escaped(&p.name))
|
|
}
|
|
|
|
/// The skeleton as plain Verilog, every fill-in written as its own default.
|
|
pub fn render(&self, layout: &Layout) -> String {
|
|
self.render_with(layout, &mut |_, default| default.to_string())
|
|
}
|
|
|
|
/// The skeleton, with each place the user must fill in written by `hole`.
|
|
///
|
|
/// `hole` is called once per fill-in with a 1-based ordinal and the default
|
|
/// text (which may be empty), in the order the user tabs through them: each
|
|
/// parameter override, then the instance name, then each port that did not
|
|
/// auto-connect. Returning the default unchanged is [`render`]; returning
|
|
/// `${n:default}` is the server's snippet.
|
|
///
|
|
/// [`render`]: InstantiationPlan::render
|
|
pub fn render_with(
|
|
&self,
|
|
layout: &Layout,
|
|
hole: &mut dyn FnMut(usize, &str) -> String,
|
|
) -> String {
|
|
let (base, inner) = (&layout.base, format!("{}{}", layout.base, layout.step));
|
|
let mut out = String::new();
|
|
let mut n = 0usize;
|
|
// The module name needs no `terminate` of its own: both continuations
|
|
// below start with a space, which is what an escaped name wants after
|
|
// it anyway.
|
|
out.push_str(&self.module);
|
|
if !self.params.is_empty() {
|
|
out.push_str(" #(\n");
|
|
for (i, param) in self.params.iter().enumerate() {
|
|
n += 1;
|
|
out.push_str(&inner);
|
|
out.push('.');
|
|
terminate(&mut out, ¶m.name);
|
|
out.push('(');
|
|
terminate(&mut out, &hole(n, ¶m.default));
|
|
out.push(')');
|
|
out.push_str(if i + 1 < self.params.len() { ",\n" } else { "\n" });
|
|
}
|
|
out.push_str(base);
|
|
out.push(')');
|
|
}
|
|
out.push(' ');
|
|
n += 1;
|
|
// Same here: a space always follows the instance name.
|
|
out.push_str(&hole(n, &self.instance_name()));
|
|
out.push_str(" (");
|
|
if self.ports.is_empty() {
|
|
out.push_str(");");
|
|
return out;
|
|
}
|
|
out.push('\n');
|
|
for (i, port) in self.ports.iter().enumerate() {
|
|
let expr = if port.auto_connect {
|
|
port.name.clone()
|
|
} else {
|
|
n += 1;
|
|
hole(n, &port.name)
|
|
};
|
|
out.push_str(&inner);
|
|
out.push('.');
|
|
terminate(&mut out, &port.name);
|
|
out.push('(');
|
|
terminate(&mut out, &expr);
|
|
out.push(')');
|
|
out.push_str(if i + 1 < self.ports.len() { ",\n" } else { "\n" });
|
|
}
|
|
out.push_str(base);
|
|
out.push_str(");");
|
|
out
|
|
}
|
|
}
|
|
|
|
/// Write `text`, plus the space it needs before whatever is written next.
|
|
///
|
|
/// A SystemVerilog escaped identifier runs from its `\` to the next
|
|
/// **whitespace** character (IEEE 1800 §5.6.1), so `.\my-port(sig),` lexes as
|
|
/// one enormous identifier that swallows the parens, the comma and the rest of
|
|
/// the line — and the skeleton no longer parses. Every splice point that is
|
|
/// not already followed by a space goes through here.
|
|
fn terminate(out: &mut String, text: &str) {
|
|
out.push_str(text);
|
|
if ends_escaped(text) {
|
|
out.push(' ');
|
|
}
|
|
}
|
|
|
|
/// Whether `text` ends *inside* an escaped identifier, and so cannot be
|
|
/// followed directly by punctuation.
|
|
///
|
|
/// An escaped identifier is terminated by whitespace and by nothing else, so
|
|
/// the question is exactly whether a `\` survives in the run of characters
|
|
/// after the last whitespace. Conservative by construction: a false positive
|
|
/// writes one harmless extra space.
|
|
pub(crate) fn ends_escaped(text: &str) -> bool {
|
|
text.rsplit(char::is_whitespace).next().unwrap_or(text).contains('\\')
|
|
}
|
|
|
|
/// Whether a declared name is an escaped identifier.
|
|
fn is_escaped(name: &str) -> bool {
|
|
name.starts_with('\\')
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// reading a declaration
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The parameters an instantiation may override.
|
|
///
|
|
/// A `localparam` written in the parameter port list is not one of them — it is
|
|
/// derived inside the module and overriding it is illegal — and a continuation
|
|
/// entry (`#(parameter A = 1, B = 2)`) inherits the keyword of the entry before
|
|
/// it, so the keyword is carried forward rather than read per entry.
|
|
fn params(module: &Module, text: &str) -> Vec<PlanParam> {
|
|
let Some(declared) = &module.param_ports else { return Vec::new() };
|
|
let mut out = Vec::new();
|
|
let mut kw = String::new();
|
|
// A parameter a tolerant parse could not read has no name to override.
|
|
for param in declared.iter().filter_map(ListElem::ok) {
|
|
if let Some(written) = ¶m.kw {
|
|
kw = written.clone();
|
|
}
|
|
if kw == "localparam" || param.name.is_empty() {
|
|
continue;
|
|
}
|
|
out.push(PlanParam { name: param.name.clone(), default: default_text(text, param) });
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A parameter's default as an override list can write it, or nothing.
|
|
///
|
|
/// Two things disqualify one:
|
|
///
|
|
/// * it is written across several lines — the source's own indentation means
|
|
/// nothing inside a `#( ... )` on someone else's line, and re-flowing it
|
|
/// would risk rewriting a string literal's spaces;
|
|
/// * writing it back does not parse, which the probe below asks rather than
|
|
/// guesses, because a skeleton that does not parse hands the user a red
|
|
/// squiggle from our own server.
|
|
///
|
|
/// A default lucisv cannot write back is simply not offered: the tabstop comes
|
|
/// up empty and the user types what they meant.
|
|
///
|
|
/// The probe is what makes this grow with the grammar. An **inline aggregate**
|
|
/// default (`parameter type T = struct packed { logic a; }`) used to fail it —
|
|
/// the override grammar refused a `struct` head — and was dropped; since
|
|
/// TODO §45.3 the same probe passes and the type text is emitted. Only the
|
|
/// multi-line spelling, which the corpus's `common_cells/src/ecc_encode.sv`
|
|
/// writes, is still refused, and by the first rule rather than the second.
|
|
fn default_text(text: &str, param: &ParamPort) -> String {
|
|
let Some(expr) = ¶m.default else { return String::new() };
|
|
let written = slice(text, expr.span).trim();
|
|
if written.is_empty() || written.contains('\n') {
|
|
return String::new();
|
|
}
|
|
// The spaces are the ones `terminate` writes: a default ending in an
|
|
// escaped identifier is legal where the renderer puts it, so the probe
|
|
// must not reject it for want of the space the renderer will supply.
|
|
let probe = format!("module __lucisv_probe;\n m #(.P( {written} )) u ();\nendmodule\n");
|
|
let (_, diagnostics) = parse_source_tolerant(&probe);
|
|
match diagnostics.is_empty() {
|
|
true => written.to_string(),
|
|
false => String::new(),
|
|
}
|
|
}
|
|
|
|
/// The module's ports, in declaration order, however the header declares them.
|
|
fn ports(module: &Module, text: &str) -> Vec<PlanPort> {
|
|
match &module.ports {
|
|
PortList::Ansi(declared) => ansi_ports(declared, text),
|
|
PortList::NonAnsi(declared) => declared
|
|
.iter()
|
|
.filter_map(ListElem::ok)
|
|
.map(|port| {
|
|
let (dir, ty) = non_ansi_type(module, text, &port.name);
|
|
PlanPort { name: port.name.clone(), dir, ty, auto_connect: false }
|
|
})
|
|
.collect(),
|
|
PortList::Empty | PortList::None => Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// ANSI ports, whose direction and type are written in the header itself.
|
|
///
|
|
/// An element that writes neither (`input logic a, b`) inherits both from the
|
|
/// element before it, which is what the language says and what a reader
|
|
/// expects to see spelled out. An element that writes *something* is reported
|
|
/// exactly as written, however partial: guessing what a bare `output q`
|
|
/// defaults to is the language's business, not a hint's.
|
|
fn ansi_ports(declared: &[ListElem<AnsiPort>], text: &str) -> Vec<PlanPort> {
|
|
let mut out: Vec<PlanPort> = Vec::new();
|
|
let (mut dir, mut ty) = (String::new(), String::new());
|
|
// A port a tolerant parse could not read has no name to connect.
|
|
for port in declared.iter().filter_map(ListElem::ok) {
|
|
if port.name.is_empty() {
|
|
continue;
|
|
}
|
|
let written = slice(text, TextRange::new(port.span.start, port.name_span.start));
|
|
let written = written.trim();
|
|
if !written.is_empty() {
|
|
dir = port.dir.clone().unwrap_or_default();
|
|
ty = one_line(written.strip_prefix(dir.as_str()).unwrap_or(written));
|
|
}
|
|
out.push(PlanPort {
|
|
name: port.name.clone(),
|
|
dir: dir.clone(),
|
|
ty: ty.clone(),
|
|
auto_connect: false,
|
|
});
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The direction and type a non-ANSI port gets from its body declaration
|
|
/// (`module m (a); input wire [7:0] a;`). Both are empty when the body
|
|
/// declares no such port — a header that names a port the body forgot.
|
|
fn non_ansi_type(module: &Module, text: &str, name: &str) -> (String, String) {
|
|
for item in &module.items {
|
|
let ItemKind::PortDecl(decl) = &item.kind else { continue };
|
|
if !decl.declarators.iter().any(|d| d.name == name) {
|
|
continue;
|
|
}
|
|
// Every declarator of one statement shares its direction and type, so
|
|
// the type is what stands before the *first* of them.
|
|
let Some(first) = decl.declarators.first() else { continue };
|
|
let written = slice(text, TextRange::new(item.span.start, first.span.start));
|
|
let ty = written.trim().strip_prefix(decl.dir.as_str()).unwrap_or("");
|
|
return (decl.dir.clone(), one_line(ty));
|
|
}
|
|
(String::new(), String::new())
|
|
}
|
|
|
|
fn slice(text: &str, span: TextRange) -> &str {
|
|
text.get(span.as_range()).unwrap_or("")
|
|
}
|
|
|
|
/// Every run of whitespace as one space. Display text only — see
|
|
/// [`PlanPort::ty`].
|
|
fn one_line(text: &str) -> String {
|
|
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
|
}
|
|
|
|
/// The indexed module names matching `query`, sorted and without repeats — the
|
|
/// candidate list a completion offers.
|
|
///
|
|
/// Matching is the index's own: `query` is a case-insensitive *substring*, so
|
|
/// `axi` finds `my_axi_master`, and an empty query matches everything. Modules
|
|
/// only — a package or a typedef is not something to instantiate. A name two
|
|
/// files both declare appears once here and is refused by
|
|
/// [`module_definition`], which is where the ambiguity is explained.
|
|
pub fn module_names<'i>(index: &'i WorkspaceIndex, query: &str) -> Vec<&'i str> {
|
|
let mut out: Vec<&str> = index
|
|
.workspace_symbols(query)
|
|
.into_iter()
|
|
.filter(|hit| hit.container.is_none() && hit.def.kind.is_instantiable())
|
|
.map(|hit| hit.name)
|
|
.collect();
|
|
out.dedup();
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::path::PathBuf;
|
|
use vlog_semantic::analyze;
|
|
|
|
const SUB: &str = "\
|
|
module sub #(
|
|
parameter int WIDTH = 8,
|
|
parameter DEPTH,
|
|
localparam int DERIVED = WIDTH * 2
|
|
) (
|
|
input logic clk,
|
|
input logic rst_n,
|
|
input logic [WIDTH-1:0] data,
|
|
output logic ready
|
|
);
|
|
endmodule
|
|
";
|
|
|
|
fn plan(definition: &str, module: &str) -> InstantiationPlan {
|
|
instantiation_plan(module, definition, None).expect("a plan")
|
|
}
|
|
|
|
fn index_of(files: &[(&str, &str)]) -> WorkspaceIndex {
|
|
WorkspaceIndex::build(files.iter().map(|(p, t)| (PathBuf::from(p), *t)))
|
|
}
|
|
|
|
/// A plan whose auto-connect answers come from `site`'s own text, at the
|
|
/// offset of `needle` in it.
|
|
fn plan_at(definition: &str, module: &str, site: &str, needle: &str) -> InstantiationPlan {
|
|
let (tree, _) = parse_source_tolerant(site);
|
|
let semantics = analyze(&tree, site);
|
|
let offset = site.find(needle).expect("needle present") as u32;
|
|
instantiation_plan(module, definition, Some(Site { semantics: &semantics, offset }))
|
|
.expect("a plan")
|
|
}
|
|
|
|
/// An interface is instantiated exactly as a module is, and since
|
|
/// 2026-09-01 it carries `SymbolKind::Interface`
|
|
/// (`docs/features/interface-semantics/README.md`) — so both unit lookups
|
|
/// here ask `is_instantiable()` and answer what they always did.
|
|
#[test]
|
|
fn an_interface_is_a_unit_this_module_will_instantiate() {
|
|
let index = index_of(&[
|
|
("/rtl/bus_if.sv", "interface bus_if (input logic clk);\nendinterface\n"),
|
|
("/rtl/sub.sv", SUB),
|
|
]);
|
|
assert_eq!(
|
|
module_definition(&index, "bus_if").map(|p| p.display().to_string()),
|
|
Ok("/rtl/bus_if.sv".to_string())
|
|
);
|
|
assert_eq!(module_names(&index, ""), ["bus_if", "sub"]);
|
|
let plan = plan("interface bus_if (input logic clk);\nendinterface\n", "bus_if");
|
|
let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["clk"]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_plan_reads_the_parameters_and_ports_in_declaration_order() {
|
|
let plan = plan(SUB, "sub");
|
|
assert_eq!(
|
|
plan.params,
|
|
vec![
|
|
PlanParam { name: "WIDTH".into(), default: "8".into() },
|
|
PlanParam { name: "DEPTH".into(), default: String::new() },
|
|
],
|
|
"a localparam is not overridable and is not offered"
|
|
);
|
|
let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["clk", "rst_n", "data", "ready"]);
|
|
assert_eq!(plan.ports[2].dir, "input");
|
|
assert_eq!(plan.ports[2].ty, "logic [WIDTH-1:0]");
|
|
assert_eq!(plan.ports[3].label(), "output logic ready");
|
|
assert!(plan.warnings.is_empty(), "{:?}", plan.warnings);
|
|
}
|
|
|
|
#[test]
|
|
fn an_ansi_port_that_writes_nothing_inherits_the_one_before_it() {
|
|
let text = "module m (input logic [3:0] a, b, output wire c);\nendmodule\n";
|
|
let plan = plan(text, "m");
|
|
assert_eq!(plan.ports[1].label(), "input logic [3:0] b", "a, b share a declaration");
|
|
assert_eq!(plan.ports[2].label(), "output wire c");
|
|
}
|
|
|
|
#[test]
|
|
fn a_non_ansi_module_takes_its_types_from_its_body() {
|
|
let text = "\
|
|
module legacy (a, b, q);
|
|
input wire [7:0] a, b;
|
|
output reg q;
|
|
always @(*) q = |(a & b);
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "legacy");
|
|
assert_eq!(plan.ports.len(), 3);
|
|
assert_eq!(plan.ports[0].label(), "input wire [7:0] a");
|
|
assert_eq!(plan.ports[1].label(), "input wire [7:0] b", "the second declarator too");
|
|
assert_eq!(plan.ports[2].label(), "output reg q");
|
|
}
|
|
|
|
#[test]
|
|
fn a_header_port_the_body_never_declares_is_named_without_a_type() {
|
|
let text = "module m (a, b);\n input a;\nendmodule\n";
|
|
let plan = plan(text, "m");
|
|
assert_eq!(plan.ports[1].label(), "b");
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_with_no_ports_and_no_parameters_still_plans() {
|
|
let bare = plan("module bare;\nendmodule\n", "bare");
|
|
assert!(bare.params.is_empty());
|
|
assert!(bare.ports.is_empty());
|
|
assert_eq!(bare.render(&Layout::default()), "bare u_bare ();");
|
|
|
|
let empty_parens = plan("module bare2 ();\nendmodule\n", "bare2");
|
|
assert!(empty_parens.ports.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_with_parameters_and_no_ports_writes_the_override_list_only() {
|
|
let plan = plan("module p #(parameter W = 1) ();\nendmodule\n", "p");
|
|
assert_eq!(plan.render(&Layout::default()), "p #(\n .W(1)\n) u_p ();");
|
|
}
|
|
|
|
#[test]
|
|
fn the_skeleton_is_laid_out_at_the_sites_own_indentation() {
|
|
let layout = Layout { base: " ".to_string(), step: " ".to_string() };
|
|
assert_eq!(
|
|
plan(SUB, "sub").render(&layout),
|
|
"\
|
|
sub #(
|
|
.WIDTH(8),
|
|
.DEPTH()
|
|
) u_sub (
|
|
.clk(clk),
|
|
.rst_n(rst_n),
|
|
.data(data),
|
|
.ready(ready)
|
|
);"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_holes_are_numbered_in_the_order_they_are_tabbed_through() {
|
|
let plan = plan(SUB, "sub");
|
|
let mut seen: Vec<(usize, String)> = Vec::new();
|
|
let rendered = plan.render_with(&Layout::default(), &mut |n, default| {
|
|
seen.push((n, default.to_string()));
|
|
format!("${{{n}:{default}}}")
|
|
});
|
|
let order: Vec<&str> = seen.iter().map(|(_, d)| d.as_str()).collect();
|
|
assert_eq!(order, ["8", "", "u_sub", "clk", "rst_n", "data", "ready"]);
|
|
assert_eq!(seen.iter().map(|(n, _)| *n).collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6, 7]);
|
|
assert!(rendered.contains("${3:u_sub}"), "{rendered}");
|
|
assert!(rendered.contains(".WIDTH(${1:8})"), "{rendered}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_port_with_a_same_named_signal_in_scope_connects_itself() {
|
|
let site = "\
|
|
module top;
|
|
logic clk;
|
|
logic [7:0] data;
|
|
// here
|
|
endmodule
|
|
";
|
|
let plan = plan_at(SUB, "sub", site, "// here");
|
|
let connected: Vec<&str> =
|
|
plan.ports.iter().filter(|p| p.auto_connect).map(|p| p.name.as_str()).collect();
|
|
assert_eq!(connected, ["clk", "data"]);
|
|
// The rest are holes the user fills in; the connected ones are not.
|
|
let rendered = plan.render_with(&Layout::default(), &mut |n, d| format!("${{{n}:{d}}}"));
|
|
assert!(rendered.contains(".clk(clk)"), "{rendered}");
|
|
assert!(rendered.contains(".rst_n(${4:rst_n})"), "{rendered}");
|
|
}
|
|
|
|
#[test]
|
|
fn without_a_site_nothing_auto_connects() {
|
|
assert!(plan(SUB, "sub").ports.iter().all(|p| !p.auto_connect));
|
|
}
|
|
|
|
#[test]
|
|
fn a_signal_declared_in_another_module_does_not_count_as_in_scope() {
|
|
let site = "\
|
|
module other;
|
|
logic clk;
|
|
endmodule
|
|
module top;
|
|
// here
|
|
endmodule
|
|
";
|
|
let plan = plan_at(SUB, "sub", site, "// here");
|
|
assert!(plan.ports.iter().all(|p| !p.auto_connect), "{:?}", plan.ports);
|
|
}
|
|
|
|
#[test]
|
|
fn a_conditional_port_list_lists_every_arm_and_says_so() {
|
|
let text = "\
|
|
module cond (
|
|
input logic clk,
|
|
`ifdef WITH_DEBUG
|
|
input logic dbg,
|
|
`endif
|
|
output logic q
|
|
);
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "cond");
|
|
let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["clk", "dbg", "q"], "every arm's ports");
|
|
assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings);
|
|
assert!(plan.warnings[0].contains("port list"), "{:?}", plan.warnings);
|
|
assert!(plan.warnings[0].contains("`ifdef arm"), "{:?}", plan.warnings);
|
|
}
|
|
|
|
#[test]
|
|
fn a_conditional_parameter_list_warns_too() {
|
|
let text = "\
|
|
module cond #(
|
|
parameter W = 1,
|
|
`ifdef WIDE
|
|
parameter D = 2,
|
|
`endif
|
|
parameter E = 3
|
|
) ();
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "cond");
|
|
assert_eq!(plan.params.len(), 3);
|
|
assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings);
|
|
assert!(plan.warnings[0].contains("parameter list"), "{:?}", plan.warnings);
|
|
}
|
|
|
|
#[test]
|
|
fn a_default_lucisv_could_not_write_back_is_not_offered() {
|
|
// The corpus case: a `parameter type` defaulting to an anonymous
|
|
// multi-line `struct packed`. Pasting it into `#(.T( ... ))` gives
|
|
// text lucisv's own parser rejects, so no default is offered at all.
|
|
let text = "\
|
|
module ecc #(
|
|
parameter int DataWidth = 64,
|
|
parameter type word_t = logic [DataWidth-1:0],
|
|
parameter type encoded_t = struct packed {
|
|
logic parity;
|
|
word_t word;
|
|
}
|
|
) ();
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "ecc");
|
|
assert_eq!(
|
|
plan.params,
|
|
vec![
|
|
PlanParam { name: "DataWidth".into(), default: "64".into() },
|
|
PlanParam { name: "word_t".into(), default: "logic [DataWidth-1:0]".into() },
|
|
PlanParam { name: "encoded_t".into(), default: String::new() },
|
|
]
|
|
);
|
|
let skeleton = plan.render(&Layout::default());
|
|
assert!(skeleton.contains(".encoded_t()"), "{skeleton}");
|
|
let probe = format!("module p;\n{skeleton}\nendmodule\n");
|
|
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_one_line_inline_aggregate_default_is_emitted() {
|
|
// TODO §45.3: the override grammar accepts an inline aggregate, so the
|
|
// probe in `default_text` passes and the type text is offered instead
|
|
// of an empty tabstop. Only the multi-line spelling is still dropped,
|
|
// by the "written across several lines" rule above it.
|
|
let text = "\
|
|
module agg #(
|
|
parameter type packed_t = struct packed {logic parity; logic [7:0] word;},
|
|
parameter type state_e = enum logic [1:0] {IDLE, BUSY}
|
|
) ();
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "agg");
|
|
assert_eq!(
|
|
plan.params,
|
|
vec![
|
|
PlanParam {
|
|
name: "packed_t".into(),
|
|
default: "struct packed {logic parity; logic [7:0] word;}".into(),
|
|
},
|
|
PlanParam {
|
|
name: "state_e".into(),
|
|
default: "enum logic [1:0] {IDLE, BUSY}".into(),
|
|
},
|
|
]
|
|
);
|
|
let skeleton = plan.render(&Layout::default());
|
|
let probe = format!("module p;\n{skeleton}\nendmodule\n");
|
|
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_line_type_is_shown_on_one_line() {
|
|
let text = "\
|
|
module m (
|
|
input struct packed {
|
|
logic a;
|
|
logic b;
|
|
} bus
|
|
);
|
|
endmodule
|
|
";
|
|
assert_eq!(
|
|
plan(text, "m").ports[0].label(),
|
|
"input struct packed { logic a; logic b; } bus"
|
|
);
|
|
}
|
|
|
|
/// Strip a snippet's tabstops back to the text they expand to:
|
|
/// `${n:default}` becomes `default` and `${n}` becomes nothing.
|
|
///
|
|
/// Deliberately naive — it handles exactly the two shapes
|
|
/// `completion.rs::snippet_hole` produces, and it is only ever asked
|
|
/// about plans with no escaped identifier, which is the only case the
|
|
/// server encodes as a snippet at all.
|
|
fn expand(snippet: &str) -> String {
|
|
let mut out = String::new();
|
|
let mut rest = snippet;
|
|
while let Some(at) = rest.find("${") {
|
|
out.push_str(&rest[..at]);
|
|
let Some(close) = rest[at..].find('}') else { break };
|
|
let body = &rest[at + 2..at + close];
|
|
if let Some((_, default)) = body.split_once(':') {
|
|
out.push_str(default);
|
|
}
|
|
rest = &rest[at + close + 1..];
|
|
}
|
|
out.push_str(rest);
|
|
out
|
|
}
|
|
|
|
/// The skeleton, wrapped so it can be parsed as the module item it is.
|
|
fn parses(skeleton: &str) -> bool {
|
|
let probe = format!("module lucisv_probe;\n{skeleton}\nendmodule\n");
|
|
parse_source_tolerant(&probe).1.is_empty()
|
|
}
|
|
|
|
#[test]
|
|
fn an_escaped_identifier_port_renders_a_skeleton_that_parses() {
|
|
// QA's MEDIUM #1. An escaped identifier runs to the next whitespace,
|
|
// so `.\my-port(sig),` is one token that eats the rest of the line.
|
|
let text = "module m (input logic \\my-port , input logic clk);\nendmodule\n";
|
|
let plan = plan(text, "m");
|
|
assert_eq!(plan.ports[0].name, "\\my-port");
|
|
let skeleton = plan.render(&Layout::default());
|
|
assert_eq!(
|
|
skeleton, "m u_m (\n .\\my-port (\\my-port ),\n .clk(clk)\n);",
|
|
"an escaped name is terminated on both sides of the parens"
|
|
);
|
|
assert!(parses(&skeleton), "the plain rendering must parse: {skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn escaped_names_everywhere_still_render_a_plain_skeleton_that_parses() {
|
|
// Module, parameter and port names all escaped, and two of them
|
|
// carrying the snippet grammar's own metacharacters — which is why
|
|
// `has_escaped_identifier` exists and why the server answers such a
|
|
// plan with a plain-text insert.
|
|
let text = "\
|
|
module \\my-mod$1 #(
|
|
parameter \\W}idth = 8
|
|
) (
|
|
input logic \\a}b ,
|
|
output logic q
|
|
);
|
|
endmodule
|
|
";
|
|
let plan = plan(text, "\\my-mod$1");
|
|
assert_eq!(
|
|
plan.instance_name(),
|
|
"\\u_my-mod$1",
|
|
"an escaped module names an escaped instance"
|
|
);
|
|
assert!(plan.has_escaped_identifier(), "the server needs this to pick plain text");
|
|
let skeleton = plan.render(&Layout::default());
|
|
assert!(parses(&skeleton), "the plain rendering must parse:\n{skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_snippet_expands_to_exactly_the_plain_rendering() {
|
|
// The other half of the "one seam" promise: for every plan the server
|
|
// does encode as a snippet, stripping the tabstops gives back the
|
|
// plain text byte for byte — so only one of the two can ever be wrong.
|
|
for (text, module) in [
|
|
(SUB, "sub"),
|
|
("module bare;\nendmodule\n", "bare"),
|
|
("module p #(parameter W = 1) ();\nendmodule\n", "p"),
|
|
] {
|
|
let plan = plan(text, module);
|
|
assert!(!plan.has_escaped_identifier(), "{module} is the snippet-encodable case");
|
|
let snippet =
|
|
plan.render_with(&Layout::default(), &mut |n, default| match default.is_empty() {
|
|
true => format!("${{{n}}}"),
|
|
false => format!("${{{n}:{default}}}"),
|
|
});
|
|
let plain = plan.render(&Layout::default());
|
|
assert_eq!(expand(&snippet), plain, "{module}");
|
|
assert!(parses(&plain), "{module}: {plain}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_plan_with_no_escaped_identifier_says_so() {
|
|
assert!(!plan(SUB, "sub").has_escaped_identifier());
|
|
let with_default = "module m #(parameter P = \\esc$1 ) ();\nendmodule\n";
|
|
assert!(
|
|
plan(with_default, "m").has_escaped_identifier(),
|
|
"an escaped identifier inside a default counts too"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_default_ending_in_an_escaped_identifier_is_kept_and_terminated() {
|
|
// The probe in `default_text` writes the same spaces the renderer
|
|
// does, so a legal escaped default is not dropped for want of one.
|
|
let text = "module m #(parameter P = \\esc-1 ) ();\nendmodule\n";
|
|
let plan = plan(text, "m");
|
|
assert_eq!(plan.params[0].default, "\\esc-1");
|
|
let skeleton = plan.render(&Layout::default());
|
|
assert!(skeleton.contains(".P(\\esc-1 )"), "{skeleton}");
|
|
assert!(parses(&skeleton), "{skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_name_that_only_looks_escaped_is_left_alone() {
|
|
assert!(ends_escaped("\\my-port"));
|
|
assert!(!ends_escaped("logic [7:0]"));
|
|
assert!(!ends_escaped("\\a b"), "already terminated by its own space");
|
|
assert!(!ends_escaped(""));
|
|
}
|
|
|
|
#[test]
|
|
fn an_unknown_module_is_refused_by_name() {
|
|
let index = index_of(&[("a.sv", "module a;\nendmodule\n")]);
|
|
let message = module_definition(&index, "nope").expect_err("unknown");
|
|
assert!(message.contains("indexes no module named `nope`"), "{message}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_declared_twice_is_refused_rather_than_guessed() {
|
|
let index =
|
|
index_of(&[("a.sv", "module dup;\nendmodule\n"), ("b.sv", "module dup;\nendmodule\n")]);
|
|
let message = module_definition(&index, "dup").expect_err("ambiguous");
|
|
assert!(message.contains("more than one indexed file"), "{message}");
|
|
assert!(message.contains("will not guess"), "{message}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_known_module_names_its_file() {
|
|
let index = index_of(&[("a.sv", "module a;\nendmodule\n"), ("b.sv", SUB)]);
|
|
assert_eq!(module_definition(&index, "sub").expect("found"), Path::new("b.sv"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_definition_that_no_longer_declares_the_module_is_refused() {
|
|
// The file the index pointed at has been edited since; a skeleton
|
|
// invented from nothing would be worse than a sentence.
|
|
let message =
|
|
instantiation_plan("sub", "module other;\nendmodule\n", None).expect_err("gone");
|
|
assert!(message.contains("no longer declares it"), "{message}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_definition_that_does_not_parse_says_so_rather_than_blaming_an_edit() {
|
|
// QA's LOW finding: "no longer declares it" reads as "someone changed
|
|
// the file", which is the wrong story when the real cause is a syntax
|
|
// lucisv's parser does not support.
|
|
let message = instantiation_plan("sub", "moduel sub (;;;\n", None).expect_err("garbage");
|
|
assert!(message.contains("does not parse"), "{message}");
|
|
assert!(!message.contains("no longer declares it"), "{message}");
|
|
}
|
|
|
|
#[test]
|
|
fn an_interface_typed_port_list_is_planned_like_any_other() {
|
|
// Was the disclosed `vlog_parser` gap: an interface-typed ANSI port
|
|
// (`iface_bus.mst bus`) as the first, direction-less element stopped
|
|
// the header from parsing, so no module was produced at all and the
|
|
// refusal had to name the real cause. `docs/features/ansi-first-port`
|
|
// closed it, so the plan is now the ordinary one — an interface port
|
|
// has no direction, and its type is the interface (with its modport)
|
|
// exactly as written.
|
|
let text = "module m (iface_bus.mst bus, input logic clk);\nendmodule\n";
|
|
let plan = plan(text, "m");
|
|
assert_eq!(plan.ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["bus", "clk"]);
|
|
assert_eq!(plan.ports[0].dir, "");
|
|
assert_eq!(plan.ports[0].ty, "iface_bus.mst");
|
|
assert_eq!(plan.ports[1].dir, "input");
|
|
assert_eq!(plan.ports[1].ty, "logic");
|
|
let skeleton = plan.render(&Layout::default());
|
|
assert!(skeleton.contains(".bus("), "{skeleton}");
|
|
assert!(parses(&skeleton), "{skeleton}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_candidate_list_is_the_indexs_modules_and_nothing_else() {
|
|
let index = index_of(&[
|
|
("a.sv", "module alpha;\nendmodule\nmodule beta;\nendmodule\n"),
|
|
("p.sv", "package pkg;\n localparam K = 1;\nendpackage\n"),
|
|
]);
|
|
assert_eq!(module_names(&index, ""), ["alpha", "beta"], "no package, no member");
|
|
assert_eq!(module_names(&index, "al"), ["alpha"], "a substring narrows it");
|
|
assert_eq!(module_names(&index, "ET"), ["beta"], "case-insensitively, anywhere");
|
|
assert!(module_names(&index, "zzz").is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_name_two_files_declare_appears_once_in_the_candidates() {
|
|
let index =
|
|
index_of(&[("a.sv", "module dup;\nendmodule\n"), ("b.sv", "module dup;\nendmodule\n")]);
|
|
assert_eq!(module_names(&index, "dup"), ["dup"]);
|
|
}
|
|
}
|