313 lines
14 KiB
Rust
313 lines
14 KiB
Rust
//! The in-scope files, the index built from them, and the analyses computed
|
|
//! so far — what every refactoring in this crate reads the workspace through.
|
|
//! Nothing here is specific to a rename: `ports`, `references` and
|
|
//! `instantiate` read the same workspace, which is why it sits at the crate
|
|
//! root rather than under one of them.
|
|
//!
|
|
//! **One parse per file** (take 5 §P2b). Building the index parses and
|
|
//! analyses every in-scope file already — `FileFacts::of` is a parse, an
|
|
//! `analyze` and a read-off — and used to throw that analysis away, so the
|
|
//! first thing every refactoring did was parse a third of those files a
|
|
//! second time. [`FileFacts::analyzed`] hands the analysis back instead, and
|
|
//! [`Scope::build_keeping`] retains the ones a caller says it will want. What
|
|
//! is retained is a *cache and nothing else*: a file whose analysis was not
|
|
//! kept is analysed on demand exactly as before, so a retention rule that
|
|
//! guesses wrong costs time and cannot change an answer.
|
|
|
|
use std::collections::HashMap;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use vlog_parser::parse_source_tolerant;
|
|
use vlog_semantic::{
|
|
analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics,
|
|
WorkspaceIndex,
|
|
};
|
|
|
|
/// One file's two analysis layers, as `textDocument/definition` uses them.
|
|
pub(crate) struct Analysis {
|
|
pub(crate) semantics: Semantics,
|
|
pub(crate) external: ExternalResolutions,
|
|
}
|
|
|
|
/// The in-scope files, the index built from them, and the analyses computed so
|
|
/// far. Analyses are built on demand: a rename usually needs a handful of the
|
|
/// workspace's files, and analyzing the rest would be pure cost.
|
|
pub(crate) struct Scope<'a> {
|
|
/// Path and text, sorted by path and deduplicated the way
|
|
/// `WorkspaceIndex::build` does it, so index `i` and `FileId(i)`'s texts
|
|
/// agree.
|
|
sources: Vec<(&'a Path, &'a str)>,
|
|
pub(crate) index: WorkspaceIndex,
|
|
/// Source index → the index's own file id.
|
|
file_ids: Vec<Option<FileId>>,
|
|
cache: HashMap<usize, Analysis>,
|
|
/// The `Semantics` the index build kept, by source index — the half of an
|
|
/// [`Analysis`] that does not depend on the finished index. Moved into
|
|
/// `cache` the first time that file's analysis is asked for.
|
|
kept: HashMap<usize, Semantics>,
|
|
}
|
|
|
|
impl<'a> Scope<'a> {
|
|
/// The in-scope files, indexed, keeping no analysis.
|
|
///
|
|
/// Each file is still parsed and analysed exactly once — that is what
|
|
/// building the index costs — and every later `analysis` call parses
|
|
/// again, which is the behaviour every caller but the rename has always
|
|
/// had. [`Scope::build_keeping`] is the one that keeps them.
|
|
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
|
|
Scope::assemble(files, None, |_| Vec::new())
|
|
}
|
|
|
|
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
|
|
/// every file whose text mentions one of the words `keep` asks for.
|
|
///
|
|
/// `lead` — the file the request was made in — is analysed first, and
|
|
/// `keep` is then asked which words are worth retaining *given that
|
|
/// analysis*. That ordering is the whole trick: a rename cannot know the
|
|
/// name under the cursor until something has analysed the cursor's file,
|
|
/// and this way that analysis is the file's own one-and-only parse rather
|
|
/// than an extra one.
|
|
///
|
|
/// The rule is `text.contains(word)` — a substring test, deliberately the
|
|
/// same prefilter [`Scope::collect_occurrences`] uses, so every file the
|
|
/// occurrence walk will analyse and every file
|
|
/// [`crate::check`] will watch (a whole-word subset) is retained, and
|
|
/// nothing else is.
|
|
pub(crate) fn build_keeping(
|
|
files: &'a [(PathBuf, String)],
|
|
lead: &Path,
|
|
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
|
) -> Scope<'a> {
|
|
Scope::assemble(files, Some(lead), keep)
|
|
}
|
|
|
|
fn assemble(
|
|
files: &'a [(PathBuf, String)],
|
|
lead: Option<&Path>,
|
|
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
|
) -> Scope<'a> {
|
|
let mut sources: Vec<(&Path, &str)> =
|
|
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
|
// The same normalization `WorkspaceIndex::build` applies: a stable
|
|
// sort by path, then the first copy of a repeated path wins.
|
|
sources.sort_by(|a, b| a.0.cmp(b.0));
|
|
sources.dedup_by(|a, b| a.0 == b.0);
|
|
|
|
let mut builder = IndexBuilder::new();
|
|
let mut kept: HashMap<usize, Semantics> = HashMap::new();
|
|
// The lead file first, so its analysis can be read before the rest are
|
|
// parsed. `IndexBuilder::finish` sorts by path, so feeding it out of
|
|
// order cannot reach the index.
|
|
let first = lead.and_then(|path| sources.iter().position(|(held, _)| *held == path));
|
|
if let Some(i) = first {
|
|
let (path, text) = sources[i];
|
|
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
|
|
builder.add_facts(facts);
|
|
kept.insert(i, semantics);
|
|
}
|
|
let words = keep(first.and_then(|i| kept.get(&i)));
|
|
for (i, (path, text)) in sources.iter().enumerate() {
|
|
if Some(i) == first {
|
|
continue;
|
|
}
|
|
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
|
|
builder.add_facts(facts);
|
|
if words.iter().any(|word| text.contains(word.as_str())) {
|
|
kept.insert(i, semantics);
|
|
}
|
|
}
|
|
|
|
let index = builder.finish();
|
|
let ids: HashMap<&Path, FileId> = index
|
|
.files()
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
|
|
.collect();
|
|
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
|
|
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
|
|
}
|
|
|
|
pub(crate) fn len(&self) -> usize {
|
|
self.sources.len()
|
|
}
|
|
|
|
pub(crate) fn path(&self, i: usize) -> Option<&'a Path> {
|
|
self.sources.get(i).map(|(path, _)| *path)
|
|
}
|
|
|
|
pub(crate) fn text(&self, i: usize) -> Option<&'a str> {
|
|
self.sources.get(i).map(|(_, text)| *text)
|
|
}
|
|
|
|
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
|
|
self.file_ids.get(i).copied().flatten()
|
|
}
|
|
|
|
pub(crate) fn index_of(&self, path: &Path) -> Option<usize> {
|
|
self.sources.iter().position(|(p, _)| *p == path)
|
|
}
|
|
|
|
/// The two analysis layers for one file, computed on first use.
|
|
///
|
|
/// The local half is the one the index build already made, when it was
|
|
/// kept; otherwise it is parsed here, exactly as it always was. The
|
|
/// external half is this scope's index resolved against it, and is
|
|
/// computed here either way — it cannot exist before the index does.
|
|
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
|
|
let Scope { sources, index, cache, kept, .. } = self;
|
|
let text = sources.get(i).map(|(_, text)| *text)?;
|
|
Some(cache.entry(i).or_insert_with(|| {
|
|
let semantics =
|
|
kept.remove(&i).unwrap_or_else(|| analyze(&parse_source_tolerant(text).0, text));
|
|
let external = resolve_external(&semantics, index);
|
|
Analysis { semantics, external }
|
|
}))
|
|
}
|
|
|
|
/// One file's analysis, but only if it has already been computed — what
|
|
/// the verification pass reads while it also holds the index.
|
|
pub(crate) fn cached(&self, i: usize) -> Option<&Analysis> {
|
|
self.cache.get(&i)
|
|
}
|
|
|
|
/// One watched file's after-print inputs: the local analysis the
|
|
/// before-pass already computed, and its uses resolved against `index`.
|
|
///
|
|
/// A file the edits did not touch has the same declarations and the same
|
|
/// uses afterwards — its text did not change — so only what the workspace
|
|
/// answers *for* those uses can have moved, and re-resolving is the whole
|
|
/// of the difference. Re-parsing it to learn that is the work take 5 §P2c
|
|
/// removes.
|
|
///
|
|
/// `None` when that file's local analysis has not been computed. The
|
|
/// caller's own before-pass is what computes it, so that is a
|
|
/// contradiction rather than a fallback.
|
|
pub(crate) fn against(
|
|
&self,
|
|
i: usize,
|
|
index: &WorkspaceIndex,
|
|
) -> Option<(&Semantics, ExternalResolutions)> {
|
|
let semantics = &self.cached(i)?.semantics;
|
|
Some((semantics, resolve_external(semantics, index)))
|
|
}
|
|
|
|
/// The workspace index the edits were computed against.
|
|
pub(crate) fn index(&self) -> &WorkspaceIndex {
|
|
&self.index
|
|
}
|
|
}
|
|
|
|
/// How a file is named in a message: its file name, because an absolute path
|
|
/// in a rename box is unreadable.
|
|
pub(crate) fn display(path: &Path) -> String {
|
|
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const FILES: [(&str, &str); 4] = [
|
|
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
|
("/w/top.sv", "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign u_sub.sig = 1'b0;\nendmodule\n"),
|
|
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
|
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
|
];
|
|
|
|
fn files() -> Vec<(PathBuf, String)> {
|
|
FILES.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect()
|
|
}
|
|
|
|
/// Every declaration and use one analysis holds, as comparable text — the
|
|
/// whole observable of a `Semantics` plus its overlay.
|
|
fn print(analysis: &Analysis) -> String {
|
|
let mut out = String::new();
|
|
for symbol in analysis.semantics.symbols() {
|
|
out.push_str(&format!(
|
|
"sym {} {:?} {}..{}\n",
|
|
symbol.name, symbol.kind, symbol.name_span.start, symbol.name_span.end
|
|
));
|
|
}
|
|
for (id, reference) in analysis.semantics.references().iter().enumerate() {
|
|
out.push_str(&format!(
|
|
"ref {} {}..{} -> {:?} / {:?}\n",
|
|
reference.name,
|
|
reference.name_span.start,
|
|
reference.name_span.end,
|
|
reference.resolution,
|
|
analysis.external.get(vlog_semantic::ReferenceId(id as u32))
|
|
));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The scope's index is the index a plain `WorkspaceIndex::build` gives —
|
|
/// same fingerprint, same file ids — however the scope was assembled.
|
|
#[test]
|
|
fn assembling_the_scope_file_by_file_builds_the_same_index() {
|
|
let files = files();
|
|
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
|
let plain = Scope::build(&files);
|
|
assert_eq!(plain.index().fingerprint(), built.fingerprint());
|
|
let keeping =
|
|
Scope::build_keeping(&files, Path::new("/w/top.sv"), |_| vec!["sig".to_string()]);
|
|
assert_eq!(keeping.index().fingerprint(), built.fingerprint());
|
|
for i in 0..plain.len() {
|
|
assert_eq!(plain.file_id(i), keeping.file_id(i), "file ids move with retention");
|
|
assert_eq!(plain.path(i), keeping.path(i));
|
|
}
|
|
}
|
|
|
|
/// A retained analysis is the analysis the on-demand path would compute.
|
|
/// This is the whole of §P2b's correctness: what is kept is not a second
|
|
/// opinion, it is the same one, not thrown away.
|
|
#[test]
|
|
fn a_retained_analysis_is_the_one_the_on_demand_path_would_compute() {
|
|
let files = files();
|
|
let mut plain = Scope::build(&files);
|
|
let mut keeping = Scope::build_keeping(&files, Path::new("/w/top.sv"), |here| {
|
|
// Every word in play, so every file is retained.
|
|
assert!(here.is_some(), "the lead file's analysis is made first");
|
|
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
|
|
});
|
|
for i in 0..plain.len() {
|
|
let one = plain.analysis(i).map(print);
|
|
let two = keeping.analysis(i).map(print);
|
|
assert_eq!(one, two, "file {i} analyses differently when it is retained");
|
|
}
|
|
}
|
|
|
|
/// The lead file's analysis is made **before** the rest are parsed, which
|
|
/// is what lets a caller read the cursor's name off it and ask for that
|
|
/// name to be kept — without a second parse of anything.
|
|
#[test]
|
|
fn the_lead_files_analysis_is_available_to_the_retention_rule() {
|
|
let files = files();
|
|
let mut seen = None;
|
|
let scope = Scope::build_keeping(&files, Path::new("/w/user.sv"), |here| {
|
|
seen = here.map(|semantics| semantics.symbols().len());
|
|
Vec::new()
|
|
});
|
|
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
|
|
assert_eq!(scope.len(), 4);
|
|
}
|
|
|
|
/// A lead the scope does not hold is not an error: nothing is retained,
|
|
/// and the rest of the build is what it always was.
|
|
#[test]
|
|
fn a_lead_outside_the_scope_retains_nothing_and_still_builds() {
|
|
let files = files();
|
|
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
|
let mut asked = false;
|
|
let mut scope = Scope::build_keeping(&files, Path::new("/w/absent.sv"), |here| {
|
|
asked = true;
|
|
assert!(here.is_none(), "there is no lead analysis to offer");
|
|
vec!["sig".to_string()]
|
|
});
|
|
assert!(asked, "the retention rule is asked either way");
|
|
assert_eq!(scope.index().fingerprint(), built.fingerprint());
|
|
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
|
|
}
|
|
}
|