1206 lines
54 KiB
Rust
1206 lines
54 KiB
Rust
//! Perf measurements for the paths a keystroke and a hover run through.
|
||
//!
|
||
//! Not a benchmark harness: every test here is `#[ignore]`d, asserts nothing
|
||
//! about how long anything took, and exists only to print a number an agent
|
||
//! can compare against the numbers recorded in `docs/perf/README.md`. The
|
||
//! shape is the one the hover QA round already used — `Instant` plus
|
||
//! `eprintln!` — because a real benchmark crate would be a new dependency,
|
||
//! and a dependency needs a written justification this does not have.
|
||
//!
|
||
//! Run them all with:
|
||
//!
|
||
//! ```text
|
||
//! cargo test --release -p lucisv_server perf:: -- --ignored --nocapture \
|
||
//! --test-threads=1
|
||
//! ```
|
||
//!
|
||
//! `--test-threads=1` is not optional: the default harness runs these tests
|
||
//! concurrently with each other and with the rest of the suite, and a
|
||
//! measurement taken while three other tests fight it for a core is noise.
|
||
|
||
use std::hint::black_box;
|
||
use std::path::PathBuf;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use vlog_parser::defines::collect_defines;
|
||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||
use vlog_semantic::{analyze, resolve_external, WorkspaceIndex};
|
||
|
||
use crate::hover::hover;
|
||
use crate::state::{first_token_from, first_token_reaching, Document, Workspace};
|
||
use crate::uri::path_to_uri;
|
||
|
||
/// The two input sizes every measurement is taken at: a large-ish real module
|
||
/// and a file nobody enjoys opening.
|
||
const SIZES: [usize; 2] = [1_000, 10_000];
|
||
|
||
/// A generated module of about `lines` lines: an ANSI header, then repeated
|
||
/// four-line blocks of the shapes RTL is mostly made of — a wire, an assign, a
|
||
/// register and its update. Every block declares two names and uses four, so
|
||
/// what is measured is ordinary declaration and resolution work rather than
|
||
/// one pathological construct.
|
||
fn generated_module(name: &str, lines: usize) -> String {
|
||
let mut src = format!(
|
||
"module {name} (\n input logic clk,\n input logic rst_n,\n \
|
||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n"
|
||
);
|
||
for n in 0..lines.saturating_sub(8) / 4 {
|
||
src.push_str(&format!(
|
||
" wire [31:0] w_{n};\n \
|
||
assign w_{n} = data_in ^ {{32{{rst_n}}}};\n \
|
||
reg [31:0] r_{n};\n \
|
||
always @(posedge clk) r_{n} <= w_{n};\n"
|
||
));
|
||
}
|
||
src.push_str(" assign data_out = data_in;\nendmodule\n");
|
||
src
|
||
}
|
||
|
||
/// The mean of `runs` runs. One run of a millisecond-scale operation is mostly
|
||
/// scheduling noise; a mean of a handful is the number worth writing down.
|
||
///
|
||
/// `pub(crate)` so the probes that live beside the code they measure —
|
||
/// `nav.rs`'s references-latency probes — time themselves the same way these
|
||
/// do, rather than each growing its own stopwatch.
|
||
pub(crate) fn mean(runs: u32, mut body: impl FnMut()) -> Duration {
|
||
let start = Instant::now();
|
||
for _ in 0..runs {
|
||
body();
|
||
}
|
||
start.elapsed() / runs
|
||
}
|
||
|
||
/// A scratch directory holding the generated files a measurement needs,
|
||
/// removed when the measurement is done.
|
||
fn scratch(tag: &str, files: &[(&str, &str)]) -> PathBuf {
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||
for (name, text) in files {
|
||
std::fs::write(dir.join(name), text).expect("write");
|
||
}
|
||
dir
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::analyzing -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn analyzing_a_generated_module() {
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let (tree, _) = parse_source_tolerant(&src);
|
||
let took = mean(10, || {
|
||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||
});
|
||
let symbols = analyze(&tree, &src).symbols().len();
|
||
eprintln!(
|
||
"analyze: {lines} lines ({} KB, {symbols} symbols) took {took:?}",
|
||
src.len() / 1000
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::opening -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn opening_a_buffer_end_to_end() {
|
||
// What one flushed keystroke costs: lex, parse, analyze, resolve against
|
||
// the index. The index holds the same file, so `resolve_external` has
|
||
// something real to answer from rather than an empty table.
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let path = PathBuf::from("gen.sv");
|
||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||
let took = mean(10, || {
|
||
black_box(Document::new(Some(path.clone()), src.clone(), &index));
|
||
});
|
||
eprintln!("Document::new: {lines} lines ({} KB) took {took:?}", src.len() / 1000);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::breaking_down -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn breaking_down_one_flushed_keystroke() {
|
||
// `opening_a_buffer_end_to_end` says what a flush costs; this says where
|
||
// that cost is, stage by stage, in the order `Document::new` runs them —
|
||
// plus the diagnostics pass, which is *not* inside `Document::new` but
|
||
// runs on every publish, so a flush is the sum of the two.
|
||
//
|
||
// `parse_tolerant` consumes its token vector, so each run of the parse
|
||
// needs a fresh clone; the clone is measured on its own line and the parse
|
||
// line is reported with the clone still in it. Subtracting one from the
|
||
// other is the honest reading, and it is what `Document::new` really pays.
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let path = PathBuf::from("gen.sv");
|
||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||
let (tree, _) = parse_tolerant(tokens.clone(), &src);
|
||
let semantics = analyze(&tree, &src);
|
||
let doc = Document::new(Some(path.clone()), src.clone(), &index);
|
||
|
||
let lex = mean(20, || {
|
||
black_box(tokenize(black_box(&src)).is_ok());
|
||
});
|
||
let clone = mean(20, || {
|
||
black_box(tokens.clone());
|
||
});
|
||
let parse = mean(20, || {
|
||
black_box(parse_tolerant(black_box(tokens.clone()), black_box(&src)));
|
||
});
|
||
let defines = mean(200, || {
|
||
black_box(collect_defines(black_box(&tokens)));
|
||
});
|
||
let analyzing = mean(20, || {
|
||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||
});
|
||
let external = mean(200, || {
|
||
black_box(resolve_external(black_box(&semantics), black_box(&index)));
|
||
});
|
||
let line_index = mean(200, || {
|
||
black_box(LineIndex::new(black_box(&src)));
|
||
});
|
||
let lint = mean(20, || {
|
||
black_box(crate::diagnostics::all(black_box(&doc)));
|
||
});
|
||
|
||
eprintln!(
|
||
"flush breakdown, {lines} lines ({} tokens): tokenize {lex:?}, \
|
||
tokens.clone() {clone:?}, parse_tolerant (clone included) {parse:?}, \
|
||
collect_defines {defines:?}, analyze {analyzing:?}, \
|
||
resolve_external {external:?}, LineIndex::new {line_index:?}, \
|
||
diagnostics::all {lint:?}",
|
||
tokens.len()
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::finding_one_token -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn finding_one_token_against_sweeping_the_stream() {
|
||
// The before/after of the interactive handlers' token lookups, on the
|
||
// lookup alone. Both halves run in the same measurement, against the same
|
||
// stream, so neither number depends on remembering an earlier run.
|
||
//
|
||
// The cursor sits three quarters of the way down the file. A sweep costs
|
||
// the distance from token zero, so measuring at the top would flatter it
|
||
// and measuring at the very end would flatter it in the other direction;
|
||
// three quarters is an ordinary place for a cursor to be.
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||
let at = tokens[tokens.len() * 3 / 4].span.start;
|
||
|
||
// `selection.rs`: the innermost step of an expand-selection chain.
|
||
let covers = |span: vlog_parser::TextRange| span.start <= at && at <= span.end;
|
||
let sweep = mean(1_000, || {
|
||
black_box(tokens.iter().find(|t| covers(t.span)).map(|t| t.span));
|
||
});
|
||
let search = mean(1_000, || {
|
||
black_box(
|
||
tokens.get(first_token_reaching(&tokens, black_box(at))).filter(|t| covers(t.span)),
|
||
);
|
||
});
|
||
|
||
// `completion.rs`: the balanced-parenthesis window between an opener
|
||
// and the cursor. This one swept the *whole* stream — the filter has
|
||
// no upper bound to break on — to reach a window two offsets name.
|
||
let from = tokens[tokens.len() / 2].span.end;
|
||
let window_sweep = mean(1_000, || {
|
||
black_box(tokens.iter().filter(|t| t.span.start >= from && t.span.start < at).count());
|
||
});
|
||
let window_search = mean(1_000, || {
|
||
let window = first_token_from(&tokens, black_box(from))..first_token_from(&tokens, at);
|
||
black_box(tokens[window].len());
|
||
});
|
||
|
||
eprintln!(
|
||
"one token among {}: sweeping {sweep:?}, binary search {search:?}; \
|
||
the balanced-paren window: sweeping {window_sweep:?}, \
|
||
binary search {window_search:?}",
|
||
tokens.len()
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::hovering_a_local -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn hovering_a_local_declaration() {
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let dir = scratch(&format!("local{lines}"), &[("gen.sv", src.as_str())]);
|
||
let mut ws = Workspace::default();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let uri = path_to_uri(&dir.join("gen.sv")).expect("uri");
|
||
ws.set_document(uri.clone(), src.clone());
|
||
// The last block's `w_n` use, so the answer is as far into the file as
|
||
// this file goes.
|
||
let offset = src.rfind("<= w_").expect("a use") as u32 + 4;
|
||
let took = mean(20, || {
|
||
black_box(hover(&ws, &uri, black_box(offset)));
|
||
});
|
||
assert!(hover(&ws, &uri, offset).is_some(), "the offset must be a name");
|
||
eprintln!("hover, local target: {lines} lines took {took:?}");
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::hovering_across -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn hovering_across_files_into_a_closed_file() {
|
||
// The disk path: the target file is closed, so the card's heading line
|
||
// comes from the index (`Def::lines`, no read at all) and its snippet from
|
||
// the workspace's shared view of that file — read once, then held. This
|
||
// is a *mean of twenty*, so nineteen of the runs are the held case: it is
|
||
// the steady-state hover, not the first touch (which
|
||
// `hovering_into_a_big_closed_file_first_touch_and_repeat` reports on its
|
||
// own). Measured beside it is the read the first touch pays and every
|
||
// later one does not.
|
||
for lines in SIZES {
|
||
let sub = generated_module("sub", lines);
|
||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||
let dir = scratch(&format!("cross{lines}"), &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||
let mut ws = Workspace::default();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||
ws.set_document(uri.clone(), top.to_string());
|
||
let offset = top.find("data_in(").expect("a port connection") as u32;
|
||
let took = mean(20, || {
|
||
black_box(hover(&ws, &uri, black_box(offset)));
|
||
});
|
||
let path = dir.join("sub.sv");
|
||
let one_read = mean(20, || {
|
||
let text = ws.text_of(black_box(&path)).expect("readable");
|
||
black_box(LineIndex::new(&text));
|
||
});
|
||
// The card really is the cross-file one, read off that file's disk
|
||
// text — a measurement of a hover that answered nothing is worthless.
|
||
let card = hover(&ws, &uri, offset).expect("a cross-file card");
|
||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||
eprintln!(
|
||
"hover, closed cross-file target: {lines} lines took {took:?} \
|
||
(one read + LineIndex of that file: {one_read:?}, which only the first touch pays)"
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::hovering_into_a_big -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn hovering_into_a_big_closed_file_first_touch_and_repeat() {
|
||
// The owner's report, measured: hovering an *instantiation* and hovering
|
||
// one of its *ports* into a closed file that is big — the netlist-adjacent
|
||
// shape a real workspace has one of. Two numbers per hover: the first
|
||
// touch of that file in the session, and the touch after it, which is the
|
||
// one a text cache can make free.
|
||
//
|
||
// "First touch" is cold to *this process* and to nothing else: the file
|
||
// was written moments ago, so the OS page cache still holds it and the
|
||
// read below is the cheap kind. A genuinely cold disk is worse than this,
|
||
// never better.
|
||
let sub = big_module("sub", 12_000_000);
|
||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||
let dir = scratch("bighover", &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||
let instantiation = top.find("sub u").expect("an instantiation") as u32;
|
||
let port = top.find("data_in(").expect("a port connection") as u32;
|
||
|
||
for (what, offset) in [("instantiation", instantiation), ("port", port)] {
|
||
// A fresh workspace per measurement, so "first touch" really is one.
|
||
let mut ws = Workspace::default();
|
||
ws.set_client_settings(crate::settings::ClientSettings {
|
||
max_file_size: 100_000_000,
|
||
..Default::default()
|
||
});
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
ws.set_document(uri.clone(), top.to_string());
|
||
|
||
let start = Instant::now();
|
||
let card = hover(&ws, &uri, black_box(offset)).expect("a cross-file card");
|
||
let first = start.elapsed();
|
||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||
let repeat = mean(10, || {
|
||
black_box(hover(&ws, &uri, black_box(offset)));
|
||
});
|
||
eprintln!(
|
||
"hover on a {what} into a {:.1} MB closed file: first touch {first:?}, \
|
||
repeat {repeat:?}",
|
||
sub.len() as f64 / 1_000_000.0
|
||
);
|
||
}
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// A module of at least `bytes` bytes: a small ANSI header — the declaration a
|
||
/// hover actually lands on — behind a wall of filler lines, which is the shape
|
||
/// of the files the owner's report is about.
|
||
fn big_module(name: &str, bytes: usize) -> String {
|
||
let mut src = format!("module {name} (\n input logic [31:0] data_in\n);\n");
|
||
let mut n = 0;
|
||
while src.len() < bytes {
|
||
src.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n"));
|
||
n += 1;
|
||
}
|
||
src.push_str("endmodule\n");
|
||
src
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn reindexing_one_changed_file() {
|
||
// What a save costs the index: one file re-parsed and merged, against a
|
||
// workspace of twenty files of the same size.
|
||
for lines in SIZES {
|
||
let sources: Vec<(PathBuf, String)> = (0..20)
|
||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), lines)))
|
||
.collect();
|
||
let index = WorkspaceIndex::build(
|
||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||
);
|
||
let (path, src) = &sources[7];
|
||
let took = mean(10, || {
|
||
let mut index = index.clone();
|
||
index.update_file(black_box(path.clone()), black_box(src));
|
||
black_box(index);
|
||
});
|
||
let clone = mean(10, || {
|
||
black_box(index.clone());
|
||
});
|
||
eprintln!(
|
||
"WorkspaceIndex::update_file: 20 files of {lines} lines took {took:?} \
|
||
(of which {clone:?} is the clone this measurement needs to repeat itself)"
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::what_a_scan -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn what_a_scan_does_before_its_first_file() {
|
||
// The floor under a mid-scan answer's latency. A scan answers messages
|
||
// between two *files*, so whatever it does before the first one is a
|
||
// block no drain can break up: resolving the scope, reading every
|
||
// in-scope file, and opening the persistent store. Measured because
|
||
// `docs/features/scan-interleave/README.md` files "read the files lazily"
|
||
// as a deliberate not-done, and a not-done is only honest with a number.
|
||
let files: Vec<(String, String)> =
|
||
(0..200).map(|n| (format!("m{n}.sv"), generated_module(&format!("m{n}"), 1_000))).collect();
|
||
let refs: Vec<(&str, &str)> =
|
||
files.iter().map(|(name, text)| (name.as_str(), text.as_str())).collect();
|
||
let dir = scratch("scanhead", &refs);
|
||
let mut workspace = Workspace::default();
|
||
workspace.set_client_settings(crate::settings::ClientSettings {
|
||
index_scope: crate::settings::IndexScope::Workspace,
|
||
..Default::default()
|
||
});
|
||
workspace.adopt_roots(vec![dir.clone()]);
|
||
let started = Instant::now();
|
||
let mut scan = workspace.begin_scan(&mut |_| {}, false);
|
||
let head = started.elapsed();
|
||
let started = Instant::now();
|
||
workspace.scan_step(&mut scan, &mut |_| {});
|
||
let one = started.elapsed();
|
||
let started = Instant::now();
|
||
while workspace.scan_step(&mut scan, &mut |_| {}) {}
|
||
let rest = started.elapsed();
|
||
let started = Instant::now();
|
||
workspace.finish_scan(scan);
|
||
let tail = started.elapsed();
|
||
eprintln!(
|
||
"scan of {} files of 1k lines: before the first file {head:?}, \
|
||
one file {one:?}, the other {} {rest:?}, finishing {tail:?}",
|
||
files.len(),
|
||
files.len() - 1
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::publishing -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn publishing_a_half_built_index_mid_scan() {
|
||
// What an interleaved scan's *publish* costs, against the per-file work it
|
||
// is interleaved with. `docs/features/scan-interleave/README.md` chose the
|
||
// publish rhythm from these numbers: a merge is a whole-index pass, so one
|
||
// per file would be quadratic and one per drain is not.
|
||
for files in [50usize, 200, 800] {
|
||
let sources: Vec<(PathBuf, String)> = (0..files)
|
||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), 1_000)))
|
||
.collect();
|
||
let records: Vec<vlog_semantic::FileFacts> = sources
|
||
.iter()
|
||
.map(|(path, src)| vlog_semantic::FileFacts::of(path.clone(), src))
|
||
.collect();
|
||
let parse = mean(3, || {
|
||
let (path, src) = &sources[0];
|
||
black_box(vlog_semantic::FileFacts::of(black_box(path.clone()), black_box(src)));
|
||
});
|
||
let build = mean(3, || {
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
for facts in &records {
|
||
builder.add_facts(facts.clone());
|
||
}
|
||
black_box(builder.finish());
|
||
});
|
||
let clone = mean(3, || {
|
||
black_box(records.clone());
|
||
});
|
||
let index = WorkspaceIndex::build(
|
||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||
);
|
||
let held = mean(10, || {
|
||
let mut index = index.clone();
|
||
index.update_facts(black_box(records[files / 2].clone()));
|
||
black_box(index);
|
||
});
|
||
let index_clone = mean(10, || {
|
||
black_box(index.clone());
|
||
});
|
||
eprintln!(
|
||
"{files} files of 1k lines: one file's parse {parse:?}; \
|
||
one whole merge {:?} (build {build:?} less {clone:?} of record cloning); \
|
||
one update_facts on a held file {:?} (less {index_clone:?} of index cloning); \
|
||
per-file feeding would cost {:?} of merging against {:?} of parsing",
|
||
build.saturating_sub(clone),
|
||
held.saturating_sub(index_clone),
|
||
held.saturating_sub(index_clone) * files as u32,
|
||
parse * files as u32,
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn looking_up_one_name_against_scanning_every_symbol() {
|
||
// The before/after of the name-keyed lookup, on the lookup alone. What
|
||
// `hover::live_symbol` actually saves is larger: every symbol the scan
|
||
// used to reach and reject by name is also an `indexed_def_for_symbol`
|
||
// call it no longer makes — two index lookups apiece.
|
||
for lines in SIZES {
|
||
let src = generated_module("gen", lines);
|
||
let (tree, _) = parse_source_tolerant(&src);
|
||
let semantics = analyze(&tree, &src);
|
||
let name = format!("w_{}", lines / 8);
|
||
let scan = mean(1_000, || {
|
||
let name = black_box(name.as_str());
|
||
black_box(semantics.symbols().iter().filter(|s| s.name == name).count());
|
||
});
|
||
let keyed = mean(1_000, || {
|
||
black_box(semantics.symbols_named(black_box(&name)).count());
|
||
});
|
||
eprintln!(
|
||
"one name among {} symbols: scanning {scan:?}, keyed lookup {keyed:?}",
|
||
semantics.symbols().len()
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::what_a_jump -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn what_a_jump_into_a_new_folder_costs_before_and_after() {
|
||
// The owner's opentitan report, on a workspace this repository generates
|
||
// for itself: many folders, browsed one jump at a time. Both shapes are
|
||
// measured in the same run over the same tree, so the pair is a real
|
||
// before/after and not two numbers from two days.
|
||
//
|
||
// * **before** — the whole rescan a widening `didOpen` used to run: every
|
||
// file of every folder reached so far, re-read, re-hashed and re-merged.
|
||
// It grows with every jump, which is the shape the report describes.
|
||
// * **after** — the widen: the files the opened folder brings in, folded
|
||
// into the index beside what is already there.
|
||
let (folders, each) = (40, 25);
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_jump_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
for folder in 0..folders {
|
||
let path = dir.join(format!("blk{folder:02}/rtl"));
|
||
std::fs::create_dir_all(&path).expect("folder");
|
||
for file in 0..each {
|
||
std::fs::write(
|
||
path.join(format!("f{file:02}.sv")),
|
||
generated_module(&format!("b{folder:02}_f{file:02}"), 200),
|
||
)
|
||
.expect("write");
|
||
}
|
||
}
|
||
|
||
// Two workspaces over the same tree, jumped through the same folders, so
|
||
// the only difference between the two columns is which path the widen
|
||
// took. Neither uses the persistent store: `cache_dir` answers `None` in
|
||
// this crate's tests unless a path is named, which is what keeps the
|
||
// measurement about the scan and not about a warm cache.
|
||
let mut whole = Workspace::default();
|
||
whole.adopt_roots(vec![dir.clone()]);
|
||
let mut incremental = Workspace::default();
|
||
incremental.adopt_roots(vec![dir.clone()]);
|
||
let mut rows: Vec<(usize, Duration, Duration, usize)> = Vec::new();
|
||
for jump in 0..6 {
|
||
let path = dir.join(format!("blk{jump:02}/rtl/f00.sv"));
|
||
let uri = path_to_uri(&path).expect("uri");
|
||
let text = std::fs::read_to_string(&path).expect("read");
|
||
|
||
whole.set_document(uri.clone(), text.clone());
|
||
let started = Instant::now();
|
||
black_box(whole.rebuild_index());
|
||
let rescan = started.elapsed();
|
||
|
||
let before = incremental.scope_dirs();
|
||
incremental.set_document(uri, text);
|
||
let added: Vec<PathBuf> =
|
||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||
let started = Instant::now();
|
||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||
while incremental.scan_step(&mut scan, &mut |_| {}) {}
|
||
black_box(incremental.finish_scan(scan));
|
||
let widen = started.elapsed();
|
||
|
||
assert_eq!(
|
||
whole.index().fingerprint(),
|
||
incremental.index().fingerprint(),
|
||
"the two columns must describe the same index, or the numbers mean nothing"
|
||
);
|
||
rows.push((jump, rescan, widen, incremental.index().files().len()));
|
||
}
|
||
eprintln!("a jump into a new folder, {folders} folders of {each} files of 200 lines:");
|
||
for (jump, rescan, widen, indexed) in rows {
|
||
eprintln!(
|
||
" jump {jump} ({indexed} files in scope after it): \
|
||
whole rescan {rescan:?}, incremental widen {widen:?}"
|
||
);
|
||
}
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::what_a_widen_that_subsumes -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn what_a_widen_that_subsumes_the_old_scope_costs() {
|
||
// `performance_take2.md` §5b, without opentitan: at the shipped
|
||
// `scopeDepth: 2` the first jump from a block's testbench into its own RTL
|
||
// raises the scope to the directory holding *every* block, which contains
|
||
// the one already in scope. The two things this prints are the two the
|
||
// report is about — how many files the widen actually reads (the new
|
||
// blocks, never the old one), and how long that takes against the whole
|
||
// rescan the same jump would otherwise cost.
|
||
let (blocks, rtl_each, dv_each) = (20, 25, 10);
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_subsume_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
for block in 0..blocks {
|
||
for (tag, folder, files) in [("r", "rtl", rtl_each), ("d", "dv/tb", dv_each)] {
|
||
let path = dir.join(format!("ip/blk{block:02}/{folder}"));
|
||
std::fs::create_dir_all(&path).expect("folder");
|
||
for file in 0..files {
|
||
// `corpus_file`, not `generated_module`: every name in it is
|
||
// the file's own, so the workspace-wide word table grows with
|
||
// the file count the way a real one does. That is the whole
|
||
// point of this shape — a widen's cost is dominated by what it
|
||
// does to tables the size of the workspace, not by the folder.
|
||
std::fs::write(
|
||
path.join(format!("f{file:02}.sv")),
|
||
corpus_file(&format!("b{block:02}{tag}_f{file:02}"), 200),
|
||
)
|
||
.expect("write");
|
||
}
|
||
}
|
||
}
|
||
let tb = dir.join("ip/blk00/dv/tb/f00.sv");
|
||
let rtl = dir.join("ip/blk00/rtl/f00.sv");
|
||
let open = |ws: &mut Workspace, path: &PathBuf| {
|
||
let uri = path_to_uri(path).expect("uri");
|
||
ws.set_document(uri, std::fs::read_to_string(path).expect("read"));
|
||
};
|
||
// The shipped rung: depth 2, clamped by a root above `ip/`.
|
||
let depth_two = |ws: &mut Workspace| {
|
||
ws.set_client_settings(crate::settings::ClientSettings {
|
||
index_scope_depth: 2,
|
||
..Default::default()
|
||
});
|
||
ws.adopt_roots(vec![dir.clone()]);
|
||
};
|
||
|
||
let mut whole = Workspace::default();
|
||
depth_two(&mut whole);
|
||
let mut incremental = Workspace::default();
|
||
depth_two(&mut incremental);
|
||
for ws in [&mut whole, &mut incremental] {
|
||
open(ws, &tb);
|
||
ws.rebuild_index();
|
||
}
|
||
let held = incremental.index().files().len();
|
||
|
||
open(&mut whole, &rtl);
|
||
let started = Instant::now();
|
||
black_box(whole.rebuild_index());
|
||
let rescan = started.elapsed();
|
||
|
||
let before = incremental.scope_dirs();
|
||
open(&mut incremental, &rtl);
|
||
let added: Vec<PathBuf> =
|
||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||
let mut read = 0usize;
|
||
let started = Instant::now();
|
||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
|
||
// Split out because it is where the 2026-08-29 round's fix landed: folding
|
||
// a widen's words into the completion table used to move the table's tail
|
||
// once per new word, which is quadratic in the batch and was 40% of the
|
||
// whole cost on opentitan's `hw/ip`.
|
||
let landing = Instant::now();
|
||
black_box(incremental.finish_scan(scan));
|
||
let (finish, widen) = (landing.elapsed(), started.elapsed());
|
||
|
||
assert_eq!(
|
||
whole.index().fingerprint(),
|
||
incremental.index().fingerprint(),
|
||
"the two columns must describe the same index, or the numbers mean nothing"
|
||
);
|
||
eprintln!(
|
||
"a widen that subsumes the old scope, {blocks} blocks of {} files:\n \
|
||
scope {held} -> {} files; the widen read {read} of them \
|
||
(the {held} already indexed are not re-read)\n \
|
||
whole rescan {rescan:?}, subsuming widen {widen:?} (landing it: {finish:?})",
|
||
rtl_each + dv_each,
|
||
incremental.index().files().len(),
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// The module-name families a completion prefix lands in, so a one-character
|
||
/// prefix names hundreds of modules and a five-character one names a handful —
|
||
/// the shape `performance.md`'s prefix table has on the real corpus.
|
||
const FAMILIES: [&str; 10] = [
|
||
"aes",
|
||
"prim",
|
||
"kmac",
|
||
"hmac",
|
||
"spi_device",
|
||
"otbn",
|
||
"flash_ctrl",
|
||
"rv_core",
|
||
"clkmgr",
|
||
"uart",
|
||
];
|
||
|
||
/// A workspace the size of the corpus `performance.md` measured against: one
|
||
/// module per file, named from [`FAMILIES`], each declaring names no other file
|
||
/// declares so the word table grows with the file count the way a real one does.
|
||
fn completion_corpus(dir: &std::path::Path, files: usize, body: usize) {
|
||
for n in 0..files {
|
||
let family = FAMILIES[n % FAMILIES.len()];
|
||
let name = format!("{family}_{n:04}");
|
||
std::fs::write(dir.join(format!("{name}.sv")), corpus_file(&name, body)).expect("write");
|
||
}
|
||
}
|
||
|
||
/// One corpus file: a package, then a module whose header is what a skeleton
|
||
/// reads and whose body is the several hundred lines a real RTL file carries
|
||
/// behind it.
|
||
fn corpus_file(name: &str, body: usize) -> String {
|
||
let mut text = format!(
|
||
"package {name}_pkg;\n localparam int {name}_WIDTH = 8;\n \
|
||
typedef logic [1:0] {name}_pair_t;\nendpackage\n\
|
||
module {name} #(\n parameter int WIDTH = 8\n) (\n \
|
||
input logic clk_i,\n input logic rst_ni,\n \
|
||
input logic [WIDTH-1:0] {name}_data_i,\n \
|
||
output logic [WIDTH-1:0] {name}_data_o\n);\n"
|
||
);
|
||
for n in 0..body / 4 {
|
||
text.push_str(&format!(
|
||
" wire [WIDTH-1:0] {name}_w{n};\n \
|
||
assign {name}_w{n} = {name}_data_i ^ {{WIDTH{{rst_ni}}}};\n \
|
||
reg [WIDTH-1:0] {name}_r{n};\n \
|
||
always_ff @(posedge clk_i) {name}_r{n} <= {name}_w{n};\n"
|
||
));
|
||
}
|
||
text.push_str(&format!(" assign {name}_data_o = {name}_data_i;\nendmodule\n"));
|
||
text
|
||
}
|
||
|
||
/// The buffer a completion is asked for in: a module body with `prefix` typed
|
||
/// on a fresh item line, and the same prefix inside an expression.
|
||
fn completion_buffer(prefix: &str, at_item: bool) -> (String, u32) {
|
||
let text = match at_item {
|
||
true => format!("module bench_top;\n {prefix}\nendmodule\n"),
|
||
false => format!("module bench_top;\n logic x;\n assign x = {prefix}\nendmodule\n"),
|
||
};
|
||
let cursor = text.find("\nendmodule").expect("the last line") as u32;
|
||
(text, cursor)
|
||
}
|
||
|
||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server perf::completing_over_a_real -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||
fn completing_over_a_real_project() {
|
||
// The same measurement as `completing_one_keystroke_at_a_time`, over
|
||
// whatever tree `LUCISV_PERF_CORPUS` names, with tier 0's bill broken out
|
||
// over the modules that tree really declares. A generated corpus has
|
||
// uniform files; a real one has a hundred-line header on one module and a
|
||
// two-thousand-line body on the next, and the difference between the two
|
||
// is worth being able to see. **Skipped when the variable is unset**, so
|
||
// this crate's tests never depend on a checkout nobody promised.
|
||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||
return;
|
||
};
|
||
let root = PathBuf::from(root);
|
||
let mut ws = Workspace::default();
|
||
ws.set_client_settings(crate::settings::ClientSettings {
|
||
index_scope: crate::settings::IndexScope::Workspace,
|
||
..Default::default()
|
||
});
|
||
let started = Instant::now();
|
||
ws.open_whole_workspace(vec![root.clone()]);
|
||
let scan = started.elapsed();
|
||
let buffer = root.join("lucisv_perf_buffer.sv");
|
||
let uri = path_to_uri(&buffer).expect("uri");
|
||
eprintln!(
|
||
"completion over {} indexed files of {} (scan {scan:?}), {} index names, {} words:",
|
||
ws.index().files().len(),
|
||
root.display(),
|
||
ws.candidates().units("").len(),
|
||
ws.candidates().words("").len()
|
||
);
|
||
|
||
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_reg", "zzzz"] {
|
||
let (text, cursor) = completion_buffer(prefix, true);
|
||
ws.set_document(uri.clone(), text.clone());
|
||
let position = {
|
||
let doc = ws.document(&uri).expect("open");
|
||
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
|
||
};
|
||
let items = match crate::completion::completions(&ws, &uri, position, true) {
|
||
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
|
||
_ => 0,
|
||
};
|
||
let took = mean(5, || {
|
||
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
|
||
});
|
||
|
||
// Tier 0's bill over this prefix's own candidates, stage by stage, so
|
||
// a slow row can be read rather than guessed at.
|
||
let names: Vec<String> =
|
||
ws.candidates().modules(prefix).iter().take(64).map(|n| n.to_string()).collect();
|
||
let (mut read, mut slice, mut plan) = (0u128, 0u128, 0u128);
|
||
let mut whole_files: Vec<&str> = Vec::new();
|
||
let mut bytes = 0usize;
|
||
for name in &names {
|
||
let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||
let started = Instant::now();
|
||
let Some(text) = ws.text_of(path) else { continue };
|
||
read += started.elapsed().as_nanos();
|
||
bytes += text.len();
|
||
let started = Instant::now();
|
||
let header = crate::completion::module_header(ws.index(), name, &text);
|
||
slice += started.elapsed().as_nanos();
|
||
let source = match header.as_deref() {
|
||
Some(head) => head,
|
||
None => {
|
||
whole_files.push(name);
|
||
&text
|
||
}
|
||
};
|
||
let started = Instant::now();
|
||
black_box(vlog_refactor::instantiation_plan(name, source, None).ok());
|
||
plan += started.elapsed().as_nanos();
|
||
}
|
||
let each = names.len().max(1) as u128;
|
||
eprintln!(
|
||
" prefix {prefix:>9?}: {took:?} ({items} items); tier 0 over {} modules \
|
||
({} KB read, parsed whole: {whole_files:?}): read {:?}, slice {:?}, plan {:?} each",
|
||
names.len(),
|
||
bytes / 1000,
|
||
Duration::from_nanos((read / each) as u64),
|
||
Duration::from_nanos((slice / each) as u64),
|
||
Duration::from_nanos((plan / each) as u64),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::completing_one -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn completing_one_keystroke_at_a_time() {
|
||
// `performance.md` §6d: completion cost tracks the *candidate* count before
|
||
// the 512-item cap, so it is worst at the empty prefix — exactly where
|
||
// every identifier starts. Two columns over the same workspace and the same
|
||
// prefixes: the cursor at module-item position, where every tier runs, and
|
||
// the cursor inside an expression, where the module-skeleton tier is gated
|
||
// off. The difference between them is what tier 0 costs.
|
||
let (files, body) = (4_000, 1_200);
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_completion_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||
completion_corpus(&dir, files, body);
|
||
std::fs::write(dir.join("bench_top.sv"), "module bench_top;\nendmodule\n").expect("write");
|
||
|
||
let mut ws = Workspace::default();
|
||
ws.set_client_settings(crate::settings::ClientSettings {
|
||
index_scope: crate::settings::IndexScope::Workspace,
|
||
..Default::default()
|
||
});
|
||
let started = Instant::now();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let scan = started.elapsed();
|
||
let uri = path_to_uri(&dir.join("bench_top.sv")).expect("uri");
|
||
|
||
eprintln!(
|
||
"completion over {} indexed files (scan {scan:?}), \
|
||
{} index names, {} project words:",
|
||
ws.index().files().len(),
|
||
ws.candidates().units("").len(),
|
||
ws.candidates().words("").len()
|
||
);
|
||
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_0001", "zzzz"] {
|
||
let mut row = String::new();
|
||
for at_item in [true, false] {
|
||
let (text, cursor) = completion_buffer(prefix, at_item);
|
||
ws.set_document(uri.clone(), text.clone());
|
||
let position = {
|
||
let doc = ws.document(&uri).expect("open");
|
||
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
|
||
};
|
||
let items = match crate::completion::completions(&ws, &uri, position, true) {
|
||
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
|
||
_ => 0,
|
||
};
|
||
let took = mean(5, || {
|
||
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
|
||
});
|
||
let where_ = if at_item { "item" } else { "expr" };
|
||
row.push_str(&format!(" {where_} {took:?} ({items} items);"));
|
||
}
|
||
eprintln!(" prefix {prefix:>9?}:{row}");
|
||
}
|
||
|
||
// Tier 0's per-item bill, so the row above can be divided by 64.
|
||
let module = "aes_0000";
|
||
let path = dir.join(format!("{module}.sv"));
|
||
let text = ws.text_of(&path).expect("readable");
|
||
let read = mean(50, || {
|
||
black_box(ws.text_of(black_box(&path)));
|
||
});
|
||
let whole = mean(50, || {
|
||
black_box(
|
||
vlog_refactor::instantiation_plan(black_box(module), black_box(&text), None).ok(),
|
||
);
|
||
});
|
||
let header = crate::completion::module_header(ws.index(), module, &text).expect("a header");
|
||
let sliced = mean(50, || {
|
||
black_box(
|
||
vlog_refactor::instantiation_plan(black_box(module), black_box(&header), None).ok(),
|
||
);
|
||
});
|
||
let slicing = mean(50, || {
|
||
black_box(crate::completion::module_header(
|
||
ws.index(),
|
||
black_box(module),
|
||
black_box(&text),
|
||
));
|
||
});
|
||
eprintln!(
|
||
" one skeleton off a {}-line file: text_of {read:?}, \
|
||
instantiation_plan over the whole file {whole:?}, \
|
||
over its header alone {sliced:?} (slicing it: {slicing:?})",
|
||
text.lines().count()
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::what_the_scope_depth -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn what_the_scope_depth_default_costs() {
|
||
// What moving the shipped `lucisv.index.scopeDepth` from 0 to 2 buys and
|
||
// what it costs, on an opentitan-shaped tree this repository generates for
|
||
// itself: blocks of `rtl/` and `dv/tb/`, with the opened buffer three
|
||
// levels down — the layout `performance.md` §4 measured one indexed file
|
||
// in. Every rung of the ladder over the same tree, so the columns are
|
||
// comparable.
|
||
let (blocks, per_folder, lines) = (12, 20, 200);
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_depth_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
for block in 0..blocks {
|
||
for (folder, count) in [("rtl", per_folder), ("dv/tb", 1)] {
|
||
let path = dir.join(format!("hw/ip/blk{block:02}/{folder}"));
|
||
std::fs::create_dir_all(&path).expect("folder");
|
||
for file in 0..count {
|
||
let name = format!("b{block:02}_{}_{file:02}", folder.replace('/', "_"));
|
||
std::fs::write(path.join(format!("{name}.sv")), generated_module(&name, lines))
|
||
.expect("write");
|
||
}
|
||
}
|
||
}
|
||
let opened = dir.join("hw/ip/blk00/dv/tb/b00_dv_tb_00.sv");
|
||
let uri = path_to_uri(&opened).expect("uri");
|
||
let text = std::fs::read_to_string(&opened).expect("read");
|
||
|
||
eprintln!(
|
||
"scopeDepth over {blocks} blocks of {} files ({per_folder} rtl + 1 dv/tb each), \
|
||
buffer opened at hw/ip/blk00/dv/tb:",
|
||
per_folder + 1
|
||
);
|
||
for depth in [0u64, 1, 2, 3] {
|
||
let mut ws = Workspace::default();
|
||
ws.set_client_settings(crate::settings::ClientSettings {
|
||
index_scope_depth: depth,
|
||
..Default::default()
|
||
});
|
||
ws.adopt_roots(vec![dir.clone()]);
|
||
ws.set_document(uri.clone(), text.clone());
|
||
let started = Instant::now();
|
||
black_box(ws.rebuild_index());
|
||
let scan = started.elapsed();
|
||
eprintln!(
|
||
" depth {depth}: {} files indexed, {} index names, scan {scan:?}",
|
||
ws.index().files().len(),
|
||
ws.candidates().units("").len()
|
||
);
|
||
}
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::a_code_action -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn a_code_action_at_an_instantiation_before_and_after() {
|
||
// The owner's instrumented session, on a workspace this repository
|
||
// generates for itself: `textDocument/codeAction` answered in 3.1 s
|
||
// against 0.01–0.44 ms for every other request. VS Code sends one on
|
||
// nearly every cursor move, the server is single-threaded, so a cursor
|
||
// resting on an instantiation — where F12 leaves it — held up every
|
||
// definition and hover behind it.
|
||
//
|
||
// Three numbers over the same workspace and the same cursor:
|
||
//
|
||
// * **before** — the whole-workspace answer: `sources()` plus the engine
|
||
// over every file, which is what the handler did until 2026-08-28;
|
||
// * **after** — the same answer from the module's own fan-out;
|
||
// * **`sources()` alone** — the workspace read on its own, which is the
|
||
// floor the before column cannot go under, and the cost `rename` and
|
||
// `prepare_rename` still pay (the follow-up recorded in
|
||
// `docs/features/refactor-ports/README.md`).
|
||
let (files, lines) = (500, 200);
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_action_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||
std::fs::write(dir.join("sub.sv"), sub).expect("write");
|
||
// Three files instantiate `sub`; the rest have nothing to do with it.
|
||
for n in 0..3 {
|
||
std::fs::write(
|
||
dir.join(format!("top{n}.sv")),
|
||
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
|
||
)
|
||
.expect("write");
|
||
}
|
||
for n in 0..files {
|
||
std::fs::write(
|
||
dir.join(format!("f{n:04}.sv")),
|
||
generated_module(&format!("f{n:04}"), lines),
|
||
)
|
||
.expect("write");
|
||
}
|
||
|
||
let mut ws = Workspace::default();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let path = dir.join("sub.sv");
|
||
let uri = path_to_uri(&path).expect("uri");
|
||
ws.set_document(uri.clone(), sub.to_string());
|
||
let offset = sub.find("input logic rst").expect("a port") as u32 + 12;
|
||
|
||
let before = mean(3, || {
|
||
let sources = ws.sources();
|
||
black_box(vlog_refactor::port_actions(&sources, black_box(&path), black_box(offset)));
|
||
});
|
||
let after = mean(20, || {
|
||
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
|
||
});
|
||
// TODO §37.1's column: the *offer* a client that can resolve receives,
|
||
// which reads the buffer and — at an instantiation — one more file,
|
||
// whatever the fan-out is. The edit is computed by `resolve`, which is the
|
||
// `after` column above, once, when the user clicks.
|
||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||
let offer = mean(20, || {
|
||
black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset)));
|
||
});
|
||
let read = mean(3, || {
|
||
black_box(ws.sources());
|
||
});
|
||
// What `textDocument/prepareRename` cost on the same workspace when this
|
||
// probe was written — the number the follow-up in the feature README was
|
||
// filed with, and the one `a_rename_before_and_after` below now closes.
|
||
let prepare = mean(3, || {
|
||
let sources = ws.sources();
|
||
let _ =
|
||
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
|
||
});
|
||
// A measurement of an answer that was not given is worthless.
|
||
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
|
||
assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1);
|
||
eprintln!(
|
||
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
|
||
whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \
|
||
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
|
||
ws.index().files().len()
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// A workspace of `files` unrelated generated modules plus a `sub` module
|
||
/// instantiated by three tops — the shape both rename probes measure over.
|
||
/// Returns the directory, so the caller removes it.
|
||
fn rename_corpus(tag: &str, files: usize, lines: usize) -> (PathBuf, &'static str) {
|
||
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||
std::fs::write(dir.join("sub.sv"), sub).expect("write");
|
||
for n in 0..3 {
|
||
std::fs::write(
|
||
dir.join(format!("top{n}.sv")),
|
||
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
|
||
)
|
||
.expect("write");
|
||
}
|
||
for n in 0..files {
|
||
std::fs::write(
|
||
dir.join(format!("f{n:04}.sv")),
|
||
generated_module(&format!("f{n:04}"), lines),
|
||
)
|
||
.expect("write");
|
||
}
|
||
(dir, sub)
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::a_rename -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn a_rename_before_and_after() {
|
||
// The owner's OpenTitan session: `prepareRename` 2.5–3.0 s and `rename`
|
||
// 3.6–8.7 s, both of them `ws.sources()` followed by an index build and an
|
||
// analysis over every in-scope file. `prepareRename` is what the rename
|
||
// key sends *before the box opens*, so those seconds are a frozen editor
|
||
// on a keypress that has committed to nothing.
|
||
//
|
||
// Four numbers over one workspace and one cursor:
|
||
//
|
||
// * **prepare, before** — `prepare_rename` over `sources()`;
|
||
// * **prepare, after** — the buffer's own analysis and the index, reading
|
||
// nothing;
|
||
// * **rename, before** — `rename` over `sources()`;
|
||
// * **rename, after** — `rename` over the symbol's fan-out.
|
||
let (files, lines) = (500, 200);
|
||
let (dir, sub) = rename_corpus("rename", files, lines);
|
||
|
||
let mut ws = Workspace::default();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let path = dir.join("sub.sv");
|
||
let uri = path_to_uri(&path).expect("uri");
|
||
ws.set_document(uri.clone(), sub.to_string());
|
||
// The module's own name, which fans out to the three files naming it.
|
||
let offset = sub.find("sub (").expect("the module name") as u32;
|
||
|
||
let prepare_before = mean(3, || {
|
||
let sources = ws.sources();
|
||
let _ =
|
||
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
|
||
});
|
||
let prepare_after = mean(2_000, || {
|
||
let _ = black_box(crate::rename::prepare(&ws, &uri, black_box(offset)));
|
||
});
|
||
let rename_before = mean(3, || {
|
||
let sources = ws.sources();
|
||
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
|
||
});
|
||
let rename_after = mean(20, || {
|
||
let _ = black_box(crate::rename::rename_traced(
|
||
&ws,
|
||
&uri,
|
||
black_box(offset),
|
||
"renamed",
|
||
&mut None,
|
||
));
|
||
});
|
||
let fan_out = ws.rename_sources_traced(&path, "sub", Some("renamed")).0.len();
|
||
// Building the file set at all, and the one rung of it that is a linear
|
||
// walk over every file's records rather than a keyed lookup
|
||
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
|
||
// `docs/features/refactor-rename/README.md`). Measured on its own because
|
||
// it is the only part of the set builder whose cost grows with the
|
||
// workspace rather than with the symbol.
|
||
let file_set = mean(2_000, || {
|
||
black_box(ws.rename_sources_traced(black_box(&path), "sub", Some("renamed")));
|
||
});
|
||
let spelling_rung = mean(2_000, || {
|
||
black_box(ws.index().files_spelling(black_box("renamed")).count());
|
||
});
|
||
|
||
// A measurement of an answer that was not given is worthless.
|
||
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
|
||
let (edit, _) =
|
||
crate::rename::rename_traced(&ws, &uri, offset, "renamed", &mut None).expect("renames");
|
||
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
|
||
|
||
eprintln!(
|
||
"rename of `sub`, instantiated in 3 of {} files ({lines} lines each), fan-out {fan_out} files:\n \
|
||
prepareRename: whole workspace {prepare_before:?} -> buffer+index {prepare_after:?}\n \
|
||
rename: whole workspace {rename_before:?} -> fan-out {rename_after:?}\n \
|
||
building the file set: {file_set:?}, of which `files_spelling`: {spelling_rung:?}",
|
||
ws.index().files().len()
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
/// `cargo test --release -p lucisv_server perf::a_will_rename -- --ignored --nocapture --test-threads=1`
|
||
#[test]
|
||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||
fn a_will_rename_before_and_after() {
|
||
// `workspace/willRenameFiles` read every in-scope file to ask each one
|
||
// "do you write an `include?" — a question the include graph already
|
||
// holds the answer to. Renaming any folder in the VS Code explorer sent
|
||
// it, so it is the same `sources()` shape as the two above.
|
||
let (files, lines) = (500, 200);
|
||
let (dir, _) = rename_corpus("willrename", files, lines);
|
||
std::fs::write(dir.join("defs.svh"), "`define W 8\n").expect("write");
|
||
std::fs::write(dir.join("includer.sv"), "`include \"defs.svh\"\nmodule includer;\nendmodule\n")
|
||
.expect("write");
|
||
|
||
let mut ws = Workspace::default();
|
||
ws.open_whole_workspace(vec![dir.clone()]);
|
||
let uri_of = |path: &std::path::Path| path_to_uri(path).expect("uri").as_str().to_string();
|
||
let renamed = vec![lsp_types::FileRename {
|
||
old_uri: uri_of(&dir.join("defs.svh")),
|
||
new_uri: uri_of(&dir.join("widths.svh")),
|
||
}];
|
||
|
||
let read_all = mean(3, || {
|
||
black_box(ws.sources());
|
||
});
|
||
let read_includers = mean(200, || {
|
||
black_box(ws.include_sources());
|
||
});
|
||
let after = mean(20, || {
|
||
black_box(crate::file_ops::will_rename(&ws, black_box(&renamed)));
|
||
});
|
||
let rewrite = crate::file_ops::will_rename(&ws, &renamed);
|
||
assert_eq!(
|
||
rewrite.edit.and_then(|edit| edit.changes.map(|c| c.len())),
|
||
Some(1),
|
||
"the one includer"
|
||
);
|
||
eprintln!(
|
||
"willRenameFiles over {} files, 1 of which includes anything:\n \
|
||
reading the scope {read_all:?} -> reading the includers {read_includers:?}\n \
|
||
whole answer, after: {after:?}",
|
||
ws.index().files().len()
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|