TODO section 18. Typing a dot used to get the whole-index dump (every keyword and project word, capped at 512); now the answer after a separator is exclusively the members of what precedes it, or nothing. The prefix walk is published from vlog_semantic as MemberSite / Semantics::member_site / WorkspaceIndex::members_of_chain and the resolver's own member_of, unit_member, member_in_chain and follow_one are rewritten to call it - one walk, so the popup cannot list a member hover would not resolve (pinned structurally). Inherited members ride the same base chain; this./super./pkg::/cls:: are the same question. A headless dot inside an instantiation's (...) or #(...) lists the module's ports or parameters through signature.rs's own list detector and the Target::Port walk, already-connected ports dropped. Trigger characters '.' and ':'. Measured cheaper than the dump it replaces (6-62 us vs 212 us). QA's finding fixed at the root: the binder had discarded ParamPort.kw and bound every localparam as Param, so #(. offered prim_fifo_sync's DepthW. SymbolKind::LocalParam, keyword sticky across continuation entries as instantiate::params reads it, exported wherever Param is, 'localparam' on the hover card, excluded from the override list only. FACTS_FORMAT 9 -> 10. Also carried: TODO sections 19 and 20 (the escaped-identifier and constraint-body plans) and the topo rows for both lanes. Co-Authored-By: Claude Fable 5 <[email protected]>
1926 lines
76 KiB
Rust
1926 lines
76 KiB
Rust
//! Module port signature changes: add a port, remove a port, propagate the
|
|
//! ports a single instantiation is missing.
|
|
//!
|
|
//! Read top-to-bottom, each one is the same four steps: find the module (or
|
|
//! the instantiation) the request names, work out the *plan* — one edit per
|
|
//! place the signature is written down, plus a sentence for every place lucisv
|
|
//! deliberately left alone — verify the whole plan in memory, and hand it back
|
|
//! or refuse it whole. A refusal is a sentence for the user, never a partial
|
|
//! edit.
|
|
//!
|
|
//! Unlike a rename, these refactorings write and delete text, so they cannot
|
|
//! use the rename verifier's "the token stream may not change shape" contract.
|
|
//! They use [`check::verify_splice`] instead, plus a **shape** check of their
|
|
//! own (`confirm`) that reads the edited text back and asserts the port list
|
|
//! and the connection lists now say exactly what the plan promised. See
|
|
//! `docs/features/refactor-ports/README.md`.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use vlog_parser::ast::{
|
|
Connections, GenBlock, GenElse, Instance, Instantiation, Item, ItemKind, Module, PortList,
|
|
SourceFile,
|
|
};
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_parser::token::{Token, TokenKind};
|
|
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
|
|
use vlog_semantic::{Semantics, SymbolKind};
|
|
|
|
use crate::rename::{display, Scope};
|
|
use crate::{check, RefactorEdit, TextEdit};
|
|
|
|
/// Which module a port refactoring acts on.
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub enum ModuleRef<'a> {
|
|
/// The module declared under this name. It must be declared exactly once
|
|
/// in the in-scope files: lucisv does not guess between two of them.
|
|
Name(&'a str),
|
|
/// The module whose declaration covers this byte offset.
|
|
At {
|
|
/// One of the in-scope files.
|
|
file: &'a Path,
|
|
/// A byte offset inside the module's declaration.
|
|
offset: u32,
|
|
},
|
|
}
|
|
|
|
/// One refactoring an editor can offer at a position, computed in full.
|
|
///
|
|
/// The title is written here rather than in the server so that Vim, VS Code
|
|
/// and any future CLI say the same thing.
|
|
#[derive(Debug, Clone)]
|
|
pub struct PortAction {
|
|
/// What the lightbulb says.
|
|
pub title: String,
|
|
/// The edit it applies, already verified.
|
|
pub edit: RefactorEdit,
|
|
}
|
|
|
|
/// Add one ANSI port declaration to a module, and a connection for it to every
|
|
/// instantiation of that module in the in-scope files.
|
|
///
|
|
/// `decl` is the one piece of free-form input any of these refactorings takes
|
|
/// (`input logic [7:0] cfg`), so it is parsed as a port declaration before
|
|
/// anything else happens, and the edited files are re-parsed afterwards.
|
|
pub fn add_port(
|
|
files: &[(PathBuf, String)],
|
|
module: ModuleRef<'_>,
|
|
decl: &str,
|
|
) -> Result<RefactorEdit, String> {
|
|
let port = parse_port_decl(decl)?;
|
|
let mut scope = Scope::build(files);
|
|
let site = locate_module(&mut scope, module)?;
|
|
let plan = plan_add(&mut scope, &site, &port)?;
|
|
let what = format!("adding port `{}` to `{}`", port.name, site.name);
|
|
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
|
|
}
|
|
|
|
/// Remove the port at `offset` from its module, and its named connection from
|
|
/// every instantiation in the in-scope files.
|
|
pub fn remove_port(
|
|
files: &[(PathBuf, String)],
|
|
file: &Path,
|
|
offset: u32,
|
|
) -> Result<RefactorEdit, String> {
|
|
Ok(removal(files, file, offset)?.0)
|
|
}
|
|
|
|
/// The removal, the port's name, and how many instantiations it rewrites.
|
|
fn removal(
|
|
files: &[(PathBuf, String)],
|
|
file: &Path,
|
|
offset: u32,
|
|
) -> Result<(RefactorEdit, String, usize), String> {
|
|
let mut scope = Scope::build(files);
|
|
let (site, port) = locate_port(&mut scope, file, offset)?;
|
|
let plan = plan_remove(&mut scope, &site, &port)?;
|
|
let what = format!("removing port `{port}` from `{}`", site.name);
|
|
let (edit, sites) = finish(&mut scope, plan, &site.name, &what)?;
|
|
Ok((edit, port, sites))
|
|
}
|
|
|
|
/// Add the named connections one instantiation is missing, from the
|
|
/// instantiated module's own declaration.
|
|
pub fn propagate_ports(
|
|
files: &[(PathBuf, String)],
|
|
file: &Path,
|
|
offset: u32,
|
|
) -> Result<RefactorEdit, String> {
|
|
let mut scope = Scope::build(files);
|
|
let (site, plan) = plan_propagate(&mut scope, file, offset)?;
|
|
let what = format!("connecting the missing ports of `{}`", site.name);
|
|
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
|
|
}
|
|
|
|
/// Every port refactoring available at a position, each with its edit already
|
|
/// computed and verified — which is what lets a code action carry its own
|
|
/// `WorkspaceEdit` instead of a command the editor has to resolve.
|
|
///
|
|
/// Nothing is offered for a position where the refactoring would be refused:
|
|
/// a lightbulb that only ever explains itself is worse than no lightbulb.
|
|
pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec<PortAction> {
|
|
let mut out = Vec::new();
|
|
let here = files.iter().find(|(path, _)| path == file).map(|(_, text)| text.as_str());
|
|
if !here.is_some_and(|text| may_have_port_action(text, offset)) {
|
|
return out;
|
|
}
|
|
if let Ok((edit, port, sites)) = removal(files, file, offset) {
|
|
out.push(PortAction {
|
|
title: format!("lucisv: remove port `{port}` ({})", sites_phrase(sites)),
|
|
edit,
|
|
});
|
|
}
|
|
if let Ok(edit) = propagate_ports(files, file, offset) {
|
|
let missing = edit.edit_count();
|
|
out.push(PortAction {
|
|
title: format!(
|
|
"lucisv: connect {missing} missing port{}",
|
|
if missing == 1 { "" } else { "s" }
|
|
),
|
|
edit,
|
|
});
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether a position could carry a port refactoring at all, judged from one
|
|
/// file's own text: is it inside a module's port element, inside a non-ANSI
|
|
/// port declaration, or inside an instantiation?
|
|
///
|
|
/// This is a **cheap** question — one parse of one file, no workspace, no I/O —
|
|
/// and it exists because a `textDocument/codeAction` request arrives on every
|
|
/// cursor move. Materializing the in-scope files and building an index for a
|
|
/// cursor sitting in the middle of an `always` block would stall the editor for
|
|
/// a fifth of a second on a large workspace; this answers `false` in
|
|
/// microseconds. It never says `false` where a refactoring would have
|
|
/// succeeded: every one of the three starts by locating exactly one of these
|
|
/// three constructs.
|
|
///
|
|
/// Exactly [`port_action_modules`] asked for emptiness — one walk, two
|
|
/// readers, so the gate and the fan-out cannot come to disagree about which
|
|
/// positions carry an action.
|
|
pub fn may_have_port_action(text: &str, offset: u32) -> bool {
|
|
!port_action_modules(text, offset).is_empty()
|
|
}
|
|
|
|
/// Every module name a port refactoring at this position could act on: the
|
|
/// module an instantiation under the cursor names, or the module whose port
|
|
/// the cursor sits on.
|
|
///
|
|
/// [`may_have_port_action`]'s own walk, saying *which* module it found rather
|
|
/// than only that it found one — which is what lets a server hand
|
|
/// [`port_actions`] the handful of files that module fans out to instead of
|
|
/// the whole workspace. Empty for exactly the positions the gate refuses.
|
|
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut instantiations = Vec::new();
|
|
collect_instantiations(&tree.items, &mut instantiations);
|
|
let named: Vec<String> = instantiations
|
|
.iter()
|
|
.filter(|instantiation| {
|
|
instantiation.module_span.contains(offset)
|
|
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
|
|
})
|
|
.map(|instantiation| instantiation.module.clone())
|
|
.collect();
|
|
if !named.is_empty() {
|
|
return named;
|
|
}
|
|
let mut module = None;
|
|
module_at(&tree.items, offset, &mut module);
|
|
let Some((name, (module, _))) =
|
|
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
|
|
else {
|
|
return Vec::new();
|
|
};
|
|
if declared_ports(module).iter().any(|port| port.span.contains(offset)) {
|
|
return vec![name];
|
|
}
|
|
let on_body_declaration = module.items.iter().any(|item| match &item.kind {
|
|
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
|
|
_ => false,
|
|
});
|
|
match on_body_declaration {
|
|
true => vec![name],
|
|
false => Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// The module whose declaration covers this offset — what
|
|
/// `ModuleRef::At { file, offset }` will resolve to.
|
|
///
|
|
/// The fan-out question for the *command* path, which takes a position
|
|
/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with
|
|
/// a `Position` names the module the cursor is inside, and a server working
|
|
/// out which files that refactoring needs has to name it the same way
|
|
/// `locate_module` will.
|
|
pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut module = None;
|
|
module_at(&tree.items, offset, &mut module);
|
|
module
|
|
}
|
|
|
|
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
|
/// in scope".
|
|
fn sites_phrase(sites: usize) -> String {
|
|
match sites {
|
|
0 => "no instantiation in scope".to_string(),
|
|
1 => "updates 1 instantiation".to_string(),
|
|
n => format!("updates {n} instantiations"),
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// the plan
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Everything a port refactoring wants done, before it is verified.
|
|
#[derive(Default)]
|
|
struct Plan {
|
|
/// Source index → the edits for that file, sorted.
|
|
edits: Vec<(usize, Vec<TextEdit>)>,
|
|
warnings: Vec<String>,
|
|
/// What the edited text must say afterwards, per file.
|
|
expected: Vec<(usize, Shape)>,
|
|
/// How many instantiations the plan rewrites — what a code action's title
|
|
/// promises the user.
|
|
sites: usize,
|
|
}
|
|
|
|
impl Plan {
|
|
/// Add one file's edits to the plan.
|
|
fn add(&mut self, file: usize, mut edits: Vec<TextEdit>) {
|
|
if edits.is_empty() {
|
|
return;
|
|
}
|
|
if let Some((_, existing)) = self.edits.iter_mut().find(|(i, _)| *i == file) {
|
|
existing.append(&mut edits);
|
|
} else {
|
|
self.edits.push((file, edits));
|
|
}
|
|
}
|
|
|
|
/// Sort every file's edits and refuse two that overlap — a caller cannot
|
|
/// apply those, so the plan is abandoned before it is verified.
|
|
fn settle(&mut self) -> Result<(), String> {
|
|
for (_, edits) in &mut self.edits {
|
|
edits.sort_by_key(|e| (e.range.start, e.range.end));
|
|
for pair in edits.windows(2) {
|
|
let (a, b) = (&pair[0], &pair[1]);
|
|
if b.range.start < a.range.end {
|
|
return Err(OVERLAP.to_string());
|
|
}
|
|
}
|
|
}
|
|
self.edits.sort_by_key(|(i, _)| *i);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
const OVERLAP: &str = "two of the edits lucisv computed overlap, so it made none.";
|
|
|
|
/// Verify a plan and turn it into the refactoring's answer.
|
|
fn finish(
|
|
scope: &mut Scope,
|
|
mut plan: Plan,
|
|
module: &str,
|
|
what: &str,
|
|
) -> Result<(RefactorEdit, usize), String> {
|
|
plan.settle()?;
|
|
if plan.edits.is_empty() {
|
|
return Err(format!("lucisv found nothing to change for {what}."));
|
|
}
|
|
check::verify_splice(scope, &plan.edits, module, what)?;
|
|
confirm(scope, &plan, module, what)?;
|
|
|
|
let mut edits: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
|
for (i, file_edits) in plan.edits {
|
|
let Some(path) = scope.path(i) else {
|
|
return Err(format!("lucisv could not name one of the files it edited for {what}."));
|
|
};
|
|
edits.push((path.to_path_buf(), file_edits));
|
|
}
|
|
edits.sort_by(|a, b| a.0.cmp(&b.0));
|
|
Ok((RefactorEdit { edits, warnings: plan.warnings }, plan.sites))
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// the shape check
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// What one file says about a module's signature: the module's own declared
|
|
/// port names, and every instantiation's connection names in order (`""` for a
|
|
/// positional connection, `"*"` for the wildcard).
|
|
///
|
|
/// This is the "did it do what it said" check. `verify_splice` proves the edit
|
|
/// is lexically and semantically honest; nothing in it proves the new text
|
|
/// landed in the *port list* rather than in the parameter list, so the plan
|
|
/// also states the shape it expects and the shape is read back.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
struct Shape {
|
|
ports: Option<Vec<String>>,
|
|
instances: Vec<(String, Vec<String>)>,
|
|
}
|
|
|
|
fn shape(text: &str, module: &str) -> Shape {
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut out = Shape::default();
|
|
if let Some((declaration, _)) = find_module(&tree, module) {
|
|
out.ports = Some(declared_ports(declaration).into_iter().map(|p| p.name).collect());
|
|
}
|
|
let mut instantiations = Vec::new();
|
|
collect_instantiations(&tree.items, &mut instantiations);
|
|
for instantiation in instantiations {
|
|
if instantiation.module != module {
|
|
continue;
|
|
}
|
|
for instance in &instantiation.instances {
|
|
let names = match &instance.conns {
|
|
Connections::Named(conns) => conns.iter().map(|c| c.name.clone()).collect(),
|
|
Connections::Ordered(conns) => conns.iter().map(|_| String::new()).collect(),
|
|
};
|
|
out.instances.push((instance.name.clone(), names));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Read the edited text back and require it to say what the plan promised.
|
|
fn confirm(scope: &Scope, plan: &Plan, module: &str, what: &str) -> Result<(), String> {
|
|
for (i, expected) in &plan.expected {
|
|
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
|
|
return Err(format!("lucisv could not re-read a file it edited for {what}."));
|
|
};
|
|
let edits = plan.edits.iter().find(|(j, _)| j == i).map(|(_, e)| e.as_slice());
|
|
let edited = crate::apply(text, edits.unwrap_or(&[]));
|
|
let actual = shape(&edited, module);
|
|
if &actual != expected {
|
|
return Err(format!(
|
|
"{what} would not leave {} with the signature lucisv intended; no edits were made.",
|
|
display(path)
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// finding things
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The module a refactoring acts on: which in-scope file declares it, and
|
|
/// under what name.
|
|
struct ModuleSite {
|
|
file: usize,
|
|
name: String,
|
|
}
|
|
|
|
fn locate_module(scope: &mut Scope, module: ModuleRef<'_>) -> Result<ModuleSite, String> {
|
|
let name = match module {
|
|
ModuleRef::Name(name) => name.to_string(),
|
|
ModuleRef::At { file, offset } => {
|
|
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
|
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut found = None;
|
|
module_at(&tree.items, offset, &mut found);
|
|
match found {
|
|
Some(name) => name,
|
|
None => return Err("there is no module declaration at this position.".to_string()),
|
|
}
|
|
}
|
|
};
|
|
let defs: Vec<_> = scope
|
|
.index()
|
|
.units(&name)
|
|
.iter()
|
|
.filter(|def| def.kind.is_instantiable())
|
|
.cloned()
|
|
.collect();
|
|
let [def] = defs.as_slice() else {
|
|
return Err(match defs.len() {
|
|
0 => format!("lucisv indexes no module named `{name}`."),
|
|
_ => format!(
|
|
"`{name}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
|
),
|
|
});
|
|
};
|
|
let Some(file) = scope.index().path(def.file).and_then(|p| scope.index_of(p)) else {
|
|
return Err(format!("`{name}`'s declaring file is not in scope."));
|
|
};
|
|
Ok(ModuleSite { file, name })
|
|
}
|
|
|
|
fn not_in_scope(file: &Path) -> String {
|
|
format!(
|
|
"{} is not one of the files lucisv indexes; nothing outside the project scope can be refactored.",
|
|
display(file)
|
|
)
|
|
}
|
|
|
|
/// The innermost module declaration covering an offset.
|
|
fn module_at(items: &[Item], offset: u32, found: &mut Option<String>) {
|
|
for item in items {
|
|
if !item.span.contains(offset) {
|
|
continue;
|
|
}
|
|
match &item.kind {
|
|
ItemKind::Module(module) => {
|
|
*found = Some(module.name.clone());
|
|
module_at(&module.items, offset, found);
|
|
}
|
|
ItemKind::Package { items, .. } => module_at(items, offset, found),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The module node named `name` in a parsed file, with the span of the item
|
|
/// that holds it.
|
|
pub(crate) fn find_module<'t>(tree: &'t SourceFile, name: &str) -> Option<(&'t Module, TextRange)> {
|
|
fn walk<'t>(items: &'t [Item], name: &str) -> Option<(&'t Module, TextRange)> {
|
|
for item in items {
|
|
match &item.kind {
|
|
ItemKind::Module(module) if module.name == name => {
|
|
return Some((module, item.span))
|
|
}
|
|
ItemKind::Module(module) => {
|
|
if let Some(found) = walk(&module.items, name) {
|
|
return Some(found);
|
|
}
|
|
}
|
|
ItemKind::Package { items, .. } => {
|
|
if let Some(found) = walk(items, name) {
|
|
return Some(found);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
walk(&tree.items, name)
|
|
}
|
|
|
|
/// One declared port: its name and where the name is written in the header.
|
|
struct DeclaredPort {
|
|
name: String,
|
|
/// The whole header element (`input logic [7:0] cfg`, or just `cfg`).
|
|
span: TextRange,
|
|
}
|
|
|
|
fn declared_ports(module: &Module) -> Vec<DeclaredPort> {
|
|
match &module.ports {
|
|
PortList::Ansi(ports) => ports
|
|
.iter()
|
|
.map(|port| DeclaredPort { name: port.name.clone(), span: port.span })
|
|
.collect(),
|
|
PortList::NonAnsi(ports) => ports
|
|
.iter()
|
|
.map(|port| DeclaredPort { name: port.name.clone(), span: port.span })
|
|
.collect(),
|
|
PortList::Empty | PortList::None => Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// Every instantiation written in a file, generate blocks and `bind`
|
|
/// directives included.
|
|
fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t Instantiation>) {
|
|
for item in items {
|
|
match &item.kind {
|
|
ItemKind::Instantiation(inst) => out.push(inst),
|
|
ItemKind::Bind(bind) => out.push(&bind.inst),
|
|
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
|
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
|
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
|
ItemKind::GenIf(gen) => {
|
|
collect_gen_block(&gen.then, out);
|
|
let mut els = gen.els.as_deref();
|
|
while let Some(next) = els {
|
|
match next {
|
|
GenElse::If(_, gen) => {
|
|
collect_gen_block(&gen.then, out);
|
|
els = gen.els.as_deref();
|
|
}
|
|
GenElse::Block(block) => {
|
|
collect_gen_block(block, out);
|
|
els = None;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ItemKind::GenFor(gen) => collect_gen_block(&gen.body, out),
|
|
ItemKind::GenCase(gen) => {
|
|
for arm in &gen.items {
|
|
collect_gen_block(&arm.body, out);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn collect_gen_block<'t>(block: &'t GenBlock, out: &mut Vec<&'t Instantiation>) {
|
|
collect_instantiations(&block.items, out);
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// the free-form input: one port declaration
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// A port declaration the user typed, once lucisv has agreed that it is one.
|
|
struct NewPort {
|
|
name: String,
|
|
/// The declaration as written, trimmed.
|
|
text: String,
|
|
}
|
|
|
|
/// Parse `decl` as exactly one ANSI port declaration, or say why it is not.
|
|
///
|
|
/// The formatter-grade suspicion the milestone asks for: the string is lexed
|
|
/// (no comments, no directives, no macro calls), planted in a throwaway module
|
|
/// header, parsed, and then required to have produced precisely one port with
|
|
/// an explicit direction and nothing else — no second port, no module item a
|
|
/// stray `)` could have opened, no leftovers.
|
|
fn parse_port_decl(decl: &str) -> Result<NewPort, String> {
|
|
let text = decl.trim();
|
|
if text.is_empty() {
|
|
return Err("a port declaration cannot be empty.".to_string());
|
|
}
|
|
let refusal = format!("`{text}` is not a single ANSI port declaration.");
|
|
let Ok(tokens) = tokenize(text) else { return Err(refusal) };
|
|
if tokens.iter().any(|t| !t.leading.is_empty() || t.trailing.is_some()) {
|
|
return Err(
|
|
"a port declaration lucisv writes into a header must carry no comment.".to_string()
|
|
);
|
|
}
|
|
if tokens.iter().any(|t| t.kind == TokenKind::Directive || t.is_macro()) {
|
|
return Err(
|
|
"a port declaration lucisv writes into a header must contain no compiler directive or macro call: lucisv does not preprocess."
|
|
.to_string(),
|
|
);
|
|
}
|
|
let probe = format!("module __lucisv_port_probe ({text});\nendmodule\n");
|
|
let (tree, diagnostics) = parse_source_tolerant(&probe);
|
|
if !diagnostics.is_empty() {
|
|
return Err(refusal);
|
|
}
|
|
let [item] = tree.items.as_slice() else { return Err(refusal) };
|
|
let ItemKind::Module(module) = &item.kind else { return Err(refusal) };
|
|
if !module.items.is_empty() || !module.port_directives.is_empty() {
|
|
return Err(refusal);
|
|
}
|
|
let PortList::Ansi(ports) = &module.ports else { return Err(refusal) };
|
|
let [port] = ports.as_slice() else { return Err(refusal) };
|
|
if port.comma {
|
|
return Err(refusal);
|
|
}
|
|
if port.dir.is_none() {
|
|
return Err(format!(
|
|
"`{text}` does not say a direction; a port lucisv adds must start with `input`, `output` or `inout`."
|
|
));
|
|
}
|
|
if port.name.is_empty() {
|
|
return Err(refusal);
|
|
}
|
|
Ok(NewPort { name: port.name.clone(), text: text.to_string() })
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// add
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn plan_add(scope: &mut Scope, site: &ModuleSite, port: &NewPort) -> Result<Plan, String> {
|
|
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let Some((module, item_span)) = find_module(&tree, &site.name) else {
|
|
return Err(not_indexed(&site.name));
|
|
};
|
|
let existing = declared_ports(module);
|
|
if existing.iter().any(|p| p.name == port.name) {
|
|
return Err(format!("`{}` already has a port named `{}`.", site.name, port.name));
|
|
}
|
|
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
|
let tokens = tokenize(text).map_err(|_| lex_failed(Some(path)))?;
|
|
let file = File { text, path, tokens };
|
|
|
|
let mut plan = Plan::default();
|
|
let header = header_edits(&file, module, item_span, port, &existing, &mut plan.warnings)?;
|
|
let mut names: Vec<String> = existing.iter().map(|p| p.name.clone()).collect();
|
|
names.push(port.name.clone());
|
|
plan.add(site.file, header);
|
|
|
|
let ports_before = existing.len();
|
|
for i in 0..scope.len() {
|
|
let (edits, sites) =
|
|
instantiation_edits(scope, i, site, port, ports_before, &mut plan.warnings)?;
|
|
plan.sites += sites;
|
|
plan.add(i, edits);
|
|
}
|
|
// Every file's expected shape: the module's file gains the port, and every
|
|
// instantiation gains its connection.
|
|
for i in plan.edits.iter().map(|(i, _)| *i).collect::<Vec<_>>() {
|
|
let Some(text) = scope.text(i) else { continue };
|
|
let mut expected = shape(text, &site.name);
|
|
if i == site.file {
|
|
expected.ports = Some(names.clone());
|
|
}
|
|
for (_, conns) in &mut expected.instances {
|
|
// A wildcard site and an empty positional list are both left
|
|
// exactly as they are.
|
|
if conns.is_empty()
|
|
|| conns.iter().any(|c| c == "*")
|
|
|| conns.iter().any(|c| c == &port.name)
|
|
{
|
|
continue;
|
|
}
|
|
match conns.iter().all(String::is_empty) {
|
|
true => conns.push(String::new()),
|
|
false => conns.push(port.name.clone()),
|
|
}
|
|
}
|
|
plan.expected.push((i, expected));
|
|
}
|
|
Ok(plan)
|
|
}
|
|
|
|
fn not_indexed(name: &str) -> String {
|
|
format!("lucisv can no longer find the declaration of `{name}`.")
|
|
}
|
|
|
|
fn lex_failed(path: Option<&Path>) -> String {
|
|
format!("{} does not lex, so lucisv will not edit it.", display(path.unwrap_or(Path::new("?"))))
|
|
}
|
|
|
|
/// The file a module is written in, as the planners read it: its text, its
|
|
/// name for a message, and its tokens.
|
|
struct File<'a> {
|
|
text: &'a str,
|
|
path: &'a Path,
|
|
tokens: Vec<Token>,
|
|
}
|
|
|
|
/// The edits that add the port to the module's own declaration.
|
|
fn header_edits(
|
|
file: &File<'_>,
|
|
module: &Module,
|
|
item_span: TextRange,
|
|
port: &NewPort,
|
|
existing: &[DeclaredPort],
|
|
warnings: &mut Vec<String>,
|
|
) -> Result<Vec<TextEdit>, String> {
|
|
let (text, path, tokens) = (file.text, file.path, file.tokens.as_slice());
|
|
let name_end = module.name_span.end;
|
|
let list = list_directives(module);
|
|
let header = format!("`{}`'s port list", module.name);
|
|
match &module.ports {
|
|
PortList::Ansi(_) if !existing.is_empty() => {
|
|
let open = port_list_open(tokens, name_end);
|
|
let edits = append_to_list(text, open, &element_spans(existing), &port.text);
|
|
guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?;
|
|
Ok(edits)
|
|
}
|
|
PortList::NonAnsi(_) if !existing.is_empty() => {
|
|
let open = port_list_open(tokens, name_end);
|
|
let mut edits = append_to_list(text, open, &element_spans(existing), &port.name);
|
|
guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?;
|
|
let declaration = non_ansi_declaration(text, module, item_span, tokens, &port.text)?;
|
|
guard_conditionals(
|
|
&body_directives(module),
|
|
declaration.range.start,
|
|
&format!("the body of `{}`", module.name),
|
|
text,
|
|
path,
|
|
warnings,
|
|
)?;
|
|
edits.push(declaration);
|
|
Ok(edits)
|
|
}
|
|
// An empty port list has no style to follow, so the port is written
|
|
// the modern way: ANSI, in the header.
|
|
PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => {
|
|
let Some(open) = port_list_open(tokens, name_end) else {
|
|
return Err("lucisv cannot find this module's port list.".to_string());
|
|
};
|
|
let edits = append_to_list(text, Some(open), &[], &port.text);
|
|
guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?;
|
|
Ok(edits)
|
|
}
|
|
PortList::None => {
|
|
if !module.imports.is_empty() {
|
|
return Err(format!(
|
|
"`{}` writes an `import` in its header and has no port list; write `()` first and lucisv will fill it in.",
|
|
module.name
|
|
));
|
|
}
|
|
let Some(semi) = header_semicolon(tokens, name_end) else {
|
|
return Err("lucisv cannot find where this module's header ends.".to_string());
|
|
};
|
|
Ok(vec![insert(semi, format!(" ({})", port.text))])
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Where an append writes its new element: the last of its edits, since the
|
|
/// one before it is only the comma that makes room.
|
|
fn written_at(edits: &[TextEdit]) -> u32 {
|
|
edits.last().map_or(0, |edit| edit.range.start)
|
|
}
|
|
|
|
/// The `(name, span, trailing comment)` triples a list append needs.
|
|
fn element_spans(ports: &[DeclaredPort]) -> Vec<TextRange> {
|
|
ports.iter().map(|p| p.span).collect()
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// conditional compilation
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// One compiler directive written inside a port list or a module body, and
|
|
/// where it is written.
|
|
struct Directive {
|
|
text: String,
|
|
span: TextRange,
|
|
}
|
|
|
|
/// What a directive does to the conditional nesting depth.
|
|
enum Nesting {
|
|
Open,
|
|
Close,
|
|
Neither,
|
|
}
|
|
|
|
fn nesting_of(directive: &str) -> Nesting {
|
|
let word = directive.split_whitespace().next().unwrap_or_default();
|
|
match word {
|
|
"`ifdef" | "`ifndef" => Nesting::Open,
|
|
"`endif" => Nesting::Close,
|
|
// `else` and `elsif` continue the region they are in rather than
|
|
// opening or closing one.
|
|
_ => Nesting::Neither,
|
|
}
|
|
}
|
|
|
|
/// The directives written *between the elements* of a module's port list.
|
|
fn list_directives(module: &Module) -> Vec<Directive> {
|
|
module
|
|
.port_directives
|
|
.iter()
|
|
.map(|directive| Directive { text: directive.raw.text.clone(), span: directive.raw.span })
|
|
.collect()
|
|
}
|
|
|
|
/// The directives written among a module's items — where a non-ANSI port
|
|
/// declaration goes. A macro *item* (`` `ASSERT_INIT(...) ``) is not collected:
|
|
/// it is a call, not a directive, and cannot open a conditional region.
|
|
fn body_directives(module: &Module) -> Vec<Directive> {
|
|
module
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match &item.kind {
|
|
ItemKind::Directive(raw) => Some(Directive { text: raw.text.clone(), span: raw.span }),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Refuse an insertion that would land **inside** a conditional arm, and warn
|
|
/// when the region it joins is conditionally compiled at all.
|
|
///
|
|
/// lucisv does not preprocess, so an `` `ifdef`` arm is ordinary text to it: a
|
|
/// port appended after the last declared port lands wherever that port sits,
|
|
/// conditional arm included, and every later check would wave it through —
|
|
/// the file parses, no name changes meaning, and the re-parsed header really
|
|
/// does declare the port, because lucisv reads through the `` `ifdef``. Only the
|
|
/// *plan* can catch this, so it is caught here: count the arms open at the
|
|
/// insertion point, and refuse when the count is not zero.
|
|
fn guard_conditionals(
|
|
directives: &[Directive],
|
|
at: u32,
|
|
region: &str,
|
|
text: &str,
|
|
path: &Path,
|
|
warnings: &mut Vec<String>,
|
|
) -> Result<(), String> {
|
|
if directives.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let lines = LineIndex::new(text);
|
|
let where_ = |span: TextRange| format!("{}:{}", display(path), lines.line_col(span.start).0);
|
|
let mut depth = 0i32;
|
|
let mut opened: Option<&Directive> = None;
|
|
for directive in directives.iter().filter(|d| d.span.start < at) {
|
|
match nesting_of(&directive.text) {
|
|
Nesting::Open => {
|
|
depth += 1;
|
|
opened = Some(directive);
|
|
}
|
|
Nesting::Close => depth -= 1,
|
|
Nesting::Neither => {}
|
|
}
|
|
}
|
|
if depth > 0 {
|
|
let arm = opened.map_or_else(String::new, |d| {
|
|
format!(" opened by `{}` at {}", first_line(&d.text), where_(d.span))
|
|
});
|
|
return Err(format!(
|
|
"{region} is conditionally compiled, and the new port would land inside the arm{arm}; a port added to one arm of an `ifdef does not exist in the other, so lucisv made no edits — place it by hand."
|
|
));
|
|
}
|
|
if depth != 0 {
|
|
return Err(format!(
|
|
"the compiler directives in {region} do not balance, so lucisv cannot tell whether a new port would be conditionally compiled; it made no edits."
|
|
));
|
|
}
|
|
let first = directives.first();
|
|
let named = first
|
|
.map_or_else(String::new, |d| format!("`{}` at {}", first_line(&d.text), where_(d.span)));
|
|
let rest = directives.len() - 1;
|
|
let more = match rest {
|
|
0 => String::new(),
|
|
1 => ", and 1 more".to_string(),
|
|
n => format!(", and {n} more"),
|
|
};
|
|
warnings.push(format!(
|
|
"{region} carries compiler directives ({named}{more}), so what ports it declares depends on the configuration; lucisv added the port outside every conditional arm."
|
|
));
|
|
Ok(())
|
|
}
|
|
|
|
/// A directive's first line, for a message: the raw text may be a multi-line
|
|
/// `` `define``, and a warning is not the place to print all of it.
|
|
fn first_line(directive: &str) -> &str {
|
|
directive.trim().lines().next().unwrap_or_default().trim_end()
|
|
}
|
|
|
|
/// Where the non-ANSI body declaration of a new port goes.
|
|
fn non_ansi_declaration(
|
|
text: &str,
|
|
module: &Module,
|
|
item_span: TextRange,
|
|
tokens: &[Token],
|
|
decl: &str,
|
|
) -> Result<TextEdit, String> {
|
|
let last_port_decl =
|
|
module.items.iter().rfind(|item| matches!(item.kind, ItemKind::PortDecl(_)));
|
|
if let Some(item) = last_port_decl {
|
|
let after = after_same_line_comments(text, item.span.end);
|
|
let indent = line_indent(text, item.span.start);
|
|
return Ok(insert(after.at, format!("\n{indent}{decl};")));
|
|
}
|
|
if let Some(item) = module.items.first() {
|
|
let start = item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start);
|
|
let indent = line_indent(text, start);
|
|
return Ok(insert(start, format!("{decl};\n{indent}")));
|
|
}
|
|
// A non-ANSI module with a header port list and no items at all is not
|
|
// legal Verilog, but a tolerant parse can still hand one over.
|
|
let Some(semi) = header_semicolon(tokens, module.name_span.end) else {
|
|
return Err("lucisv cannot find where this module's header ends.".to_string());
|
|
};
|
|
let indent = format!("{} ", line_indent(text, item_span.start));
|
|
Ok(insert(semi + 1, format!("\n{indent}{decl};")))
|
|
}
|
|
|
|
/// The edits that give one file's instantiations of the module a connection
|
|
/// for the new port.
|
|
fn instantiation_edits(
|
|
scope: &mut Scope,
|
|
file: usize,
|
|
site: &ModuleSite,
|
|
port: &NewPort,
|
|
ports_before: usize,
|
|
warnings: &mut Vec<String>,
|
|
) -> Result<(Vec<TextEdit>, usize), String> {
|
|
let (Some(text), Some(path)) = (scope.text(file), scope.path(file)) else {
|
|
return Ok((Vec::new(), 0));
|
|
};
|
|
if !text.contains(&site.name) {
|
|
return Ok((Vec::new(), 0));
|
|
}
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut instantiations = Vec::new();
|
|
collect_instantiations(&tree.items, &mut instantiations);
|
|
let lines = LineIndex::new(text);
|
|
|
|
// Every place a connection could go, collected first so the semantic
|
|
// lookups below can borrow the scope on their own.
|
|
let mut named: Vec<(&Instance, Vec<TextRange>, Option<u32>)> = Vec::new();
|
|
let mut ordered: Vec<(&Instance, Vec<TextRange>)> = Vec::new();
|
|
let mut wildcards: Vec<&Instance> = Vec::new();
|
|
for instantiation in instantiations.iter().filter(|i| i.module == site.name) {
|
|
for instance in &instantiation.instances {
|
|
match &instance.conns {
|
|
Connections::Named(conns) if conns.iter().any(|c| c.name == "*") => {
|
|
wildcards.push(instance)
|
|
}
|
|
Connections::Named(conns) => {
|
|
if conns.iter().any(|c| c.name == port.name) {
|
|
continue;
|
|
}
|
|
named.push((
|
|
instance,
|
|
conns.iter().map(|c| c.span).collect(),
|
|
conn_list_open(text, instance, conns.first().map(|c| c.span)),
|
|
));
|
|
}
|
|
// An empty list connects nothing, so a new port changes
|
|
// nothing there: it stays unconnected either way.
|
|
Connections::Ordered(conns) if conns.is_empty() => {
|
|
warnings.push(format!(
|
|
"`{}` at {}:{} writes an empty connection list, so `{}` is left unconnected there.",
|
|
instance.name,
|
|
display(path),
|
|
lines.line_col(instance.name_span.start).0,
|
|
port.name
|
|
));
|
|
}
|
|
Connections::Ordered(conns) => {
|
|
if conns.len() != ports_before {
|
|
return Err(format!(
|
|
"`{}` in {} connects {} of `{}`'s {ports_before} port(s) by position, so lucisv cannot tell where a new one goes; give it named connections first.",
|
|
instance.name,
|
|
display(path),
|
|
conns.len(),
|
|
site.name
|
|
));
|
|
}
|
|
ordered.push((instance, conns.iter().map(|c| c.span).collect()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for instance in &wildcards {
|
|
let visible = name_visible(scope, file, instance.name_span.start, &port.name);
|
|
if !visible {
|
|
warnings.push(format!(
|
|
"`{}` at {}:{} connects with `.*` and {} has no signal named `{}`, so the new port will not bind; connect it by hand.",
|
|
instance.name,
|
|
display(path),
|
|
lines.line_col(instance.name_span.start).0,
|
|
display(path),
|
|
port.name
|
|
));
|
|
}
|
|
}
|
|
|
|
let mut edits = Vec::new();
|
|
let mut todo: Vec<String> = Vec::new();
|
|
let mut empty: Vec<String> = Vec::new();
|
|
let sites = named.len() + ordered.len();
|
|
for (instance, spans, open) in named {
|
|
let visible = name_visible(scope, file, instance.name_span.start, &port.name);
|
|
let expr = if visible {
|
|
port.name.clone()
|
|
} else {
|
|
todo.push(at_site(&instance.name, path, &lines, instance.name_span.start));
|
|
"/* TODO: connect */".to_string()
|
|
};
|
|
let element = format!(".{}({expr})", port.name);
|
|
let open = match open {
|
|
Some(open) => open,
|
|
None => return Err(missing_parens(&instance.name, path)),
|
|
};
|
|
edits.extend(append_to_list(text, Some(open), &spans, &element));
|
|
}
|
|
for (instance, spans) in ordered {
|
|
let visible = name_visible(scope, file, instance.name_span.start, &port.name);
|
|
// A positional connection has nowhere to put a `/* TODO */` — a
|
|
// comment between two commas is an *empty* position, not a
|
|
// placeholder — so an unconnectable one is written as the empty
|
|
// position it is, and said out loud.
|
|
let expr = if visible {
|
|
port.name.clone()
|
|
} else {
|
|
empty.push(at_site(&instance.name, path, &lines, instance.name_span.start));
|
|
String::new()
|
|
};
|
|
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
|
|
return Err(missing_parens(&instance.name, path));
|
|
};
|
|
edits.extend(append_to_list(text, Some(open), &spans, &expr));
|
|
}
|
|
if !todo.is_empty() {
|
|
warnings.push(format!(
|
|
"no signal named `{}` is in scope at {}, so its connection was left as `/* TODO: connect */`.",
|
|
port.name,
|
|
todo.join(", ")
|
|
));
|
|
}
|
|
if !empty.is_empty() {
|
|
warnings.push(format!(
|
|
"no signal named `{}` is in scope at {}, so the new positional connection was left empty.",
|
|
port.name,
|
|
empty.join(", ")
|
|
));
|
|
}
|
|
Ok((edits, sites))
|
|
}
|
|
|
|
/// How one instantiation site is named in a warning: `` `u_sub` (top.sv:12) ``.
|
|
fn at_site(instance: &str, path: &Path, lines: &LineIndex, offset: u32) -> String {
|
|
format!("`{instance}` ({}:{})", display(path), lines.line_col(offset).0)
|
|
}
|
|
|
|
fn missing_parens(instance: &str, path: &Path) -> String {
|
|
format!(
|
|
"lucisv cannot find the connection list of `{instance}` in {}; no edits were made.",
|
|
display(path)
|
|
)
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// remove
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The module and port name a removal request points at. The cursor may sit on
|
|
/// the header port or, for a non-ANSI module, on its body declaration.
|
|
fn locate_port(
|
|
scope: &mut Scope,
|
|
file: &Path,
|
|
offset: u32,
|
|
) -> Result<(ModuleSite, String), String> {
|
|
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
|
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut module_name = None;
|
|
module_at(&tree.items, offset, &mut module_name);
|
|
let Some(module_name) = module_name else {
|
|
return Err(NOT_A_PORT.to_string());
|
|
};
|
|
let Some((module, _)) = find_module(&tree, &module_name) else {
|
|
return Err(NOT_A_PORT.to_string());
|
|
};
|
|
let ports = declared_ports(module);
|
|
let mut name = ports.iter().find(|p| p.span.contains(offset)).map(|p| p.name.clone());
|
|
if name.is_none() {
|
|
// The cursor may be on the non-ANSI body declaration instead.
|
|
for item in &module.items {
|
|
let ItemKind::PortDecl(decl) = &item.kind else { continue };
|
|
for declarator in &decl.declarators {
|
|
if declarator.span.contains(offset) || declarator.name_span.contains(offset) {
|
|
name = Some(declarator.name.clone());
|
|
}
|
|
}
|
|
}
|
|
// ...and it must still be a port of this module.
|
|
if let Some(found) = &name {
|
|
if !ports.iter().any(|p| &p.name == found) {
|
|
return Err(NOT_A_PORT.to_string());
|
|
}
|
|
}
|
|
}
|
|
let Some(name) = name else { return Err(NOT_A_PORT.to_string()) };
|
|
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
|
|
if site.file != i {
|
|
return Err(format!(
|
|
"`{module_name}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
|
));
|
|
}
|
|
Ok((site, name))
|
|
}
|
|
|
|
const NOT_A_PORT: &str = "there is no module port at this position.";
|
|
|
|
fn plan_remove(scope: &mut Scope, site: &ModuleSite, port: &str) -> Result<Plan, String> {
|
|
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
|
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let Some((module, _)) = find_module(&tree, &site.name) else {
|
|
return Err(not_indexed(&site.name));
|
|
};
|
|
let ports = declared_ports(module);
|
|
let Some(index) = ports.iter().position(|p| p.name == port) else {
|
|
return Err(format!("`{}` has no port named `{port}`.", site.name));
|
|
};
|
|
|
|
let mut header: Vec<TextEdit> = remove_element(text, &element_spans(&ports), index)?;
|
|
if matches!(module.ports, PortList::NonAnsi(_)) {
|
|
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
|
|
}
|
|
// A port still used by the module's own body is a refusal, not a warning:
|
|
// deleting it would leave the body naming something that no longer exists.
|
|
let used = body_uses(scope, site.file, module, port, &header);
|
|
if !used.is_empty() {
|
|
return Err(format!(
|
|
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
|
|
site.name,
|
|
display(path),
|
|
used.join(", ")
|
|
));
|
|
}
|
|
|
|
let mut plan = Plan::default();
|
|
plan.add(site.file, header);
|
|
for i in 0..scope.len() {
|
|
let (edits, sites) = disconnection_edits(scope, i, site, port, &mut plan.warnings)?;
|
|
plan.sites += sites;
|
|
plan.add(i, edits);
|
|
}
|
|
// What the preprocessor owns, lucisv cannot edit — and after a removal, what
|
|
// it owns may name a port that no longer exists.
|
|
let mut watched: Vec<usize> = plan.edits.iter().map(|(i, _)| *i).collect();
|
|
if !watched.contains(&site.file) {
|
|
watched.push(site.file);
|
|
}
|
|
watched.sort_unstable();
|
|
for &i in &watched {
|
|
plan.warnings.extend(preprocessor_warnings(scope, i, port));
|
|
}
|
|
|
|
let mut names: Vec<String> = ports.iter().map(|p| p.name.clone()).collect();
|
|
names.remove(index);
|
|
for i in plan.edits.iter().map(|(i, _)| *i).collect::<Vec<_>>() {
|
|
let Some(text) = scope.text(i) else { continue };
|
|
let mut expected = shape(text, &site.name);
|
|
if i == site.file {
|
|
expected.ports = Some(names.clone());
|
|
}
|
|
for (_, conns) in &mut expected.instances {
|
|
conns.retain(|name| name != port);
|
|
}
|
|
plan.expected.push((i, expected));
|
|
}
|
|
Ok(plan)
|
|
}
|
|
|
|
/// Every place in one file where the removed port's name lives in text the
|
|
/// preprocessor owns: a macro invocation's arguments, or a `` `define`` body.
|
|
///
|
|
/// lucisv does not expand macros — a macro invocation is one opaque token, so
|
|
/// `` `BUMP(rst) `` records no reference for `body_uses` to find and no span
|
|
/// for an edit to land on. Silence would be the worst answer: the file still
|
|
/// parses and still *looks* right, and only a real preprocessor discovers that
|
|
/// the expansion names a port that no longer exists. The same scan M2 added to
|
|
/// rename after QA found the same hole there (`Scope::macro_argument_sites`,
|
|
/// `Scope::define_sites`) answers it here, with news of its own.
|
|
fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String> {
|
|
let where_ = display(scope.path(file).unwrap_or(Path::new("?")));
|
|
let mut out = Vec::new();
|
|
for site in scope.macro_argument_sites(file, port) {
|
|
out.push(format!(
|
|
"`{port}` appears in the arguments of the macro invocation `{}` at {where_}:{}; a macro invocation is one opaque token to lucisv, so nothing was removed there and that expansion now names a port `{port}`'s module no longer has.",
|
|
site.macro_name, site.line
|
|
));
|
|
}
|
|
for site in scope.define_sites(file, port) {
|
|
// A macro *named* like the port is not news for a removal; a macro
|
|
// whose body spells it is.
|
|
if site.defines_the_name.is_some() {
|
|
continue;
|
|
}
|
|
out.push(format!(
|
|
"`{port}` appears in the body of macro `{}` at {where_}:{}; lucisv does not preprocess, so that body still names the removed port.",
|
|
site.macro_name, site.line
|
|
));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The lines of the module's body that still name the port, ignoring the
|
|
/// declarations the removal is itself deleting.
|
|
fn body_uses(
|
|
scope: &mut Scope,
|
|
file: usize,
|
|
module: &Module,
|
|
port: &str,
|
|
removed: &[TextEdit],
|
|
) -> Vec<String> {
|
|
let Some(text) = scope.text(file) else { return Vec::new() };
|
|
let lines = LineIndex::new(text);
|
|
let Some(analysis) = scope.analysis(file) else { return Vec::new() };
|
|
let semantics = &analysis.semantics;
|
|
let Some(symbol) = semantics.symbols().iter().position(|s| {
|
|
s.name == port
|
|
&& s.kind == SymbolKind::Port
|
|
&& module_span(module).contains(s.name_span.start)
|
|
}) else {
|
|
return Vec::new();
|
|
};
|
|
let id = vlog_semantic::SymbolId(symbol as u32);
|
|
let mut out: Vec<String> = Vec::new();
|
|
for reference in semantics.references_of(id) {
|
|
let span = reference.name_span;
|
|
if removed.iter().any(|e| e.range.start <= span.start && span.end <= e.range.end) {
|
|
continue;
|
|
}
|
|
let line = lines.line_col(span.start).0.to_string();
|
|
if !out.contains(&line) {
|
|
out.push(line);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The bytes a module covers, taken from its name and its last item — the
|
|
/// `Module` node carries no span of its own.
|
|
fn module_span(module: &Module) -> TextRange {
|
|
let end = module.items.last().map_or(module.name_span.end, |item| item.span.end);
|
|
TextRange::new(module.name_span.start, end.max(module.name_span.end))
|
|
}
|
|
|
|
/// Delete the non-ANSI body declaration of a port: the whole item when it
|
|
/// declares only this port, otherwise just its declarator.
|
|
fn non_ansi_declaration_removal(
|
|
text: &str,
|
|
module: &Module,
|
|
port: &str,
|
|
) -> Result<Vec<TextEdit>, String> {
|
|
for item in &module.items {
|
|
let ItemKind::PortDecl(decl) = &item.kind else { continue };
|
|
let Some(index) = decl.declarators.iter().position(|d| d.name == port) else { continue };
|
|
if decl.declarators.len() == 1 {
|
|
return Ok(vec![TextEdit {
|
|
range: whole_line(text, item.span),
|
|
new_text: String::new(),
|
|
}]);
|
|
}
|
|
let spans: Vec<TextRange> = decl.declarators.iter().map(|d| d.span).collect();
|
|
return remove_element(text, &spans, index);
|
|
}
|
|
Err(format!("`{port}` has no declaration in the body of `{}`.", module.name))
|
|
}
|
|
|
|
/// The edits that take the port's connection out of one file's instantiations.
|
|
fn disconnection_edits(
|
|
scope: &mut Scope,
|
|
file: usize,
|
|
site: &ModuleSite,
|
|
port: &str,
|
|
warnings: &mut Vec<String>,
|
|
) -> Result<(Vec<TextEdit>, usize), String> {
|
|
let (Some(text), Some(path)) = (scope.text(file), scope.path(file)) else {
|
|
return Ok((Vec::new(), 0));
|
|
};
|
|
if !text.contains(&site.name) {
|
|
return Ok((Vec::new(), 0));
|
|
}
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut instantiations = Vec::new();
|
|
collect_instantiations(&tree.items, &mut instantiations);
|
|
let lines = LineIndex::new(text);
|
|
|
|
let mut edits = Vec::new();
|
|
let mut sites = 0usize;
|
|
for instantiation in instantiations.iter().filter(|i| i.module == site.name) {
|
|
for instance in &instantiation.instances {
|
|
match &instance.conns {
|
|
Connections::Ordered(conns) if conns.is_empty() => {}
|
|
Connections::Ordered(_) => {
|
|
return Err(format!(
|
|
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
|
|
instance.name,
|
|
display(path),
|
|
site.name
|
|
))
|
|
}
|
|
Connections::Named(conns) => {
|
|
// `.*` binds the port implicitly, so there is nothing to
|
|
// delete — and the signal it was binding may now have no
|
|
// reader at all, which is worth saying.
|
|
if conns.iter().any(|c| c.name == "*") && conns.iter().all(|c| c.name != port) {
|
|
warnings.push(format!(
|
|
"`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.",
|
|
instance.name,
|
|
display(path),
|
|
lines.line_col(instance.name_span.start).0
|
|
));
|
|
continue;
|
|
}
|
|
let Some(index) = conns.iter().position(|c| c.name == port) else { continue };
|
|
// The connected expression goes with the connection. A
|
|
// plain `.p(p)` loses nothing; anything else is said out
|
|
// loud, because it is the user's code being deleted.
|
|
if let Some(expr) = conns.get(index) {
|
|
let written = text.get(expr.span.as_range()).unwrap_or("");
|
|
let trivial = written == format!(".{port}({port})")
|
|
|| written == format!(".{port}()")
|
|
|| written == format!(".{port}");
|
|
if !trivial {
|
|
warnings.push(format!(
|
|
"`{written}` at {}:{} was deleted with the port.",
|
|
display(path),
|
|
lines.line_col(expr.span.start).0
|
|
));
|
|
}
|
|
}
|
|
let spans: Vec<TextRange> = conns.iter().map(|c| c.span).collect();
|
|
sites += 1;
|
|
edits.append(&mut remove_element(text, &spans, index)?);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Ok((edits, sites))
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// propagate
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn plan_propagate(
|
|
scope: &mut Scope,
|
|
file: &Path,
|
|
offset: u32,
|
|
) -> Result<(ModuleSite, Plan), String> {
|
|
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
|
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
|
let (tree, _) = parse_source_tolerant(text);
|
|
let mut instantiations = Vec::new();
|
|
collect_instantiations(&tree.items, &mut instantiations);
|
|
|
|
// The instance under the cursor, or the only one of the instantiation the
|
|
// cursor's module name belongs to.
|
|
let mut found: Option<(&Instantiation, &Instance)> = None;
|
|
for instantiation in &instantiations {
|
|
for instance in &instantiation.instances {
|
|
if instance.span.contains(offset) {
|
|
found = Some((instantiation, instance));
|
|
}
|
|
}
|
|
if found.is_none() && instantiation.module_span.contains(offset) {
|
|
let [only] = instantiation.instances.as_slice() else {
|
|
return Err(format!(
|
|
"this statement declares {} instances of `{}`; put the cursor on the one to connect.",
|
|
instantiation.instances.len(),
|
|
instantiation.module
|
|
));
|
|
};
|
|
found = Some((instantiation, only));
|
|
}
|
|
}
|
|
let Some((instantiation, instance)) = found else {
|
|
return Err("there is no module instantiation at this position.".to_string());
|
|
};
|
|
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
|
|
|
let conns = match &instance.conns {
|
|
Connections::Ordered(_) => {
|
|
return Err(format!(
|
|
"`{}` connects `{}`'s ports by position; lucisv propagates named connections only.",
|
|
instance.name, instantiation.module
|
|
))
|
|
}
|
|
Connections::Named(conns) => conns,
|
|
};
|
|
if conns.iter().any(|c| c.name == "*") {
|
|
return Err(format!(
|
|
"`{}` connects with `.*`, which already binds every same-named port.",
|
|
instance.name
|
|
));
|
|
}
|
|
|
|
let Some(module_text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
|
let (module_tree, _) = parse_source_tolerant(module_text);
|
|
let Some((module, _)) = find_module(&module_tree, &site.name) else {
|
|
return Err(not_indexed(&site.name));
|
|
};
|
|
let declared = declared_ports(module);
|
|
let missing: Vec<String> = declared
|
|
.iter()
|
|
.map(|p| p.name.clone())
|
|
.filter(|name| conns.iter().all(|c| &c.name != name))
|
|
.collect();
|
|
if missing.is_empty() {
|
|
return Err(format!(
|
|
"`{}` already connects every port `{}` declares.",
|
|
instance.name, site.name
|
|
));
|
|
}
|
|
|
|
let spans: Vec<TextRange> = conns.iter().map(|c| c.span).collect();
|
|
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
|
|
return Err(missing_parens(&instance.name, file));
|
|
};
|
|
let lines = LineIndex::new(text);
|
|
let at = instance.name_span.start;
|
|
let instance_name = instance.name.clone();
|
|
|
|
let mut plan = Plan::default();
|
|
let mut edits = Vec::new();
|
|
let mut spans = spans;
|
|
let mut todo: Vec<String> = Vec::new();
|
|
let mut connected: Vec<String> = conns.iter().map(|c| c.name.clone()).collect();
|
|
for name in &missing {
|
|
let expr = if name_visible(scope, i, at, name) {
|
|
name.clone()
|
|
} else {
|
|
todo.push(name.clone());
|
|
"/* TODO: connect */".to_string()
|
|
};
|
|
let element = format!(".{name}({expr})");
|
|
let mut written = append_to_list(text, Some(open), &spans, &element);
|
|
// Each connection is appended after the previous one, so the next
|
|
// append sees it as the list's last element.
|
|
let start = written.last().map_or(open, |edit| edit.range.start);
|
|
spans.push(TextRange::new(start, start));
|
|
edits.append(&mut written);
|
|
connected.push(name.clone());
|
|
}
|
|
if !todo.is_empty() {
|
|
plan.warnings.push(format!(
|
|
"no signal named {} is in scope at {}:{}, so those connections were left as `/* TODO: connect */`.",
|
|
todo.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
|
|
display(file),
|
|
lines.line_col(at).0
|
|
));
|
|
}
|
|
plan.sites = 1;
|
|
plan.add(i, edits);
|
|
let mut expected = shape(text, &site.name);
|
|
for (name, conns) in &mut expected.instances {
|
|
if name == &instance_name {
|
|
*conns = connected.clone();
|
|
}
|
|
}
|
|
plan.expected.push((i, expected));
|
|
Ok((site, plan))
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// editing a comma-separated list
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn insert(at: u32, text: String) -> TextEdit {
|
|
TextEdit { range: TextRange::empty(at), new_text: text }
|
|
}
|
|
|
|
/// Append one element to a parenthesized comma-separated list.
|
|
///
|
|
/// The layout is copied from the list itself: an element per line keeps an
|
|
/// element per line, at the last element's own indentation; an inline list
|
|
/// stays inline. When the last element carries a line comment the comma is
|
|
/// written *before* the comment and the new element after it, because a `,`
|
|
/// written after `//` is a `,` inside a comment.
|
|
fn append_to_list(
|
|
text: &str,
|
|
open: Option<u32>,
|
|
elements: &[TextRange],
|
|
element: &str,
|
|
) -> Vec<TextEdit> {
|
|
let Some(last) = elements.last() else {
|
|
// An empty list: the new element is the only one, written just before
|
|
// the `)`.
|
|
return match open {
|
|
Some(open) => vec![insert(close_paren(text, open).unwrap_or(open + 1), element.into())],
|
|
None => Vec::new(),
|
|
};
|
|
};
|
|
let previous = elements.len().checked_sub(2).and_then(|n| elements.get(n)).map(|e| e.end);
|
|
let gap_from = previous.or(open);
|
|
let one_per_line = gap_from
|
|
.and_then(|from| text.get(from as usize..last.start as usize))
|
|
.is_some_and(|gap| gap.contains('\n'));
|
|
let indent = line_indent(text, last.start);
|
|
let separator = match one_per_line {
|
|
true => format!(",\n{indent}"),
|
|
false => ", ".to_string(),
|
|
};
|
|
|
|
let after = after_same_line_comments(text, last.end);
|
|
match after.line_comment {
|
|
// `input a // why`: the comma goes before the comment, the element on
|
|
// the next line — which is where the source was going to put it anyway.
|
|
true => vec![
|
|
insert(last.end, ",".to_string()),
|
|
insert(after.at, format!("\n{indent}{element}")),
|
|
],
|
|
false => vec![insert(after.at, format!("{separator}{element}"))],
|
|
}
|
|
}
|
|
|
|
/// Delete element `index` from a comma-separated list, taking the comma that
|
|
/// keeps the list well-formed with it: the one after the element, or — for the
|
|
/// last element — the one before it.
|
|
///
|
|
/// The last element's comma is a **deletion of its own** rather than part of
|
|
/// one range, because the source may have written a comment between the two
|
|
/// (`.a(x), // about a` ⏎ `.b(y)`) and one range would swallow it.
|
|
fn remove_element(
|
|
text: &str,
|
|
elements: &[TextRange],
|
|
index: usize,
|
|
) -> Result<Vec<TextEdit>, String> {
|
|
let Some(element) = elements.get(index) else {
|
|
return Err("lucisv lost track of the element it was removing.".to_string());
|
|
};
|
|
let delete = |range: TextRange| TextEdit { range, new_text: String::new() };
|
|
if elements.len() == 1 {
|
|
return Ok(vec![delete(whole_line(text, *element))]);
|
|
}
|
|
if index + 1 < elements.len() {
|
|
return Ok(match comma_after(text, element.end) {
|
|
// The blanks after the comma go too, so `a, b, c` minus `b` is
|
|
// `a, c` and not `a, c`.
|
|
Some(comma) => vec![delete(whole_line(
|
|
text,
|
|
TextRange::new(element.start, blanks_after(text, comma + 1)),
|
|
))],
|
|
None => vec![delete(whole_line(text, *element))],
|
|
});
|
|
}
|
|
// The last element: its comma is the one after the element before it,
|
|
// which is where a forward scan finds it without guessing.
|
|
let previous = index.checked_sub(1).and_then(|n| elements.get(n));
|
|
let comma = previous.and_then(|previous| comma_after(text, previous.end));
|
|
let mut edits = Vec::new();
|
|
if let Some(comma) = comma {
|
|
// The blanks after the comma go with it, unless a comment follows:
|
|
// `.a(x), // about a` must not become `.a(x)// about a`.
|
|
let next = blanks_after(text, comma + 1);
|
|
let comment = text
|
|
.get(next as usize..)
|
|
.is_some_and(|rest| rest.starts_with("//") || rest.starts_with("/*"));
|
|
edits.push(delete(TextRange::new(comma, if comment { comma + 1 } else { next })));
|
|
}
|
|
edits.push(delete(whole_line(text, *element)));
|
|
Ok(edits)
|
|
}
|
|
|
|
/// Widen a deletion to the whole line when nothing else is written on it, so
|
|
/// removing a one-per-line element does not leave a blank line behind. A line
|
|
/// that holds anything else — code or a comment — is left exactly as it is.
|
|
fn whole_line(text: &str, range: TextRange) -> TextRange {
|
|
let (start, end) = (range.start as usize, range.end as usize);
|
|
let line_start =
|
|
text.get(..start).map_or(0, |before| before.rfind('\n').map_or(0, |newline| newline + 1));
|
|
let Some(head) = text.get(line_start..start) else { return range };
|
|
if !head.chars().all(|c| c == ' ' || c == '\t') {
|
|
return range;
|
|
}
|
|
let Some(tail) = text.get(end..) else { return range };
|
|
let line_end = tail.find('\n').map_or(tail.len(), |n| n + 1);
|
|
let Some(rest) = tail.get(..line_end) else { return range };
|
|
if !rest.chars().all(|c| c == ' ' || c == '\t' || c == '\n' || c == '\r') {
|
|
return range;
|
|
}
|
|
TextRange::new(line_start as u32, (end + line_end) as u32)
|
|
}
|
|
|
|
/// Where an append must write, once the comments the source put after the last
|
|
/// element are accounted for.
|
|
struct AfterElement {
|
|
at: u32,
|
|
/// True when the element is followed by a `//` comment, which nothing may
|
|
/// be written into.
|
|
line_comment: bool,
|
|
}
|
|
|
|
fn after_same_line_comments(text: &str, end: u32) -> AfterElement {
|
|
let mut at = end as usize;
|
|
loop {
|
|
let Some(rest) = text.get(at..) else {
|
|
return AfterElement { at: at as u32, line_comment: false };
|
|
};
|
|
let skipped = rest.len() - rest.trim_start_matches([' ', '\t']).len();
|
|
let rest = &rest[skipped..];
|
|
if rest.starts_with("//") {
|
|
let line = rest.find('\n').unwrap_or(rest.len());
|
|
return AfterElement { at: (at + skipped + line) as u32, line_comment: true };
|
|
}
|
|
if rest.starts_with("/*") {
|
|
let Some(close) = rest.find("*/") else {
|
|
return AfterElement { at: at as u32, line_comment: false };
|
|
};
|
|
if rest[..close].contains('\n') {
|
|
return AfterElement { at: at as u32, line_comment: false };
|
|
}
|
|
at += skipped + close + 2;
|
|
continue;
|
|
}
|
|
return AfterElement { at: at as u32, line_comment: false };
|
|
}
|
|
}
|
|
|
|
/// The whitespace the line holding `offset` starts with, or nothing when
|
|
/// `offset` is not the first thing written on its line.
|
|
fn line_indent(text: &str, offset: u32) -> String {
|
|
let offset = offset as usize;
|
|
let line_start = text.get(..offset).map_or(0, |before| before.rfind('\n').map_or(0, |n| n + 1));
|
|
let Some(head) = text.get(line_start..offset) else { return String::new() };
|
|
match head.chars().all(|c| c == ' ' || c == '\t') {
|
|
true => head.to_string(),
|
|
false => String::new(),
|
|
}
|
|
}
|
|
|
|
/// The `,` written after `end`, skipping whitespace and comments.
|
|
fn comma_after(text: &str, end: u32) -> Option<u32> {
|
|
let mut at = end as usize;
|
|
loop {
|
|
let rest = text.get(at..)?;
|
|
let skipped = rest.len() - rest.trim_start().len();
|
|
at += skipped;
|
|
let rest = text.get(at..)?;
|
|
if rest.starts_with("//") {
|
|
at += rest.find('\n').unwrap_or(rest.len());
|
|
continue;
|
|
}
|
|
if rest.starts_with("/*") {
|
|
at += rest.find("*/")? + 2;
|
|
continue;
|
|
}
|
|
return rest.starts_with(',').then_some(at as u32);
|
|
}
|
|
}
|
|
|
|
/// Where the run of spaces and tabs starting at `from` ends. Newlines are not
|
|
/// blanks here: a deletion that crossed one would join two lines.
|
|
fn blanks_after(text: &str, from: u32) -> u32 {
|
|
let Some(rest) = text.get(from as usize..) else { return from };
|
|
from + (rest.len() - rest.trim_start_matches([' ', '\t']).len()) as u32
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// finding parentheses
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The `(` of a module's port list, given where its name ends. The parameter
|
|
/// port list `#( ... )` is skipped.
|
|
fn port_list_open(tokens: &[Token], name_end: u32) -> Option<u32> {
|
|
port_list_parens(tokens, name_end).map(|(open, _)| open)
|
|
}
|
|
|
|
/// The `(` and `)` of a module's port list.
|
|
fn port_list_parens(tokens: &[Token], name_end: u32) -> Option<(u32, u32)> {
|
|
let mut i = tokens.iter().position(|t| t.span.start >= name_end)?;
|
|
while i < tokens.len() {
|
|
let token = &tokens[i];
|
|
if token.is_sym("#") {
|
|
i = skip_group(tokens, i + 1)?;
|
|
continue;
|
|
}
|
|
if token.is_sym("(") {
|
|
let close = skip_group(tokens, i)?;
|
|
let close_token = tokens.get(close.checked_sub(1)?)?;
|
|
return Some((token.span.start, close_token.span.start));
|
|
}
|
|
if token.is_sym(";") || token.kind == TokenKind::Eof {
|
|
return None;
|
|
}
|
|
i += 1;
|
|
}
|
|
None
|
|
}
|
|
|
|
/// The `;` that ends a module header that wrote no port list.
|
|
fn header_semicolon(tokens: &[Token], name_end: u32) -> Option<u32> {
|
|
let mut i = tokens.iter().position(|t| t.span.start >= name_end)?;
|
|
while i < tokens.len() {
|
|
let token = &tokens[i];
|
|
if token.is_sym("#") {
|
|
i = skip_group(tokens, i + 1)?;
|
|
continue;
|
|
}
|
|
if token.is_sym(";") {
|
|
return Some(token.span.start);
|
|
}
|
|
if token.kind == TokenKind::Eof {
|
|
return None;
|
|
}
|
|
i += 1;
|
|
}
|
|
None
|
|
}
|
|
|
|
/// The index just past the `( ... )` group starting at `open`.
|
|
fn skip_group(tokens: &[Token], open: usize) -> Option<usize> {
|
|
if !tokens.get(open)?.is_sym("(") {
|
|
return None;
|
|
}
|
|
let mut depth = 0usize;
|
|
for (i, token) in tokens.iter().enumerate().skip(open) {
|
|
if token.is_sym("(") {
|
|
depth += 1;
|
|
} else if token.is_sym(")") {
|
|
depth -= 1;
|
|
if depth == 0 {
|
|
return Some(i + 1);
|
|
}
|
|
} else if token.kind == TokenKind::Eof {
|
|
return None;
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// The `(` opening an instance's connection list.
|
|
fn conn_list_open(text: &str, instance: &Instance, first: Option<TextRange>) -> Option<u32> {
|
|
match first {
|
|
// The list has elements: its `(` is the last one before the first of
|
|
// them that is not inside the instance's dimensions.
|
|
Some(first) => text.get(..first.start as usize)?.rfind('(').map(|at| at as u32),
|
|
// An empty list: the instance's span ends at its own `)`.
|
|
None => {
|
|
let end = instance.span.end as usize;
|
|
let close = text.get(..end)?.rfind(')')? as u32;
|
|
text.get(..close as usize)?.rfind('(').map(|at| at as u32)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The `)` matching an `(` at `open`, found over the text — used only where a
|
|
/// list is empty, so nothing but whitespace and comments sits between them.
|
|
fn close_paren(text: &str, open: u32) -> Option<u32> {
|
|
let rest = text.get(open as usize + 1..)?;
|
|
rest.find(')').map(|at| open + 1 + at as u32)
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// what is in scope where
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Whether a signal called `name` is visible at `offset` in a file — the test
|
|
/// that decides between `.p(p)` and `.p(/* TODO: connect */)`.
|
|
fn name_visible(scope: &mut Scope, file: usize, offset: u32, name: &str) -> bool {
|
|
let Some(analysis) = scope.analysis(file) else { return false };
|
|
visible_in(&analysis.semantics, offset, name)
|
|
}
|
|
|
|
pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool {
|
|
let scopes = semantics.scopes();
|
|
// The innermost scope covering the offset: the smallest span that holds it.
|
|
let mut best: Option<usize> = None;
|
|
for (i, scope) in scopes.iter().enumerate() {
|
|
if !scope.span.contains(offset) {
|
|
continue;
|
|
}
|
|
let better = best.is_none_or(|b| {
|
|
scopes.get(b).is_some_and(|current| scope.span.len() <= current.span.len())
|
|
});
|
|
if better {
|
|
best = Some(i);
|
|
}
|
|
}
|
|
let mut at = best;
|
|
while let Some(i) = at {
|
|
let Some(current) = scopes.get(i) else { return false };
|
|
if let Some(symbol) = current.lookup_local(name) {
|
|
return semantics.symbol(symbol).is_some_and(|s| {
|
|
matches!(
|
|
s.kind,
|
|
SymbolKind::Net
|
|
| SymbolKind::Var
|
|
| SymbolKind::Port
|
|
| SymbolKind::Param
|
|
| SymbolKind::LocalParam
|
|
| SymbolKind::Genvar
|
|
| SymbolKind::TfArg
|
|
)
|
|
});
|
|
}
|
|
at = current.parent.map(|p| p.0 as usize);
|
|
}
|
|
false
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn at(text: &str, needle: &str) -> u32 {
|
|
text.find(needle).expect("needle present") as u32
|
|
}
|
|
|
|
/// An interface is `SymbolKind::Interface` since 2026-09-01
|
|
/// (`docs/features/interface-semantics/README.md`), and `locate_module`
|
|
/// asks `is_instantiable()` rather than `kind == Module` — so adding a
|
|
/// port to an interface, and rewriting every instantiation of it, works
|
|
/// exactly as it did when an interface was indexed as a module.
|
|
#[test]
|
|
fn a_port_refactoring_finds_an_interface_the_way_it_finds_a_module() {
|
|
let files = vec![
|
|
(
|
|
std::path::PathBuf::from("/rtl/bus_if.sv"),
|
|
"interface bus_if (input logic clk);\nendinterface\n".to_string(),
|
|
),
|
|
(
|
|
std::path::PathBuf::from("/rtl/top.sv"),
|
|
"module top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n".to_string(),
|
|
),
|
|
];
|
|
let edit = crate::add_port(&files, crate::ModuleRef::Name("bus_if"), "input logic rst_n")
|
|
.expect("an interface's port list is refactored like a module's");
|
|
let paths: Vec<String> = edit.edits.iter().map(|(p, _)| p.display().to_string()).collect();
|
|
assert!(paths.contains(&"/rtl/bus_if.sv".to_string()), "{paths:?}");
|
|
assert!(
|
|
paths.contains(&"/rtl/top.sv".to_string()),
|
|
"the instantiation is rewritten too: {paths:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_port_declaration_must_be_exactly_one_directed_port() {
|
|
assert_eq!(parse_port_decl("input logic [7:0] cfg").map(|p| p.name), Ok("cfg".into()));
|
|
assert_eq!(
|
|
parse_port_decl(" output wire q ").map(|p| p.text),
|
|
Ok("output wire q".into())
|
|
);
|
|
assert!(parse_port_decl("").is_err(), "empty");
|
|
assert!(parse_port_decl("logic a").is_err(), "no direction");
|
|
assert!(parse_port_decl("input a, input b").is_err(), "two ports");
|
|
assert!(parse_port_decl("input a,").is_err(), "a dangling comma");
|
|
assert!(parse_port_decl("input a); wire evil; //").is_err(), "an escape from the list");
|
|
assert!(parse_port_decl("input a /* hm */").is_err(), "a comment");
|
|
assert!(parse_port_decl("`PORT(a)").is_err(), "a macro call");
|
|
assert!(parse_port_decl("input a; input b").is_err(), "two declarations");
|
|
}
|
|
|
|
#[test]
|
|
fn an_appended_element_copies_the_lists_layout() {
|
|
// Inline stays inline.
|
|
let inline = "module m (input a, input b);";
|
|
let elements = [TextRange::new(10, 17), TextRange::new(19, 26)];
|
|
let edits = append_to_list(inline, Some(9), &elements, "input c");
|
|
assert_eq!(edits.len(), 1);
|
|
assert_eq!(crate::apply(inline, &edits), "module m (input a, input b, input c);");
|
|
|
|
// One per line stays one per line, at the last element's indentation.
|
|
let stacked = "module m (\n input a,\n input b\n);";
|
|
let elements = [TextRange::new(15, 22), TextRange::new(28, 35)];
|
|
let edits = append_to_list(stacked, Some(9), &elements, "input c");
|
|
assert_eq!(
|
|
crate::apply(stacked, &edits),
|
|
"module m (\n input a,\n input b,\n input c\n);"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn an_append_after_a_line_comment_writes_the_comma_before_it() {
|
|
let text = "module m (\n input a // why\n);";
|
|
let a = TextRange::new(at(text, "input a"), at(text, "input a") + 7);
|
|
let edits = append_to_list(text, Some(9), &[a], "input b");
|
|
assert_eq!(edits.len(), 2, "one for the comma, one for the element");
|
|
assert_eq!(crate::apply(text, &edits), "module m (\n input a, // why\n input b\n);");
|
|
}
|
|
|
|
#[test]
|
|
fn an_append_to_an_empty_list_writes_between_the_parens() {
|
|
let text = "module m ();";
|
|
let edits = append_to_list(text, Some(9), &[], "input a");
|
|
assert_eq!(crate::apply(text, &edits), "module m (input a);");
|
|
}
|
|
|
|
#[test]
|
|
fn removing_an_element_takes_one_comma_with_it() {
|
|
let text = "module m (input a, input b, input c);";
|
|
let elements = [TextRange::new(10, 17), TextRange::new(19, 26), TextRange::new(28, 35)];
|
|
let first = remove_element(text, &elements, 0).expect("an edit");
|
|
assert_eq!(crate::apply(text, &first), "module m (input b, input c);");
|
|
let last = remove_element(text, &elements, 2).expect("an edit");
|
|
assert_eq!(crate::apply(text, &last), "module m (input a, input b);");
|
|
}
|
|
|
|
#[test]
|
|
fn removing_a_line_of_its_own_takes_the_line() {
|
|
let text = "module m (\n input a,\n input b\n);";
|
|
let elements = [TextRange::new(13, 20), TextRange::new(24, 31)];
|
|
let first = remove_element(text, &elements, 0).expect("an edit");
|
|
assert_eq!(crate::apply(text, &first), "module m (\n input b\n);", "no blank line left");
|
|
}
|
|
|
|
#[test]
|
|
fn an_indent_is_only_the_whitespace_a_line_starts_with() {
|
|
assert_eq!(line_indent(" input a;", 2), " ");
|
|
assert_eq!(line_indent("\tinput a;", 1), "\t");
|
|
assert_eq!(line_indent("x = 1; input a;", 7), "", "not the first thing on its line");
|
|
}
|
|
|
|
#[test]
|
|
fn a_same_line_block_comment_is_written_past_but_a_line_comment_is_not() {
|
|
let text = "input a /* c */ , b";
|
|
let after = after_same_line_comments(text, 7);
|
|
assert_eq!(after.at, 15);
|
|
assert!(!after.line_comment);
|
|
|
|
let text = "input a // c\ninput b";
|
|
let after = after_same_line_comments(text, 7);
|
|
assert_eq!(after.at, 12, "the end of the comment, not of the line");
|
|
assert!(after.line_comment);
|
|
|
|
let text = "input a /* two\nlines */";
|
|
let after = after_same_line_comments(text, 7);
|
|
assert_eq!(after.at, 7, "a multi-line comment is left where it is");
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_header_hides_its_parameter_list_from_the_port_list() {
|
|
let text = "module m #(parameter W = 1) (input a);\nendmodule\n";
|
|
let tokens = tokenize(text).expect("lexes");
|
|
let name_end = at(text, "m #") + 1;
|
|
let (open, close) = port_list_parens(&tokens, name_end).expect("a port list");
|
|
assert_eq!(open, at(text, "(input"));
|
|
assert_eq!(close, at(text, ");"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_header_with_no_port_list_ends_at_its_semicolon() {
|
|
let text = "module m;\nendmodule\n";
|
|
let tokens = tokenize(text).expect("lexes");
|
|
assert_eq!(header_semicolon(&tokens, 8), Some(8));
|
|
assert_eq!(port_list_parens(&tokens, 8), None);
|
|
}
|
|
}
|