Files
lucisv/crates/vlog_refactor/src/references.rs
T

183 lines
7.0 KiB
Rust

//! Find-all-references: the read-only half of what a rename already computes.
//!
//! A rename resolves the cursor to a *declaration* and then collects every
//! occurrence of that declaration across the in-scope files. Listing those
//! occurrences is the same walk with the edits left off, so it is the same
//! code — this module only decides what to do with the spans. The sharing is
//! the point, not the lines it saves: a reference list that disagreed with
//! what a rename would touch would be a lie about what lucisv is going to do.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use crate::rename::Scope;
/// Every occurrence of the symbol at `offset` in `file`, across `files`.
///
/// `files` is the in-scope set — path and current text, open buffers already
/// overlaying disk — exactly what [`crate::rename`] takes. The result is
/// sorted by path and then by position, and every span slices back to the
/// name it claims.
///
/// An `Err` is the sentence a rename at the same position would refuse with
/// (nothing here to name, a name declared in two indexed files, a use nothing
/// resolves). A caller that only wants to draw highlights can fall back to
/// the file's own answer rather than showing it.
pub fn find_references(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
include_declaration: bool,
) -> Result<Vec<(PathBuf, TextRange)>, String> {
let mut scope = Scope::build(files);
let target = scope.locate(file, offset)?;
let declaration = scope.declaration_span(&target);
let found = scope.collect_occurrences(&target)?;
let mut out: Vec<(PathBuf, TextRange)> = Vec::new();
for (i, mut spans) in found {
let (Some(path), Some(text)) = (scope.path(i), scope.text(i)) else { continue };
if !include_declaration && i == target.file {
if let Some(span) = declaration {
spans.retain(|s| *s != span);
}
}
// The semantic layer promises a name span slices back to its own
// name. A span that does not is not a place to send an editor, and
// dropping it costs one string comparison per occurrence.
spans.retain(|s| text.get(s.as_range()) == Some(target.name.as_str()));
spans.sort_by_key(|s| (s.start, s.end));
spans.dedup();
out.extend(spans.into_iter().map(|span| (path.to_path_buf(), span)));
}
out.sort_by(|a, b| (a.0.as_path(), a.1.start).cmp(&(b.0.as_path(), b.1.start)));
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
const SUB: &str = "module sub (input logic clk);\nendmodule\n";
const TOP: &str = "module top;\n sub u_a (.clk(1'b0));\n sub u_b (.clk(1'b1));\nendmodule\n";
const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n";
fn files() -> Vec<(PathBuf, String)> {
vec![
(PathBuf::from("/w/sub.sv"), SUB.to_string()),
(PathBuf::from("/w/top.sv"), TOP.to_string()),
(PathBuf::from("/w/other.sv"), OTHER.to_string()),
]
}
fn at(text: &str, needle: &str) -> u32 {
text.find(needle).expect("needle present") as u32
}
/// `(file name, byte start)` of every hit, which is enough to read.
fn hits(found: &[(PathBuf, TextRange)]) -> Vec<(String, u32)> {
found
.iter()
.map(|(path, span)| {
(path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string(), span.start)
})
.collect()
}
#[test]
fn a_modules_references_come_from_every_file_that_instantiates_it() {
let files = files();
let found =
find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), true).expect("found");
assert_eq!(
hits(&found),
vec![
("other.sv".to_string(), at(OTHER, "sub u_c")),
("sub.sv".to_string(), at(SUB, "sub")),
("top.sv".to_string(), at(TOP, "sub u_a")),
("top.sv".to_string(), at(TOP, "sub u_b")),
]
);
}
#[test]
fn the_answer_is_the_same_from_an_instantiation_as_from_the_declaration() {
let files = files();
let from_declaration =
find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), true).expect("found");
let from_use =
find_references(&files, Path::new("/w/top.sv"), at(TOP, "sub u_b"), true).expect("f");
assert_eq!(hits(&from_declaration), hits(&from_use));
}
#[test]
fn include_declaration_drops_only_the_declarations_own_name() {
let files = files();
let without =
find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), false).expect("found");
assert_eq!(
hits(&without),
vec![
("other.sv".to_string(), at(OTHER, "sub u_c")),
("top.sv".to_string(), at(TOP, "sub u_a")),
("top.sv".to_string(), at(TOP, "sub u_b")),
]
);
}
#[test]
fn a_package_member_is_found_at_every_import_site() {
let pkg = "package p;\n localparam WIDTH = 8;\nendpackage\n";
let a = "module a;\n import p::*;\n wire [WIDTH-1:0] x;\nendmodule\n";
let b = "module b;\n wire [p::WIDTH-1:0] y;\nendmodule\n";
let files = vec![
(PathBuf::from("/w/p.sv"), pkg.to_string()),
(PathBuf::from("/w/a.sv"), a.to_string()),
(PathBuf::from("/w/b.sv"), b.to_string()),
];
let found =
find_references(&files, Path::new("/w/p.sv"), at(pkg, "WIDTH"), false).expect("found");
assert_eq!(
hits(&found),
vec![("a.sv".to_string(), at(a, "WIDTH-1")), ("b.sv".to_string(), at(b, "WIDTH-1")),]
);
}
#[test]
fn a_local_signal_is_answered_from_its_own_file_only() {
let m = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
let other = "module other;\n wire a;\n assign a = 0;\nendmodule\n";
let files = vec![
(PathBuf::from("/w/m.sv"), m.to_string()),
(PathBuf::from("/w/other.sv"), other.to_string()),
];
let found =
find_references(&files, Path::new("/w/m.sv"), at(m, "wire a") + 5, true).expect("f");
assert_eq!(
hits(&found),
vec![
("m.sv".to_string(), at(m, "wire a") + 5),
("m.sv".to_string(), at(m, "assign a") + 7),
]
);
}
#[test]
fn a_name_two_files_declare_is_refused_rather_than_guessed() {
let files = vec![
(PathBuf::from("/w/a.sv"), "module dup;\nendmodule\n".to_string()),
(PathBuf::from("/w/b.sv"), "module dup;\nendmodule\n".to_string()),
];
let message =
find_references(&files, Path::new("/w/a.sv"), 7, true).expect_err("ambiguous");
assert!(message.contains("more than one indexed file"), "{message}");
}
#[test]
fn a_position_on_nothing_is_refused() {
let files = files();
assert!(find_references(&files, Path::new("/w/sub.sv"), 0, true).is_err(), "the keyword");
}
}