diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 13cb59a..41c7767 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -29,6 +29,8 @@ mod locate; mod nav; mod on_type; mod pairs; +#[cfg(test)] +mod perf; mod ports; mod rename; mod selection; diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs new file mode 100644 index 0000000..784202f --- /dev/null +++ b/crates/lucisv_server/src/perf.rs @@ -0,0 +1,338 @@ +//! 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. +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 and + // its snippet both come out of one read (`hover::disk_view`). The second + // read that memo removed is measured beside it — it is the whole file + // again, plus a whole `LineIndex` again. + 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 is what the memo saves)" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// `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::>(), + ); + 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::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() + ); + } +}