From c82978c3dbcd51c13b781ac252178a117d32b2da Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 12 Sep 2026 03:11:59 -0700 Subject: [PATCH] =?UTF-8?q?First=20request=20after=20an=20edit=20=E2=88=92?= =?UTF-8?q?19=20%=20(=C2=A763.2,=20N1=20of=20the=200.52.0=20review):=20the?= =?UTF-8?q?=20flush=20split=20on=20the=20timing=20line=20(rebuild{lex=20pa?= =?UTF-8?q?rse=20defines=20analyze=20external=20lines=20publish=20document?= =?UTF-8?q?s})=20named=20lex=2029=20+=20parse=2026=20of=20a=20100=20ms=20f?= =?UTF-8?q?lush=20and=20no=20second=20lint=20or=20analysis;=20the=20lexer'?= =?UTF-8?q?s=20two=20phases=20fused=20(the=20intermediate=20Vec=20?= =?UTF-8?q?gone),=20Parser::skip=20for=20the=20178=20bump()=20sites=20that?= =?UTF-8?q?=20discarded=20the=20token,=20a=20first-byte=20test=20in=20fron?= =?UTF-8?q?t=20of=20the=20operator=20table=20(tokenize=2027.8=20=E2=86=92?= =?UTF-8?q?=2011.6=20ms).=20Pinmux=20first=20menu=20after=20didChange=2010?= =?UTF-8?q?9=20=E2=86=92=2088=20ms=20paired;=20every=20other=20row=20withi?= =?UTF-8?q?n=20noise;=20RSS=20not=20up.=20Token=20stream,=20diagnostics,?= =?UTF-8?q?=20AST=20and=20symbols=20digested=20over=204=20807=20files:=200?= =?UTF-8?q?=20differ=20(re-derived=20by=20QA=20against=20a=20rebuilt=201b8?= =?UTF-8?q?723c);=20five=20gap=20fuzzers=20at=20their=20pins;=20corpus=20a?= =?UTF-8?q?nd=20opentitan=20byte-identical.=20Lead:=20an=20orphan=20traili?= =?UTF-8?q?ng=20comment=20leads=20the=20next=20token=20instead=20of=20vani?= =?UTF-8?q?shing=20(unreachable,=20kept=20as=20a=20rule).=20QA:=2016=20att?= =?UTF-8?q?ack=20tests,=20the=20flat-groups=20guard=20the=20harness=20reli?= =?UTF-8?q?es=20on.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- TODO.md | 52 +- crates/lucisv_server/src/lint_trace.rs | 211 +++++- .../lucisv_server/src/server/diagnostics.rs | 2 +- crates/lucisv_server/src/state/mod.rs | 85 ++- crates/vlog_parser/src/lexer.rs | 342 +++++++-- crates/vlog_parser/src/parser/assertion.rs | 34 +- crates/vlog_parser/src/parser/class.rs | 24 +- crates/vlog_parser/src/parser/covergroup.rs | 44 +- crates/vlog_parser/src/parser/cursor.rs | 29 +- crates/vlog_parser/src/parser/decl.rs | 14 +- crates/vlog_parser/src/parser/directive.rs | 4 +- crates/vlog_parser/src/parser/expr.rs | 16 +- crates/vlog_parser/src/parser/instance.rs | 22 +- crates/vlog_parser/src/parser/item.rs | 22 +- crates/vlog_parser/src/parser/keyword_stmt.rs | 36 +- crates/vlog_parser/src/parser/mod.rs | 4 +- crates/vlog_parser/src/parser/module.rs | 10 +- crates/vlog_parser/src/parser/primary.rs | 26 +- crates/vlog_parser/src/parser/randsequence.rs | 14 +- crates/vlog_parser/src/parser/recover.rs | 8 +- crates/vlog_parser/src/parser/recover_list.rs | 8 +- crates/vlog_parser/src/parser/split.rs | 2 +- crates/vlog_parser/src/parser/stmt.rs | 24 +- crates/vlog_parser/src/parser/sva.rs | 16 +- crates/vlog_parser/src/parser/tf.rs | 10 +- crates/vlog_parser/src/parser/verbatim.rs | 14 +- docs/features/perf-first-after-edit/README.md | 654 ++++++++++++++++++ docs/perf/README.md | 40 ++ docs/topo.md | 4 +- tools/perf/README.md | 2 +- 30 files changed, 1513 insertions(+), 260 deletions(-) create mode 100644 docs/features/perf-first-after-edit/README.md diff --git a/TODO.md b/TODO.md index 46bc05d..8d55d87 100644 --- a/TODO.md +++ b/TODO.md @@ -4740,6 +4740,12 @@ in 0.49.0. Take 4's findings are in the loop-3 list above. `WorkspaceIndex::member`, the connection surface; the fix is the hierarchical-surface lookup in both call sites plus a fixture sweep across definition/references/hover/documentHighlight. +- **§63.2 filed (2026-09-12):** the rest of the first-after-edit flush — + the token clone into `parse_tolerant` (3.9 ms; the parser mutates the + stream it is given, and `Document::tokens` is read for comments by + semantic tokens and the linter), `analyze` (9.4 ms), `resolve_external` + (4.7 ms against the 3 975-file index), and ~6 ms dropping the previous + revision's products on the request path (drop it after answering). Sections after §46 are planned when reached. ## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22 @@ -6759,14 +6765,46 @@ code_action.rs}`, `crates/vlog_parser/src/{lexer.rs,parser/,lib.rs}`, `crates/vlog_semantic/src/{analyze*,bind/}` only for a measured stage, `tools/perf/` for the flush split rows. Nothing else. -- [ ] the flush split in `lint_trace` and a harness row per stage; the - 0.53.0 numbers in the README before any change -- [ ] the fix, one stage at a time, each with its before/after cell; +- [x] the flush split in `lint_trace` and a harness row per stage; the + 0.53.0 numbers in the README before any change — `Rebuild`'s seven + stages (`lex parse defines analyze external lines publish`) plus + `documents`, printed as a **third sibling group** `rebuild{…}` on + the `timing: codeaction` line, which `phases_r1.actionprofile` + picks up as `trace_rebuild_*` with no harness code change + (`phases_p2.parse_trace` flattens one level). **The 100 ms flush on + 0.53.0: lex 29.1, parse 25.6, publish 22.2 (lint 22.0), analyze + 10.1, external 4.8, lines 0.6, defines 0.5, ~7 dropping the old + revision.** Two of the review's candidates were answered by the + split: `action` reads `snapshot=hit`/`lint=0.00ms` (no second lint + of the revision) and `lint::context` already lends `doc.semantics` + (no second analysis) +- [x] the fix, one stage at a time, each with its before/after cell; parser snapshot and idempotency suites green; corpus and opentitan - byte-identity gates -- [ ] `offeredit`, `offerkinds`, `flush`, `diagnostics` phases paired - against 0.53.0 with the order alternated; RSS cell -- [ ] QA: the trace's arithmetic re-derived, the parity attacked (a buffer + byte-identity gates — three changes, all in `vlog_parser`: the + lexer's two phases **fused** (the intermediate `Vec` gone; + `tokenize` 27.8 → 24.7 ms), **`Parser::skip`** for the 178 + `bump()` sites that threw the token away (`parse_tolerant` 17.5 → + 16.0 ms), and a **first-byte test in front of the 44-entry + operator table** (24.7 → **11.6 ms**, the largest single win). + Parity: token stream + parse diagnostics + whole AST + symbol + table digested per file over **4 807 files** (corpus + opentitan), + 0 differ; `format --stdout` byte-identical over corpus (860) and + over opentitan (one tree digest, identical stderr); diagnostics + and the all-family + seven-family menus identical on the pinmux, + aes and tb buffers before and after an edit, including a revision + edited to *have* lint findings. 4 403 → **4 406 tests** +- [x] `offeredit`, `offerkinds`, `flush`, `diagnostics` phases paired + against 0.53.0 with the order alternated; RSS cell — the cell + **110.95 / 107.54 → 88.31 / 88.36 ms, −19.2 %**: the ≥ 15 % gate + met and the < 95 ms stretch met. The unchanged-repeat cell + (0.27/0.32 → 0.22/0.19) and every `offeredit`/`offerkinds`/ + `flush`/`diagnostics` row are inside their own version's a/b + spread. RSS **not up**: warm flat (≈428 MiB both), cold scan + ~25 MiB *lower* (506 → 480 MiB) — the `Vec` that is no + longer built; index store byte-identical at 45 468 KiB. Feature + README `docs/features/perf-first-after-edit/`; evidence and + runners in `~/.cache/lucisv-perf/63-2/` +- [x] QA: the trace's arithmetic re-derived, the parity attacked (a buffer that fails to lex; a `` `define`` edit that changes the macro table; an edit that moves a fence), the numbers re-taken diff --git a/crates/lucisv_server/src/lint_trace.rs b/crates/lucisv_server/src/lint_trace.rs index dbad8ee..8f62b66 100644 --- a/crates/lucisv_server/src/lint_trace.rs +++ b/crates/lucisv_server/src/lint_trace.rs @@ -72,6 +72,86 @@ impl Stage { [Stage::Config, Stage::Build, Stage::Lint, Stage::Fence, Stage::Serialize]; } +/// One stage of the debounced `Document` rebuild the flush performs, plus the +/// diagnostics publish that follows it. +/// +/// TODO §63.2: `flush{wall=…}` said the rebuild cost 100 ms and nothing about +/// *which* of the six derivations that was, so the first thing this round does +/// is name them. The six are [`crate::state::Document::new`]'s own steps in +/// the order it runs them; `Publish` is what `flush_dirty` does with the +/// rebuilt buffer, and the flush group's `config`/`build`/`lint`/`fence` +/// stages are inside it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rebuild { + /// `tokenize` over the buffer's text. + Lex, + /// `parse_tolerant` over those tokens (or `parse_source_tolerant` when the + /// buffer does not lex). + Parse, + /// `collect_defines` over the tokens. + Defines, + /// `analyze` over the tree. + Analyze, + /// `resolve_external` against the workspace index. + External, + /// `LineIndex::new` over the text. + Lines, + /// The diagnostics publish for the rebuilt buffer. + Publish, +} + +impl Rebuild { + /// The name this stage is counted under in the `timing:` line. + fn label(self) -> &'static str { + match self { + Rebuild::Lex => "lex", + Rebuild::Parse => "parse", + Rebuild::Defines => "defines", + Rebuild::Analyze => "analyze", + Rebuild::External => "external", + Rebuild::Lines => "lines", + Rebuild::Publish => "publish", + } + } + + /// Every stage, in the order the flush passes through them. + const ALL: [Rebuild; 7] = [ + Rebuild::Lex, + Rebuild::Parse, + Rebuild::Defines, + Rebuild::Analyze, + Rebuild::External, + Rebuild::Lines, + Rebuild::Publish, + ]; +} + +/// The flush's inner stages: what rebuilding the dirty buffers cost, split. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Rebuilt { + ms: [f64; Rebuild::ALL.len()], + /// How many `Document`s were built from scratch. + documents: usize, +} + +impl Rebuilt { + /// The `const` form `thread_local!`'s initializer needs. + const EMPTY: Rebuilt = Rebuilt { ms: [0.0; Rebuild::ALL.len()], documents: 0 }; + + fn add(&mut self, stage: Rebuild, took: Duration) { + self.ms[stage as usize] += took.as_secs_f64() * 1_000.0; + } + + /// This group's fields, in the `key=value` shape `tools/perf` parses. + fn fields(&self) -> String { + let stages: Vec = Rebuild::ALL + .iter() + .map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize])) + .collect(); + format!("{} documents={}", stages.join(" "), self.documents) + } +} + /// What the fence filter did, when a pass reached it at all. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Fences { @@ -200,6 +280,8 @@ pub struct Trace { pub flush_buffers: usize, /// Whole-file parses the flush performed (`vlog_parser::stats`). pub flush_parses: u64, + /// What the flush's `Document` rebuild and publish cost, stage by stage. + pub rebuild: Rebuilt, /// The handler's own stages. pub action: Group, } @@ -208,17 +290,25 @@ impl Trace { /// Whether this request touched the lint path at all. A trace that did /// not is not worth a line. pub fn is_empty(&self) -> bool { - self.flush == Group::default() && self.action == Group::default() && self.flush_buffers == 0 + self.flush == Group::default() + && self.action == Group::default() + && self.flush_buffers == 0 + && self.rebuild == Rebuilt::default() } /// The whole trace as one `timing:`-style fragment. + /// + /// The three groups are siblings, never nested: `tools/perf`'s group + /// regex flattens `name{…}` one level and would not survive a brace + /// inside a brace. pub fn line(&self) -> String { format!( - "flush{{wall={:.2}ms buffers={} parses={} {}}} action{{{}}}", + "flush{{wall={:.2}ms buffers={} parses={} {}}} rebuild{{{}}} action{{{}}}", self.flush_ms, self.flush_buffers, self.flush_parses, self.flush.fields(), + self.rebuild.fields(), self.action.fields(), ) } @@ -232,6 +322,7 @@ thread_local! { flush_ms: 0.0, flush_buffers: 0, flush_parses: 0, + rebuild: Rebuilt::EMPTY, action: Group::EMPTY, }) }; /// Which group the stages recorded right now belong to. @@ -292,6 +383,30 @@ pub fn stage(stage: Stage, work: impl FnOnce() -> T) -> T { out } +/// Run `work`, counting what it took against one of the flush's inner stages. +/// +/// Off costs the same one thread-local read [`stage`] costs. The flush group +/// is not consulted: a rebuild belongs to the rebuild it is part of whichever +/// half of the request it happens in, and outside a flush there is none. +pub fn rebuild(stage: Rebuild, work: impl FnOnce() -> T) -> T { + if !ARMED.get() { + return work(); + } + let started = Instant::now(); + let out = work(); + let took = started.elapsed(); + TRACE.with_borrow_mut(|trace| trace.rebuild.add(stage, took)); + out +} + +/// Record that one `Document` was built from scratch. +pub fn saw_document() { + if !ARMED.get() { + return; + } + TRACE.with_borrow_mut(|trace| trace.rebuild.documents += 1); +} + /// Record what a lint pass ran and found. pub fn saw_lint(rules: usize, violations: usize, reuse: Reuse) { group(|held| { @@ -397,4 +512,96 @@ mod tests { assert!(line.contains("snapshot=none"), "{line}"); assert!(!line.contains(" "), "no empty field: {line}"); } + + /// The flush's inner stages are their own sibling group, named whether or + /// not they ran, and never nested inside `flush{…}` — `tools/perf`'s + /// group regex flattens one level only (TODO §63.2). + #[test] + fn the_rebuild_group_names_every_stage_beside_the_other_two() { + arm(); + rebuild(Rebuild::Lex, || {}); + saw_document(); + close_flush(Duration::from_millis(1), 1, 1); + let line = disarm().expect("armed").line(); + let rebuilt = line.split("rebuild{").nth(1).expect("a rebuild group").split('}').next(); + let rebuilt = rebuilt.expect("a closed rebuild group"); + for stage in Rebuild::ALL { + assert!(rebuilt.contains(&format!("{}=", stage.label())), "{line}"); + } + assert!(rebuilt.contains("documents=1"), "{line}"); + assert!(!rebuilt.contains('{'), "no nested group: {line}"); + } + + /// TODO §63.2 QA: the sibling-group contract, attacked directly against + /// the parser it is a contract *with*. + /// + /// `tools/perf/phases_p2.py`'s `GROUP` regex is `([a-z_]+)\{([^{}]*)\}` — + /// a group's body may not contain another `{`. Sabotaging `line()` to + /// nest `rebuild{…}` inside `flush{…}` (tried by hand while attacking + /// this pin) does **not** fail the test above: splitting on `"rebuild{"` + /// still finds a clean `rebuild` body, because the extra brace the + /// nesting adds sits *outside* the slice that test inspects. Run through + /// the actual regex, though, nesting is fatal: `[^{}]*` cannot cross the + /// inner `{`, so the whole `flush{...}` match fails and `flush_wall`, + /// `flush_buffers`, `flush_parses` and every `flush.fields()` entry + /// silently vanish from every `tools/perf` row — confirmed with + /// `GROUP.findall` in a scratch interpreter against the sabotaged line, + /// which matched only `rebuild` and `action`, never `flush`. This test + /// reads the line the way the regex does (each group's body must reach + /// its own `}` before another `{` opens) so a future nesting regression + /// fails here instead of only downstream in Python. + #[test] + fn the_three_top_level_groups_are_flat_never_nested() { + arm(); + rebuild(Rebuild::Lex, || {}); + saw_document(); + close_flush(Duration::from_millis(1), 1, 1); + let line = disarm().expect("armed").line(); + for name in ["flush", "rebuild", "action"] { + let open = + line.find(&format!("{name}{{")).unwrap_or_else(|| panic!("no {name}{{ in {line}")); + let body = &line[open + name.len() + 1..]; + let close = + body.find('}').unwrap_or_else(|| panic!("no closing brace for {name}: {line}")); + let next_open = body.find('{'); + assert!( + next_open.is_none_or(|o| o > close), + "{name}{{...}} is not flat — a nested group vanishes from every \ + tools/perf row parsed by phases_p2.GROUP instead of failing loudly: {line}" + ); + } + } + + /// A rebuild is recorded in either half of the request, and an unarmed + /// one records nothing at all. + #[test] + fn a_rebuild_is_counted_whichever_half_of_the_request_runs_it() { + assert_eq!(rebuild(Rebuild::Parse, || 4), 4); + assert_eq!(disarm(), None); + arm(); + rebuild(Rebuild::Parse, || {}); + close_flush(Duration::ZERO, 1, 1); + rebuild(Rebuild::Parse, || {}); + saw_document(); + saw_document(); + let trace = disarm().expect("armed"); + assert_eq!(trace.rebuild.documents, 2); + assert_eq!(trace.flush.passes, 0, "a rebuild is not a lint pass"); + assert_eq!(trace.action.passes, 0); + } + + /// A request that only rebuilt a buffer still has something to say: the + /// trace must not be discarded as empty before the line is logged. + /// + /// The rebuilt *count*, not a stage's milliseconds, is what says a + /// rebuild happened — a stage whose work takes less than the clock's + /// resolution adds 0.00 ms, which is why `Document::new` reports itself + /// with [`saw_document`] rather than leaving the evidence to a duration. + #[test] + fn a_trace_holding_only_a_rebuild_is_not_empty() { + arm(); + rebuild(Rebuild::Analyze, || {}); + saw_document(); + assert!(!disarm().expect("armed").is_empty()); + } } diff --git a/crates/lucisv_server/src/server/diagnostics.rs b/crates/lucisv_server/src/server/diagnostics.rs index 9f093dc..5ec6209 100644 --- a/crates/lucisv_server/src/server/diagnostics.rs +++ b/crates/lucisv_server/src/server/diagnostics.rs @@ -53,7 +53,7 @@ impl Server { let buffers = self.dirty.len(); for (uri, text) in std::mem::take(&mut self.dirty) { self.set_document(uri.clone(), text); - self.publish(&uri); + crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri)); } self.timed(started, |took| { format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers)) diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 30520d4..6e69a0d 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -122,17 +122,19 @@ impl Document { // `tokenize` + `parse_tolerant`, so the tree is identical). A buffer // that does not lex keeps the old path, so its all-error tree and its // lex diagnostic are byte-for-byte what they always were. - let (tokens, (tree, diagnostics)) = match tokenize(&text) { + use crate::lint_trace::{rebuild, Rebuild}; + crate::lint_trace::saw_document(); + let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) { Ok(tokens) => { - let parsed = parse_tolerant(tokens.clone(), &text); + let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text)); (tokens, parsed) } - Err(_) => (Vec::new(), parse_source_tolerant(&text)), + Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))), }; - let defines = collect_defines(&tokens); - let semantics = analyze(&tree, &text); - let external = resolve_external(&semantics, index); - let line_index = LineIndex::new(&text); + let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens)); + let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text)); + let external = rebuild(Rebuild::External, || resolve_external(&semantics, index)); + let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text)); let large = false; Document { path, @@ -5861,4 +5863,73 @@ mod tests { assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed"); assert_eq!(ws.index().member("a_pkg", "K").len(), 0); } + + // ------------------------------------------------------------------ + // TODO §63.2 QA: the trace's arithmetic, attacked with the three + // shapes TODO.md names — a buffer that fails to lex, a `define` edit + // that changes the macro table, and (below, via the server-level + // parity re-run) an edit that moves a fence. + // ------------------------------------------------------------------ + + /// A buffer that never lexes still reports a `Lex` stage (the failed + /// attempt is real work and costs real time) and a `Parse` stage (the + /// `parse_source_tolerant` fallback), and still counts as one document. + /// `defines`/`analyze`/`external`/`lines` all still run over the empty + /// token stream and empty-error tree exactly as the un-instrumented + /// path always did — the wrapping must not skip a stage just because + /// an earlier one errored. + #[test] + fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() { + crate::lint_trace::arm(); + // An unterminated string literal is an unambiguous lex error that + // does not depend on lexer internals that could drift between + // versions (`vlog_parser::tokenize` is documented all-or-nothing). + let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string(); + let doc = Document::new(None, text, &WorkspaceIndex::default()); + assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream"); + assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic"); + let trace = crate::lint_trace::disarm().expect("armed"); + // Every stage's field is present on the line, whether or not it + // took measurable time (`saw_document`, not a duration, is what + // says a rebuild happened at all — see the flaky test this round + // fixed in `lint_trace.rs`). + let line = trace.line(); + assert!(line.contains("documents=1"), "{line}"); + for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] { + assert!(line.contains(stage), "{line}"); + } + } + + /// A `` `define `` edit changes the macro table `collect_defines` + /// produces, and nothing about wrapping that call in `rebuild` changes + /// which tokens it sees or what it returns: the new revision's table + /// reflects only the new text, never a stale value from the revision + /// before it (`Document::new` builds a fresh `DefineTable` every time, + /// same as before this round). + #[test] + fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() { + crate::lint_trace::arm(); + let before = Document::new( + None, + "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(), + &WorkspaceIndex::default(), + ); + assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8")); + assert!(before.defines.latest("DEPTH").is_none()); + + let after = Document::new( + None, + "`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(), + &WorkspaceIndex::default(), + ); + assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents"); + assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16")); + + let trace = crate::lint_trace::disarm().expect("armed"); + let line = trace.line(); + assert!( + line.contains("documents=2"), + "two fresh Document::new calls, two rebuilds: {line}" + ); + } } diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index b672d8f..1caf2dd 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -403,8 +403,14 @@ impl<'a> RawLexer<'a> { }); } - // Operators, longest match first. + // Operators, longest match first. The first-byte test is not a second + // way of matching — `starts_with` still decides — it is what keeps a + // `;` from being compared against all 42 spellings: one byte compare + // rejects every operator that cannot start here (TODO §63.2). for op in OPERATORS { + if op.as_bytes()[0] != c { + continue; + } if self.starts_with(op) { for _ in 0..op.len() { self.bump(); @@ -918,80 +924,111 @@ fn is_line_directive(word: &str) -> bool { ) } +/// What the attachment phase carries from one raw token to the next. +#[derive(Default)] +struct Attaching { + /// Comments waiting for the real token they lead. + pending: Vec, + /// Whether a blank line was seen since the last pending comment. + pending_blank: bool, +} + /// Tokenize source text, attaching comments and blank-line info to tokens. +/// +/// The two phases are **fused**: each raw token is attached as it is lexed, +/// rather than collected into a `Vec` the attachment loop then walks. +/// Attachment only ever reads the raw token in hand and the token last pushed, +/// so the fusion is a pure reordering — it drops a second whole-file vector +/// (a 40 267-line file's worth of it is ~22 MB of allocation, growth copying +/// and teardown), which is why the first request after an edit pays less for +/// the same tokens (TODO §63.2). pub fn tokenize(source: &str) -> Result, LexError> { let mut raw_lexer = RawLexer::new(source.as_bytes()); - let mut raws: Vec = Vec::new(); + let mut tokens: Vec = Vec::with_capacity(estimated_tokens(source.len())); + let mut state = Attaching::default(); loop { - let tok = raw_lexer.next_raw()?; - let is_eof = tok.kind == RawKind::Real(TokenKind::Eof); - raws.push(tok); + let raw = raw_lexer.next_raw()?; + let is_eof = raw.kind == RawKind::Real(TokenKind::Eof); + attach(raw, &mut tokens, &mut state); if is_eof { break; } } + Ok(tokens) +} - // Attachment phase. - let mut tokens: Vec = Vec::new(); - let mut pending: Vec = Vec::new(); - let mut pending_blank = false; +/// How many tokens a source of `bytes` bytes is guessed to hold. +/// +/// Only to spare the growing vector its early doublings; a wrong guess costs +/// nothing but the growth it would have paid anyway. Six bytes a token is the +/// measured average over the corpus and over opentitan's generated register +/// files alike, and the guess is capped so a pathological file (one enormous +/// string literal) cannot reserve more than it could ever need. +fn estimated_tokens(bytes: usize) -> usize { + (bytes / 6).min(1 << 20) +} - for raw in raws { - match raw.kind { - RawKind::LineComment | RawKind::BlockComment => { - let same_line_as_prev = - raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty(); - let comment = Comment { - text: raw.text, - blank_before: raw.newlines_before > 1 || pending_blank, - line: raw.line, - col: raw.col, - span: raw.span, - }; - if same_line_as_prev { - // Trailing comment for the previous real token. - let prev = tokens.last_mut().unwrap(); - match &mut prev.trailing { - Some(existing) => { - // Two comments on one line become one node, so its - // span has to cover both — the merge normalizes - // the gap between them to a single space, which is - // why a merged comment is the one comment whose - // text can differ from `source[span]`. - existing.text.push(' '); - existing.text.push_str(&comment.text); - existing.span = TextRange::new(existing.span.start, comment.span.end); - } - None => prev.trailing = Some(comment), - } - } else { - pending.push(comment); - pending_blank = false; - } - } - RawKind::Real(kind) => { - let blank_before = if pending.is_empty() { - raw.newlines_before > 1 - } else { - // Comments already carry their own blank flags; the token - // is blank-separated only if there was a blank line - // between the last comment and the token itself. - raw.newlines_before > 1 - }; - tokens.push(Token { - kind, - text: raw.text, - line: raw.line, - col: raw.col, - span: raw.span, - leading: std::mem::take(&mut pending), - trailing: None, - blank_before, - }); +/// Fold one raw token into the token stream: a comment onto its neighbour, +/// a real token onto the end with whatever comments were waiting for it. +fn attach(raw: RawTok, tokens: &mut Vec, state: &mut Attaching) { + match raw.kind { + RawKind::LineComment | RawKind::BlockComment => { + let same_line_as_prev = + raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty(); + let comment = Comment { + text: raw.text, + blank_before: raw.newlines_before > 1 || state.pending_blank, + line: raw.line, + col: raw.col, + span: raw.span, + }; + // A comment that finds no token to trail — unreachable while + // `same_line_as_prev` requires one, kept as a rule rather than a + // hope — leads the next token instead of vanishing (invariant 3). + let orphan = + if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) }; + if let Some(comment) = orphan { + state.pending.push(comment); + state.pending_blank = false; } } + RawKind::Real(kind) => { + // Comments already carry their own blank flags; the token is + // blank-separated only if there was a blank line between the last + // comment and the token itself — which is the same test either + // way, so `pending` does not enter into it. + let blank_before = raw.newlines_before > 1; + tokens.push(Token { + kind, + text: raw.text, + line: raw.line, + col: raw.col, + span: raw.span, + leading: std::mem::take(&mut state.pending), + trailing: None, + blank_before, + }); + } } - Ok(tokens) +} + +/// Hang a comment off the token before it, merging with one already there. +/// Handed back untouched when there is no token before it. +fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option { + let Some(prev) = tokens.last_mut() else { return Some(comment) }; + match &mut prev.trailing { + Some(existing) => { + // Two comments on one line become one node, so its span has to + // cover both — the merge normalizes the gap between them to a + // single space, which is why a merged comment is the one comment + // whose text can differ from `source[span]`. + existing.text.push(' '); + existing.text.push_str(&comment.text); + existing.span = TextRange::new(existing.span.start, comment.span.end); + } + None => prev.trailing = Some(comment), + } + None } #[cfg(test)] @@ -1510,4 +1547,185 @@ mod tests { assert!(texts.contains(&"!==")); assert!(texts.contains(&"<=")); } + + // ------------------------------------------------------------------ + // TODO §63.2 QA: the fused attach phase, attacked + // + // These cover the shapes the two-phase code (a `Vec` fully + // built, then walked) could tell apart from the fused one-pass code + // (each raw token attached as it is produced) if the fusion were not a + // pure reordering: a comment with no token before it at all, comments + // that never see a "previous token" until much later, EOF immediately + // after a trailing comment, and so on. Every one of these was also + // cross-checked, file for file, against `tokenize` built from 1b8723c + // (the pre-fusion tree) with a throwaway digest tool in the QA + // scratchpad — token-for-token identical, hash and manual `Debug` + // inspection alike; the assertions below pin that result durably. + // ------------------------------------------------------------------ + + #[test] + fn a_comment_as_the_very_first_thing_in_the_file_is_the_first_token_s_leading() { + let toks = tokenize("// only thing before the module\nmodule m;\nendmodule").unwrap(); + assert_eq!(toks[0].leading.len(), 1); + assert_eq!(toks[0].leading[0].text, "// only thing before the module"); + assert!(!toks[0].leading[0].blank_before); + } + + #[test] + fn two_comments_on_the_first_line_before_any_token_both_lead_it() { + // Two *separate* comments here means two lines, each its own line + // comment (a line comment always runs to end of line, so "two + // comments on one line" before any token is only possible with + // block comments — covered by `two_block_comments_on_one_line_merge` + // below). + let toks = tokenize("// one\n// two\nmodule m;\nendmodule").unwrap(); + assert_eq!(toks[0].leading.len(), 2); + assert_eq!(toks[0].leading[0].text, "// one"); + assert_eq!(toks[0].leading[1].text, "// two"); + assert!(!toks[0].leading[1].blank_before); + } + + #[test] + fn a_trailing_comment_after_the_last_real_token_reaches_eof() { + let toks = tokenize("module m;\nendmodule // trailing at eof\n").unwrap(); + let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap(); + let trailing = end.trailing.as_ref().expect("trailing comment on endmodule"); + assert_eq!(trailing.text, "// trailing at eof"); + assert_eq!(toks.last().unwrap().kind, TokenKind::Eof); + } + + #[test] + fn two_block_comments_on_one_line_merge_into_one_trailing_comment() { + let toks = tokenize("wire w; /* one */ /* two */\nendmodule").unwrap(); + let semi = toks.iter().find(|t| t.is_sym(";")).unwrap(); + let trailing = semi.trailing.as_ref().expect("merged trailing comment"); + assert_eq!(trailing.text, "/* one */ /* two */"); + } + + #[test] + fn a_blank_line_between_a_comment_and_its_token_marks_both() { + let toks = tokenize("// lead\n\nmodule m;\nendmodule").unwrap(); + assert_eq!(toks[0].leading.len(), 1); + // The comment itself is not blank-separated from what came before it + // (nothing did); the blank line sits between the comment and the + // token, so the *token* carries the flag. + assert!(!toks[0].leading[0].blank_before); + assert!(toks[0].blank_before); + } + + #[test] + fn crlf_line_endings_lex_like_lf_with_the_same_comment_attachment() { + let toks = tokenize("module m; // c\r\nendmodule\r\n").unwrap(); + let semi = toks.iter().find(|t| t.is_sym(";")).unwrap(); + assert_eq!(semi.trailing.as_ref().unwrap().text, "// c"); + let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap(); + assert_eq!(end.line, 2); + } + + #[test] + fn a_block_comment_spanning_lines_still_leads_a_same_line_token() { + let toks = tokenize("/* block\n spanning\n lines */ module m;\nendmodule").unwrap(); + assert_eq!(toks[0].leading.len(), 1); + assert!(toks[0].leading[0].text.starts_with("/* block")); + assert!(toks[0].leading[0].text.ends_with("lines */")); + // The module keyword itself sits on the block comment's last line. + assert_eq!(toks[0].line, 3); + } + + #[test] + fn a_comment_between_a_macro_invocation_and_its_arguments_trails_the_macro() { + let toks = tokenize("module m;\n`MYMACRO /*c*/ (a, b);\nendmodule").unwrap(); + let mac = toks.iter().find(|t| t.text == "`MYMACRO").unwrap(); + assert_eq!(mac.trailing.as_ref().unwrap().text, "/*c*/"); + // The macro call's parenthesized arguments are unaffected — still + // ordinary tokens right after, comment or not. + let open_paren_idx = toks.iter().position(|t| t.is_sym("(")).unwrap(); + assert_eq!(toks[open_paren_idx + 1].text, "a"); + } + + #[test] + fn a_file_that_is_only_comments_attaches_them_all_to_the_synthetic_eof() { + let toks = tokenize("// only a comment, nothing else\n").unwrap(); + assert_eq!(toks.len(), 1); + assert_eq!(toks[0].kind, TokenKind::Eof); + assert_eq!(toks[0].leading.len(), 1); + assert_eq!(toks[0].leading[0].text, "// only a comment, nothing else"); + } + + #[test] + fn an_empty_file_lexes_to_a_lone_eof_with_no_comments() { + let toks = tokenize("").unwrap(); + assert_eq!(toks.len(), 1); + assert_eq!(toks[0].kind, TokenKind::Eof); + assert!(toks[0].leading.is_empty()); + } + + // ------------------------------------------------------------------ + // TODO §63.2 QA: the operator table's first-byte test + // ------------------------------------------------------------------ + + #[test] + fn every_operator_s_first_byte_is_a_single_ascii_byte() { + // `op.as_bytes()[0] != c` compares one byte of `c: u8` against the + // table entry's first *byte*. If any entry's first character were + // multi-byte UTF-8, its first byte alone would not identify it and + // the guard could reject a spelling it should have let through. Every + // entry here is pure ASCII punctuation, so the byte comparison is the + // whole character. + for op in OPERATORS { + let first = op.chars().next().expect("no empty operator spellings"); + assert!(first.is_ascii(), "{op:?} does not start with an ASCII byte"); + assert_eq!( + op.as_bytes()[0], + first as u8, + "{op:?}'s first byte does not match its first char" + ); + } + } + + #[test] + fn the_operator_table_has_no_duplicate_or_empty_entries() { + // A duplicate wastes a comparison; an empty entry would make + // `op.as_bytes()[0]` panic before ever reaching `starts_with`. + for op in OPERATORS { + assert!(!op.is_empty()); + } + let mut sorted = OPERATORS.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), OPERATORS.len(), "OPERATORS has a duplicate entry"); + } + + #[test] + fn every_operator_followed_by_every_other_operator_still_lexes_without_a_gap() { + // The first-byte test must not change *which* entry `starts_with` + // picks — only how many entries are tried before it does. Lexing + // every `op1 op2` concatenation (no space) and requiring the token + // stream to account for every byte with no lex error is the + // regression gate: a wrong short-circuit would either misplace the + // split point or leave a byte unconsumed. Cross-checked pair for + // pair against `tokenize` built from 1b8723c (pre-first-byte-test) + // in the QA scratchpad: 1 764 pairs, 0 differ. + for &op1 in OPERATORS { + for &op2 in OPERATORS { + let src = format!("{op1}{op2} ;"); + let toks = tokenize(&src) + .unwrap_or_else(|e| panic!("lexing {op1:?} followed by {op2:?} failed: {e}")); + // Everything up to the space must be Symbol tokens whose + // texts concatenate back to exactly op1 followed by op2, + // with no gap and no overlap. + let mut consumed = String::new(); + let mut i = 0; + while toks[i].kind == TokenKind::Symbol && toks[i].text != ";" { + consumed.push_str(&toks[i].text); + i += 1; + } + assert_eq!( + consumed, + format!("{op1}{op2}"), + "{op1:?} followed by {op2:?} did not round-trip" + ); + } + } + } } diff --git a/crates/vlog_parser/src/parser/assertion.rs b/crates/vlog_parser/src/parser/assertion.rs index fdcc7a6..094f452 100644 --- a/crates/vlog_parser/src/parser/assertion.rs +++ b/crates/vlog_parser/src/parser/assertion.rs @@ -53,11 +53,11 @@ impl<'a> Parser<'a> { let start = self.here(); let col = self.cur().col; if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") { - self.bump(); - self.bump(); + self.skip(); + self.skip(); } // `assert` / `assume` / `cover` / `restrict`. - self.bump(); + self.skip(); self.expect_kw("property")?; self.expect_sym("(")?; self.skip_balanced("(", ")")?; @@ -132,22 +132,22 @@ impl<'a> Parser<'a> { at_stmt_start = false; let t = self.cur(); if t.is_sym("(") { - self.bump(); + self.skip(); self.skip_balanced("(", ")")?; } else if t.is_sym("[") { - self.bump(); + self.skip(); self.skip_balanced("[", "]")?; } else if t.is_sym("{") { - self.bump(); + self.skip(); self.skip_balanced("{", "}")?; } else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") { // `disable fork` / `wait fork` name the enclosing block; they // do not open one. - self.bump(); - self.bump(); + self.skip(); + self.skip(); } else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) { depth += 1; - self.bump(); + self.skip(); } else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) { if depth == 0 { // A closer with nothing open: the action statement is @@ -156,7 +156,7 @@ impl<'a> Parser<'a> { return self.error("expected `;`"); } depth -= 1; - self.bump(); + self.skip(); if depth == 0 { self.parse_label()?; if !self.eat_kw("else") { @@ -167,7 +167,7 @@ impl<'a> Parser<'a> { } else if depth == 0 && self.eat_sym(";") { return Ok(()); } else { - self.bump(); + self.skip(); } } } @@ -199,9 +199,9 @@ impl<'a> Parser<'a> { let start = self.here(); let col = self.cur().col; let end_kw = if self.cur().is_kw("sequence") { "endsequence" } else { "endproperty" }; - self.bump(); + self.skip(); while !self.at_eof() && !self.cur().is_kw(end_kw) { - self.bump(); + self.skip(); } self.expect_closer(end_kw)?; self.parse_label()?; @@ -220,7 +220,7 @@ impl<'a> Parser<'a> { fn parse_default_disable(&mut self) -> PResult { let start = self.here(); let col = self.cur().col; - self.bump(); // default + self.skip(); // default self.expect_kw("disable")?; self.expect_kw("iff")?; self.skip_to_semi()?; @@ -252,7 +252,7 @@ impl<'a> Parser<'a> { fn parse_prop_seq_decl_inner(&mut self) -> PResult { let kw = self.cur().text.clone(); let end_kw = if kw == "sequence" { "endsequence" } else { "endproperty" }; - self.bump(); + self.skip(); let before_name = self.take_gap(); let name = self.expect_name()?; let before_args = self.take_before_open("("); @@ -407,7 +407,7 @@ impl<'a> Parser<'a> { let mut action = ActionBlock::default(); if self.cur().is_sym(";") { action.before = self.take_gap(); - self.bump(); + self.skip(); return Ok(action); } if !self.cur().is_kw("else") { @@ -415,7 +415,7 @@ impl<'a> Parser<'a> { } if self.cur().is_kw("else") { action.before_else = self.take_gap(); - self.bump(); + self.skip(); action.after_else = self.take_gap(); action.fail = Some(Box::new(self.parse_stmt()?)); } diff --git a/crates/vlog_parser/src/parser/class.rs b/crates/vlog_parser/src/parser/class.rs index fdb88cf..919e721 100644 --- a/crates/vlog_parser/src/parser/class.rs +++ b/crates/vlog_parser/src/parser/class.rs @@ -94,7 +94,7 @@ impl<'a> Parser<'a> { let mut after_hash = Vec::new(); let mut param_directives = Vec::new(); if self.cur().is_sym("#") { - self.bump(); + self.skip(); after_hash = self.take_gap(); self.expect_sym("(")?; let mark = self.diags_mark(); @@ -305,7 +305,7 @@ impl<'a> Parser<'a> { return self.parse_constraint_foreach(); } if self.cur().is_kw("unique") && self.nth(1).is_sym("{") { - self.bump(); + self.skip(); let comments = self.take_gap(); let items = self.parse_constraint_expr_set()?; return Ok(ConstraintItemKind::Unique { items, comments }); @@ -314,9 +314,9 @@ impl<'a> Parser<'a> { // `soft` is matched by text, for the reason `parse_constraint_expr` // gives. if self.cur().is_kw("disable") && word_at(self.nth(1), "soft") { - self.bump(); + self.skip(); let before = self.take_gap(); - self.bump(); + self.skip(); let after = self.take_gap(); let expr = self.parse_expr()?; return Ok(ConstraintItemKind::DisableSoft { @@ -341,7 +341,7 @@ impl<'a> Parser<'a> { let soft = self.at_soft_constraint(); let mut after_soft = Vec::new(); if soft { - self.bump(); + self.skip(); after_soft = self.take_gap(); } let mark = self.pending_trailing.len(); @@ -374,7 +374,7 @@ impl<'a> Parser<'a> { } if !soft && self.cur().is_sym("->") { let before = self.take_around(mark); - self.bump(); + self.skip(); let after = self.take_around(mark); let set = self.parse_constraint_set()?; return Ok(ConstraintItemKind::Implication { @@ -403,7 +403,7 @@ impl<'a> Parser<'a> { let mut els = None; if self.cur().is_kw("else") { else_comments = self.take_dangling(); - self.bump(); + self.skip(); // The gap after `else` is this item's when the set it introduces // opens with a token of its own — a `{`, or the `if` of a chain. // A set written on the next line leaves it to that item's own @@ -458,13 +458,13 @@ impl<'a> Parser<'a> { } fn parse_solve_before(&mut self) -> PResult { - self.bump(); // solve + self.skip(); // solve let solve = self.parse_solve_operands()?; if !word_at(self.cur(), "before") { return self.error("expected `before`"); } let before_comments = self.take_gap(); - self.bump(); + self.skip(); let before = self.parse_solve_operands()?; Ok(ConstraintItemKind::SolveBefore { solve, before_comments, before }) } @@ -526,7 +526,7 @@ impl<'a> Parser<'a> { expr: Expr, before: Vec, ) -> PResult { - self.bump(); // dist + self.skip(); // dist let after = self.take_gap(); self.expect_sym("{")?; let mut weights: Vec = Vec::new(); @@ -539,8 +539,8 @@ impl<'a> Parser<'a> { let mut op_comments = BinaryComments::default(); if let Some(spelling) = self.dist_weight_op() { op_comments.before = self.take_gap(); - self.bump(); - self.bump(); + self.skip(); + self.skip(); op_comments.after = self.take_gap(); op = Some(spelling.to_string()); weight = Some(self.parse_ternary()?); diff --git a/crates/vlog_parser/src/parser/covergroup.rs b/crates/vlog_parser/src/parser/covergroup.rs index 207b1ba..315c111 100644 --- a/crates/vlog_parser/src/parser/covergroup.rs +++ b/crates/vlog_parser/src/parser/covergroup.rs @@ -56,7 +56,7 @@ impl<'a> Parser<'a> { self.take_member_prefix(); self.expect_kw("covergroup")?; while !self.at_eof() && !self.cur().is_kw("endgroup") { - self.bump(); + self.skip(); } self.expect_closer("endgroup")?; self.parse_label()?; @@ -139,7 +139,7 @@ impl<'a> Parser<'a> { fn parse_coverage_event(&mut self) -> PResult> { if self.cur().is_kw("with") { let before_with = self.take_gap(); - self.bump(); + self.skip(); let after_with = self.take_gap(); self.expect_kw("function")?; let after_function = self.take_gap(); @@ -147,7 +147,7 @@ impl<'a> Parser<'a> { return self.error("expected `sample`"); } let name = Name { text: self.cur().text.clone(), span: self.cur().span }; - self.bump(); + self.skip(); let before_args = self.take_before_open("("); let has_parens = self.cur().is_sym("("); let args = self.parse_tf_ports(false)?.args; @@ -163,7 +163,7 @@ impl<'a> Parser<'a> { } if self.cur().is_sym("@") { let before = self.take_gap(); - self.bump(); + self.skip(); let sens = self.parse_sens_list()?; return Ok(Some(CoverageEvent::Clocking { before, sens })); } @@ -206,9 +206,9 @@ impl<'a> Parser<'a> { && (word_at(self.nth(2), "coverpoint") || word_at(self.nth(2), "cross")) { let name = Name { text: self.cur().text.clone(), span: self.cur().span }; - self.bump(); + self.skip(); let before = self.take_gap(); - self.bump(); // : + self.skip(); // : let after = self.take_gap(); Some(CoverLabel { name, comments: Box::new(BinaryComments { before, after }) }) } else { @@ -224,7 +224,7 @@ impl<'a> Parser<'a> { } fn parse_coverpoint(&mut self, label: Option) -> PResult { - self.bump(); // coverpoint + self.skip(); // coverpoint let after_kw = self.take_gap(); let expr = self.parse_expr()?; let iff = self.parse_cover_iff()?; @@ -234,7 +234,7 @@ impl<'a> Parser<'a> { } fn parse_cross(&mut self, label: Option) -> PResult { - self.bump(); // cross + self.skip(); // cross let after_kw = self.take_gap(); let mut items: Vec = Vec::new(); loop { @@ -265,7 +265,7 @@ impl<'a> Parser<'a> { return Ok(None); } let before_kw = self.take_gap(); - self.bump(); + self.skip(); let after_kw = self.take_gap(); self.expect_sym("(")?; let after_open = self.take_gap(); @@ -356,13 +356,13 @@ impl<'a> Parser<'a> { let wildcard = word_at(self.cur(), "wildcard") && bin_kind_at(self.nth(1)).is_some(); let mut after_wildcard = Vec::new(); if wildcard { - self.bump(); + self.skip(); after_wildcard = self.take_gap(); } let Some(kind) = bin_kind_at(self.cur()) else { return self.error("expected `bins`, `ignore_bins` or `illegal_bins`"); }; - self.bump(); + self.skip(); let before_name = self.take_gap(); let name = self.expect_name()?; let array = self.parse_bin_array()?; @@ -392,7 +392,7 @@ impl<'a> Parser<'a> { return Ok(None); } let before = self.take_gap(); - self.bump(); + self.skip(); let inner_before = self.take_gap(); let size = if self.cur().is_sym("]") { None } else { Some(self.parse_expr()?) }; let inner_after = self.gap_before("]"); @@ -412,12 +412,12 @@ impl<'a> Parser<'a> { /// `bins b = (1'b1[*5]);` wrong. fn parse_bin_spec(&mut self, in_cross: bool) -> PResult { if self.cur().is_kw("default") { - self.bump(); + self.skip(); // `sequence` really is a lexer keyword (a `sequence ... endsequence` // declaration), so this one is not matched by text. if self.cur().is_kw("sequence") { let comments = self.take_gap(); - self.bump(); + self.skip(); return Ok(BinSpec::DefaultSequence { comments }); } return Ok(BinSpec::Default); @@ -446,7 +446,7 @@ impl<'a> Parser<'a> { break; } let before = self.take_gap(); - self.bump(); + self.skip(); let after = self.take_gap(); arrow = BinaryComments { before, after }; } @@ -494,7 +494,7 @@ impl<'a> Parser<'a> { return Ok(None); } let before = self.take_gap(); - self.bump(); // [ + self.skip(); // [ let after_open = self.take_gap(); let op = self.bump().text; let inner_before = self.take_gap(); @@ -503,7 +503,7 @@ impl<'a> Parser<'a> { let mut hi = None; if self.cur().is_sym(":") { colon.before = self.take_gap(); - self.bump(); + self.skip(); colon.after = self.take_gap(); hi = Some(self.parse_expr()?); } @@ -541,13 +541,13 @@ impl<'a> Parser<'a> { fn parse_select_primary(&mut self) -> PResult { if self.cur().is_sym("!") { - self.bump(); + self.skip(); let comments = self.take_gap(); let expr = self.parse_select_primary()?; return Ok(SelectExpr::Not { comments, expr: Box::new(expr) }); } if self.cur().is_sym("(") { - self.bump(); + self.skip(); let before = self.take_gap(); let expr = self.parse_select_expr()?; let after = self.gap_before(")"); @@ -577,7 +577,7 @@ impl<'a> Parser<'a> { } fn parse_binsof(&mut self) -> PResult { - self.bump(); // binsof + self.skip(); // binsof let after_kw = self.take_gap(); self.expect_sym("(")?; let after_open = self.take_gap(); @@ -589,7 +589,7 @@ impl<'a> Parser<'a> { let mut intersect = None; if word_at(self.cur(), "intersect") { before_intersect = self.take_gap(); - self.bump(); + self.skip(); after_intersect = self.take_gap(); intersect = Some(self.parse_constraint_expr_set()?); } @@ -610,7 +610,7 @@ impl<'a> Parser<'a> { return Ok(None); } let before_kw = self.take_gap(); - self.bump(); + self.skip(); let after_kw = self.take_gap(); self.expect_sym("(")?; let after_open = self.take_gap(); diff --git a/crates/vlog_parser/src/parser/cursor.rs b/crates/vlog_parser/src/parser/cursor.rs index f5be593..7cfe66f 100644 --- a/crates/vlog_parser/src/parser/cursor.rs +++ b/crates/vlog_parser/src/parser/cursor.rs @@ -63,6 +63,31 @@ impl<'a> Parser<'a> { t } + /// Consume the current token without building a copy of it. + /// + /// Exactly [`Parser::bump`] for the caller that throws the token away — + /// the same comment plumbing, the same cursor step, the same `self.tokens` + /// left untouched — minus the clone. `bump` copies the token's `text` + /// (a `String`, so an allocation) and its comment buckets for a value most + /// callers drop on the next line; on a 40 267-line generated file that is + /// one allocate-and-free per token consumed (TODO §63.2). + pub(super) fn skip(&mut self) { + let token = &self.tokens[self.pos]; + // Cloned rather than moved out, because `bump` moved them out of its + // *copy*: the stream keeps its comments either way, which is what the + // rewind of a speculative parse relies on. + let (mut leading, trailing) = (token.leading.clone(), token.trailing.clone()); + if self.pos + 1 < self.tokens.len() { + self.pos += 1; + } + if !leading.is_empty() { + self.pending_leading.append(&mut leading); + } + if let Some(trailing) = trailing { + self.pending_trailing.push(trailing); + } + } + /// Open one level of nesting, refusing to recurse past /// [`MAX_NESTING_DEPTH`]. Callers that succeed must pair this with /// [`Parser::leave`] on every path out, including the error paths. @@ -199,7 +224,7 @@ impl<'a> Parser<'a> { pub(super) fn eat_sym(&mut self, sym: &str) -> bool { if self.cur().is_sym(sym) { - self.bump(); + self.skip(); true } else { false @@ -208,7 +233,7 @@ impl<'a> Parser<'a> { pub(super) fn eat_kw(&mut self, kw: &str) -> bool { if self.cur().is_kw(kw) { - self.bump(); + self.skip(); true } else { false diff --git a/crates/vlog_parser/src/parser/decl.rs b/crates/vlog_parser/src/parser/decl.rs index 8bc8e25..06cc34f 100644 --- a/crates/vlog_parser/src/parser/decl.rs +++ b/crates/vlog_parser/src/parser/decl.rs @@ -39,7 +39,7 @@ impl<'a> Parser<'a> { // this function with the `virtual` already taken into // `DataDecl::qualifiers`, so this only fires for the other positions.) if self.cur().is_kw("virtual") { - self.bump(); + self.skip(); ty.virt = Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare }); // `virtual spi_if.tb sif` — a modport-qualified virtual interface @@ -97,12 +97,12 @@ impl<'a> Parser<'a> { // comment inside the brackets could attach. let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; - self.bump(); + self.skip(); comments.after_open = self.take_gap(); let kind = if self.cur().is_sym("]") { // `[]` — a dynamic array. comments.before_close = std::mem::take(&mut comments.after_open); - self.bump(); + self.skip(); dims.push(Dim { kind: DimKind::Dynamic, comments: Box::new(comments), @@ -111,7 +111,7 @@ impl<'a> Parser<'a> { continue; } else if self.cur().is_sym("*") && self.nth(1).is_sym("]") { // `[*]` — a wildcard-keyed associative array. - self.bump(); + self.skip(); DimKind::Wildcard } else { let a = self.parse_expr()?; @@ -303,7 +303,7 @@ impl<'a> Parser<'a> { // `wire /* c */ #5 w;`. Taken only here — when the read does not // happen the gap belongs to whatever comes next. let before_hash = self.take_gap(); - self.bump(); + self.skip(); let after_hash = self.take_gap(); Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type })) } @@ -392,7 +392,7 @@ impl<'a> Parser<'a> { let mut eq_comments = BinaryComments::default(); let value = if self.cur().is_sym("=") { eq_comments.before = self.take_gap(); - self.bump(); + self.skip(); eq_comments.after = self.take_gap(); Some(self.parse_expr()?) } else { @@ -436,7 +436,7 @@ impl<'a> Parser<'a> { // grammar of their own and are still a clean parse error. let tagged = word_at(self.cur(), "tagged"); if tagged { - self.bump(); + self.skip(); header_comments.after_tagged = self.take_gap(); } let packed = self.eat_kw("packed"); diff --git a/crates/vlog_parser/src/parser/directive.rs b/crates/vlog_parser/src/parser/directive.rs index 1cb8e84..56abeae 100644 --- a/crates/vlog_parser/src/parser/directive.rs +++ b/crates/vlog_parser/src/parser/directive.rs @@ -347,8 +347,8 @@ impl<'a> Parser<'a> { let raw = if self.at_spaced_macro_call() { let start = self.here(); let col = self.cur().col; - self.bump(); // `NAME - self.bump(); // ( + self.skip(); // `NAME + self.skip(); // ( self.skip_balanced("(", ")")?; // Verbatim, space included: the argument text is preprocessor // input lucisv does not model, and closing the gap would make the diff --git a/crates/vlog_parser/src/parser/expr.rs b/crates/vlog_parser/src/parser/expr.rs index a8b48a6..ae16030 100644 --- a/crates/vlog_parser/src/parser/expr.rs +++ b/crates/vlog_parser/src/parser/expr.rs @@ -64,7 +64,7 @@ impl<'a> Parser<'a> { // Each of the four gaps inside a `? :` can hold comments; kept // apart so none of them drifts across the `?` or the `:`. let before_question = self.take_around(mark); - self.bump(); + self.skip(); let after_question = self.take_around(mark); let then = self.parse_expr()?; let before_colon = self.take_around(mark); @@ -144,7 +144,7 @@ impl<'a> Parser<'a> { // The word is an operator like any other, and keeps the // comments written on either side of it the same way. let before = self.take_around(mark); - self.bump(); + self.skip(); let after = self.take_around(mark); let comments = Box::new(BinaryComments { before, after }); // `x inside `MACRO` — the macro expands to the `{...}` set, @@ -324,7 +324,7 @@ impl<'a> Parser<'a> { let base = Box::new(base); if self.cur().is_sym(".") || self.cur().is_sym("::") { let scoped = self.cur().is_sym("::"); - self.bump(); + self.skip(); comments.after_open = self.take_gap(); let name = self.expect_ident()?; let comments = Box::new(comments); @@ -415,7 +415,7 @@ impl<'a> Parser<'a> { before_open: self.take_before_open("("), ..CallComments::default() }; - self.bump(); + self.skip(); let mut args = Vec::new(); if !self.cur().is_sym(")") { let arg_start = self.here(); @@ -462,14 +462,14 @@ impl<'a> Parser<'a> { }, ); } else if self.nth(1).is_sym("[") { - self.bump(); // with + self.skip(); // with let range = self.parse_stream_range(comments)?; expr = self.expr_at( start, ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) }, ); } else { - self.bump(); // with + self.skip(); // with comments.after_kw = self.take_before_open("("); // `( expression )` — an ordinary parenthesized primary, // which is what IEEE 1800 §7.12 spells here. @@ -511,9 +511,9 @@ impl<'a> Parser<'a> { }, ); } else { - self.bump(); // ' + self.skip(); // ' comments.after_tick = self.take_gap(); - self.bump(); // ( + self.skip(); // ( comments.after_open = self.take_gap(); let inner = self.parse_expr()?; comments.before_close = self.gap_before(")"); diff --git a/crates/vlog_parser/src/parser/instance.rs b/crates/vlog_parser/src/parser/instance.rs index 613ec62..fceb5d4 100644 --- a/crates/vlog_parser/src/parser/instance.rs +++ b/crates/vlog_parser/src/parser/instance.rs @@ -24,7 +24,7 @@ impl<'a> Parser<'a> { let mut after_hash = Vec::new(); let mut after_delay = Vec::new(); let delay = if self.cur().is_sym("#") { - self.bump(); + self.skip(); after_hash = self.take_gap(); let delay = self.parse_delay_value()?; // The gap between the delay and the first left-hand side is the @@ -82,7 +82,7 @@ impl<'a> Parser<'a> { } let mut comments = Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() }); - self.bump(); // ( + self.skip(); // ( comments.after_open = self.take_gap(); let first = self.bump().text; // The gap after the first strength ends either at the `,` or at the @@ -121,7 +121,7 @@ impl<'a> Parser<'a> { // What is written just inside the `(` belongs to the first value; the // gap before each `,` and the gap after it belong to the values either // side of it. - self.bump(); + self.skip(); let mut leading = self.take_gap(); let mut out: Vec = Vec::new(); loop { @@ -242,7 +242,7 @@ impl<'a> Parser<'a> { /// `bind [: , ...] [#(...)] (...);` pub(super) fn parse_bind(&mut self) -> PResult { - self.bump(); // `bind` + self.skip(); // `bind` // The target is a bare string, so a comment written before it has no // node to attach to: harvest it here, where source order is still // known, rather than letting it drift onto the instance below. @@ -250,7 +250,7 @@ impl<'a> Parser<'a> { let start = self.here(); let mut target = vec![self.parse_path_segment()?]; while self.cur().is_sym(".") { - self.bump(); + self.skip(); target.push(self.parse_path_segment()?); } let target_span = self.span_from(start); @@ -278,7 +278,7 @@ impl<'a> Parser<'a> { let start = self.here(); let mut text = self.expect_ident()?; while self.cur().is_sym(".") { - self.bump(); + self.skip(); let segment = self.expect_ident()?; Self::push_path_segment(&mut text, &segment); } @@ -301,7 +301,7 @@ impl<'a> Parser<'a> { let module_start = self.here(); let mut module = self.expect_ident()?; while self.cur().is_sym("::") { - self.bump(); + self.skip(); let segment = self.expect_ident()?; Self::push_scope_segment(&mut module, &segment); } @@ -312,7 +312,7 @@ impl<'a> Parser<'a> { let mut after_hash = Vec::new(); let mut param_directives = Vec::new(); if self.cur().is_sym("#") { - self.bump(); + self.skip(); after_hash = self.take_gap(); self.expect_sym("(")?; let mut list = Vec::new(); @@ -571,7 +571,7 @@ impl<'a> Parser<'a> { // `.name(/* unused */)`: the comments were written inside // these parens and are printed back inside them. let inside = self.take_around(mark); - self.bump(); + self.skip(); Some(self.expr_at(paren_start, ExprKind::Empty(inside))) } else { after_open = self.take_gap(); @@ -684,7 +684,7 @@ impl<'a> Parser<'a> { let start = self.here(); let col = self.cur().col; while self.pos < end_pos && !self.at_eof() { - self.bump(); + self.skip(); } let raw = self.verbatim_since(start, col); self.expr_at(start, ExprKind::Verbatim(raw)) @@ -699,7 +699,7 @@ impl<'a> Parser<'a> { let before_hash = self.take_before_open("#"); let mut after_hash = Vec::new(); let delay = if self.cur().is_sym("#") { - self.bump(); + self.skip(); after_hash = self.take_gap(); self.parse_delay_values()? } else { diff --git a/crates/vlog_parser/src/parser/item.rs b/crates/vlog_parser/src/parser/item.rs index 8dddb49..e0fc4c0 100644 --- a/crates/vlog_parser/src/parser/item.rs +++ b/crates/vlog_parser/src/parser/item.rs @@ -155,7 +155,7 @@ impl<'a> Parser<'a> { // `TokenKind` match below because punctuation is matched by text // everywhere in this file. See `ItemKind::Empty`. if self.cur().is_sym(";") { - self.bump(); + self.skip(); return Ok(ItemKind::Empty); } let t = self.cur(); @@ -209,7 +209,7 @@ impl<'a> Parser<'a> { "modport" => self.parse_modport().map(ItemKind::Modport), "clocking" => self.parse_clocking(false).map(ItemKind::Clocking), "default" if self.nth(1).is_kw("clocking") => { - self.bump(); + self.skip(); self.parse_clocking(true).map(ItemKind::Clocking) } "default" if self.nth(1).is_kw("disable") => self.parse_default_disable_item(), @@ -243,7 +243,7 @@ impl<'a> Parser<'a> { Ok(ItemKind::PortDecl(d)) } "genvar" => { - self.bump(); + self.skip(); let mut names = vec![self.expect_name()?]; while self.eat_sym(",") { names.push(self.expect_name()?); @@ -258,15 +258,15 @@ impl<'a> Parser<'a> { Ok(ItemKind::Always { kw, stmt }) } "initial" => { - self.bump(); + self.skip(); Ok(ItemKind::Initial(self.parse_stmt()?)) } "final" => { - self.bump(); + self.skip(); Ok(ItemKind::Final(self.parse_stmt()?)) } "generate" => { - self.bump(); + self.skip(); let mut items = Vec::new(); while !self.at_body_end("endgenerate") { items.push(self.item_or_recover()?); @@ -339,7 +339,7 @@ impl<'a> Parser<'a> { } } "defparam" => { - self.bump(); + self.skip(); let mut pairs = Vec::new(); loop { let lhs = self.parse_expr()?; @@ -492,7 +492,7 @@ impl<'a> Parser<'a> { loop { let star = self.cur().span; let pkg = if allow_star_pkg && self.cur().is_sym("*") { - self.bump(); + self.skip(); Name { text: "*".to_string(), span: star } } else { self.expect_name()? @@ -578,7 +578,7 @@ impl<'a> Parser<'a> { } let span = self.cur().span; let name = Name { text: self.bump().text, span }; - self.bump(); + self.skip(); Some(name) } @@ -603,7 +603,7 @@ impl<'a> Parser<'a> { let then = self.parse_gen_block()?; let els = if self.cur().is_kw("else") { let meta = self.take_meta(); - self.bump(); + self.skip(); if self.cur().is_kw("if") { Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?)))) } else { @@ -688,7 +688,7 @@ impl<'a> Parser<'a> { // The gap between whatever came before and the `begin` belongs to // the block — nothing else was written where it could attach. let before_kw = self.take_gap(); - self.bump(); + self.skip(); let before_colon = self.gap_before(":"); let mut after_colon = Vec::new(); let label_name = if self.eat_sym(":") { diff --git a/crates/vlog_parser/src/parser/keyword_stmt.rs b/crates/vlog_parser/src/parser/keyword_stmt.rs index 71037c5..1238d3d 100644 --- a/crates/vlog_parser/src/parser/keyword_stmt.rs +++ b/crates/vlog_parser/src/parser/keyword_stmt.rs @@ -22,7 +22,7 @@ impl<'a> Parser<'a> { let kw = self.cur().text.clone(); match kw.as_str() { "begin" => { - self.bump(); + self.skip(); let (label_comments, label_name) = self.parse_label_with()?; let (label, label_span) = split_label(label_name); let mut stmts = Vec::new(); @@ -45,7 +45,7 @@ impl<'a> Parser<'a> { }) } "fork" => { - self.bump(); + self.skip(); let (label_comments, label_name) = self.parse_label_with()?; let (label, label_span) = split_label(label_name); let mut stmts = Vec::new(); @@ -88,7 +88,7 @@ impl<'a> Parser<'a> { "case" | "casex" | "casez" => self.parse_case_stmt(None), "for" => self.parse_for_stmt(), "while" => { - self.bump(); + self.skip(); self.expect_sym("(")?; let cond = self.cond_or_recover()?; let recovered = cond.is_error(); @@ -96,7 +96,7 @@ impl<'a> Parser<'a> { Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) }) } "do" => { - self.bump(); + self.skip(); let body = Box::new(self.parse_stmt()?); self.expect_kw("while")?; let mut comments = @@ -110,7 +110,7 @@ impl<'a> Parser<'a> { Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) }) } "repeat" => { - self.bump(); + self.skip(); self.expect_sym("(")?; let count = self.cond_or_recover()?; let recovered = count.is_error(); @@ -118,11 +118,11 @@ impl<'a> Parser<'a> { Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) }) } "forever" => { - self.bump(); + self.skip(); Ok(StmtKind::Forever { body: Box::new(self.parse_stmt()?) }) } "foreach" => { - self.bump(); + self.skip(); let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; @@ -141,41 +141,41 @@ impl<'a> Parser<'a> { }) } "randcase" => { - self.bump(); + self.skip(); let (items, dangling) = self.parse_case_body()?; Ok(StmtKind::RandCase { items, dangling }) } "return" => { - self.bump(); + self.skip(); let after_kw = self.take_gap(); let expr = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; self.expect_stmt_semi()?; Ok(StmtKind::Return { after_kw, expr }) } "break" => { - self.bump(); + self.skip(); self.expect_stmt_semi()?; Ok(StmtKind::Break) } "continue" => { - self.bump(); + self.skip(); self.expect_stmt_semi()?; Ok(StmtKind::Continue) } "disable" => { - self.bump(); + self.skip(); // `disable fork;` kills every process the enclosing `fork` // started; `fork` is a keyword, not a block name. if self.cur().is_kw("fork") { let name_span = self.cur().span; - self.bump(); + self.skip(); self.expect_stmt_semi()?; return Ok(StmtKind::Disable { name: "fork".to_string(), name_span }); } let start = self.here(); let mut name = self.expect_ident()?; while self.cur().is_sym(".") { - self.bump(); + self.skip(); name.push('.'); name.push_str(&self.expect_ident()?); } @@ -184,11 +184,11 @@ impl<'a> Parser<'a> { Ok(StmtKind::Disable { name, name_span }) } "wait" => { - self.bump(); + self.skip(); // `wait fork;` waits for the enclosing `fork`'s children // (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition. if self.cur().is_kw("fork") { - self.bump(); + self.skip(); self.expect_stmt_semi()?; return Ok(StmtKind::WaitFork); } @@ -217,7 +217,7 @@ impl<'a> Parser<'a> { Ok(StmtKind::Assert { kw, cond, then, els }) } "force" => { - self.bump(); + self.skip(); let lhs = self.parse_unary()?; self.expect_sym("=")?; let rhs = self.parse_expr()?; @@ -290,7 +290,7 @@ impl<'a> Parser<'a> { /// is parsed as usual. The init entries read before the failure are kept /// — they are what declares the loop variable the body uses. fn parse_for_stmt(&mut self) -> PResult { - self.bump(); + self.skip(); let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; comments.after_open = self.take_gap(); diff --git a/crates/vlog_parser/src/parser/mod.rs b/crates/vlog_parser/src/parser/mod.rs index e2e28a1..46313cb 100644 --- a/crates/vlog_parser/src/parser/mod.rs +++ b/crates/vlog_parser/src/parser/mod.rs @@ -431,7 +431,7 @@ impl<'a> Parser<'a> { let mut scope: Vec = Vec::new(); while self.cur().is_sym("::") { let before_sep = self.take_gap(); - self.bump(); + self.skip(); let after_sep = self.take_gap(); let next = self.expect_name()?; scope.push(ScopeSeg { name, before_sep, after_sep }); @@ -474,7 +474,7 @@ impl<'a> Parser<'a> { let start = self.here(); let mut name = self.expect_ident()?; while self.cur().is_sym("::") { - self.bump(); + self.skip(); let segment = self.expect_ident()?; Self::push_scope_segment(&mut name, &segment); } diff --git a/crates/vlog_parser/src/parser/module.rs b/crates/vlog_parser/src/parser/module.rs index 724bf8b..ae58baa 100644 --- a/crates/vlog_parser/src/parser/module.rs +++ b/crates/vlog_parser/src/parser/module.rs @@ -327,7 +327,7 @@ impl<'a> Parser<'a> { return Ok(None); } let before_dir = self.take_gap(); - self.bump(); + self.skip(); let after_dir = self.take_gap(); Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? })) } @@ -387,7 +387,7 @@ impl<'a> Parser<'a> { if !self.cur().is_sym("#") { return Ok(out); } - self.bump(); + self.skip(); out.after_hash = self.take_gap(); self.expect_sym("(")?; let mark = self.diags_mark(); @@ -438,7 +438,7 @@ impl<'a> Parser<'a> { return Ok((Box::default(), None)); } let before = self.take_gap(); - self.bump(); + self.skip(); let after = self.take_gap(); let value = parse(self)?; Ok((Box::new(BinaryComments { before, after }), Some(value))) @@ -507,7 +507,7 @@ impl<'a> Parser<'a> { if !self.cur().is_sym("(") { return Ok((PortList::None, Vec::new(), Vec::new())); } - self.bump(); + self.skip(); let mark = self.diags_mark(); // Directives before the first port. Harvested here rather than in the // loop below because both the ANSI/non-ANSI decision and the @@ -517,7 +517,7 @@ impl<'a> Parser<'a> { if self.cur().is_sym(")") { // `module m (/* c */);` — the comments stay between the parens. let dangling = self.take_dangling(); - self.bump(); + self.skip(); return Ok((PortList::Empty, dangling, directives)); } let ansi = { diff --git a/crates/vlog_parser/src/parser/primary.rs b/crates/vlog_parser/src/parser/primary.rs index c3432d1..f172b34 100644 --- a/crates/vlog_parser/src/parser/primary.rs +++ b/crates/vlog_parser/src/parser/primary.rs @@ -31,7 +31,7 @@ impl<'a> Parser<'a> { } TokenKind::Ident | TokenKind::SystemIdent => { if self.at_shallow_copy() { - self.bump(); // new + self.skip(); // new let src = self.parse_postfix()?; return Ok(self.expr_at(start, ExprKind::New(Box::new(src)))); } @@ -53,9 +53,9 @@ impl<'a> Parser<'a> { let ty = self.expr_at(ty_start, ExprKind::Ident(ty_text)); let mut comments = CastComments { before_tick: self.take_gap(), ..Default::default() }; - self.bump(); // ' + self.skip(); // ' comments.after_tick = self.take_gap(); - self.bump(); // ( + self.skip(); // ( comments.after_open = self.take_gap(); let inner = self.parse_expr()?; comments.before_close = self.gap_before(")"); @@ -85,14 +85,14 @@ impl<'a> Parser<'a> { // work through the existing expression grammar, and lucisv // checks legality nowhere else either. "$" => { - self.bump(); + self.skip(); Ok(self.expr_at(start, ExprKind::Ident("$".to_string()))) } "(" => { // Comments written just inside the parens stay there; // anything else would move them across a token. let mut before = self.take_trailing_here(); - self.bump(); + self.skip(); before.append(&mut self.take_leading_here()); let mark = self.pending_trailing.len(); let inner_start = self.here(); @@ -106,7 +106,7 @@ impl<'a> Parser<'a> { )) } "{" => { - self.bump(); + self.skip(); if self.cur().is_sym("<<") || self.cur().is_sym(">>") { return self.parse_stream_concat(start); } @@ -114,13 +114,13 @@ impl<'a> Parser<'a> { // `{}` — the empty queue/dynamic-array literal // (`q = {};`). Illegal as a Verilog concatenation, // but lucisv is not a legality checker. - self.bump(); + self.skip(); return Ok(self.expr_at(start, ExprKind::Concat(Vec::new()))); } let first = self.parse_expr_item()?; if self.cur().is_sym("{") { // Replication {N{a, b}} - self.bump(); + self.skip(); let inner_first = self.parse_expr_item()?; let inner = self.parse_expr_list(inner_first, "}")?; self.expect_sym("}")?; @@ -241,7 +241,7 @@ impl<'a> Parser<'a> { /// (`ty'{...}`) keeps the type outside the pattern's span, in the `Cast` /// node that wraps it. pub(super) fn parse_assign_pattern(&mut self, start: u32) -> PResult { - self.bump(); // '{ + self.skip(); // '{ if self.at_assign_pattern_repl() { return self.parse_assign_pattern_repl(start); } @@ -251,7 +251,7 @@ impl<'a> Parser<'a> { let item_start = self.here(); let mut meta = self.take_meta(); let key_or_val = if self.cur().is_kw("default") { - self.bump(); + self.skip(); self.expr_at(item_start, ExprKind::Ident("default".to_string())) } else { self.parse_expr_or_type()? @@ -352,7 +352,7 @@ impl<'a> Parser<'a> { /// the `.` and the next token is an identifier. pub(super) fn parse_named_arg(&mut self) -> PResult { let start = self.here(); - self.bump(); // . + self.skip(); // . let after_dot = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let before_open = self.take_before_open("("); @@ -365,7 +365,7 @@ impl<'a> Parser<'a> { // between the parens, exactly as an empty connection does. The // span covers the `( )` pair. let comments = self.take_around(mark); - self.bump(); + self.skip(); (self.expr_at(paren_start, ExprKind::Empty(comments)), Vec::new()) } else { after_open = self.take_gap(); @@ -403,7 +403,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_value_range(&mut self) -> PResult { let start = self.here(); let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; - self.bump(); // [ + self.skip(); // [ comments.after_open = self.take_gap(); let lo = self.parse_expr()?; comments.before_op = self.gap_before(":"); diff --git a/crates/vlog_parser/src/parser/randsequence.rs b/crates/vlog_parser/src/parser/randsequence.rs index 5ef2139..e0f0ebc 100644 --- a/crates/vlog_parser/src/parser/randsequence.rs +++ b/crates/vlog_parser/src/parser/randsequence.rs @@ -52,7 +52,7 @@ impl<'a> Parser<'a> { // The gap in front of the `|` belongs to the alternative it opens, // so it prints on the bar's own side of the previous one. let before_bar = self.take_gap(); - self.bump(); + self.skip(); alternatives.push(self.parse_alternative(before_bar)?); } let span = self.span_from(start); @@ -107,8 +107,8 @@ impl<'a> Parser<'a> { let mut weight = None; if self.at_weight_op() { before_weight = self.take_gap(); - self.bump(); // : - self.bump(); // = + self.skip(); // : + self.skip(); // = weight = Some(self.parse_weight()?); } Ok(Alternative { before_bar, after_bar, items, before_weight, weight }) @@ -170,7 +170,7 @@ impl<'a> Parser<'a> { return self.parse_rs_if(); } if t.is_kw("repeat") { - self.bump(); + self.skip(); let after_kw = self.take_before_open("("); self.expect_sym("(")?; let count = self.parse_expr()?; @@ -240,7 +240,7 @@ impl<'a> Parser<'a> { // A `default` arm may write no `:` at all (§18.17.4). let has_colon = self.cur().is_sym(":"); if has_colon { - self.bump(); + self.skip(); } else if !is_default { return self.error("expected `:` in a randsequence case arm"); } @@ -271,7 +271,7 @@ impl<'a> Parser<'a> { let after_rand = self.take_gap(); self.expect_kw("join")?; let weight = if self.cur().is_sym("(") { - self.bump(); + self.skip(); let e = self.parse_expr()?; self.expect_sym(")")?; Some(e) @@ -292,7 +292,7 @@ impl<'a> Parser<'a> { let has_parens = self.cur().is_sym("("); let mut args = Vec::new(); if has_parens { - self.bump(); + self.skip(); if !self.cur().is_sym(")") { let first = self.parse_expr_item()?; args = self.parse_expr_list(first, ")")?; diff --git a/crates/vlog_parser/src/parser/recover.rs b/crates/vlog_parser/src/parser/recover.rs index e595b16..47eeab4 100644 --- a/crates/vlog_parser/src/parser/recover.rs +++ b/crates/vlog_parser/src/parser/recover.rs @@ -102,7 +102,7 @@ impl<'a> Parser<'a> { /// error node. pub(super) fn expect_closer(&mut self, kw: &str) -> PResult<()> { if self.cur().is_kw(kw) { - self.bump(); + self.skip(); return Ok(()); } if self.tolerant { @@ -150,7 +150,7 @@ impl<'a> Parser<'a> { return; } if t.is_sym(";") { - self.bump(); + self.skip(); return; } } @@ -159,7 +159,7 @@ impl<'a> Parser<'a> { } else if open > 0 && (t.is_sym(")") || t.is_sym("]") || t.is_sym("}")) { open -= 1; } - self.bump(); + self.skip(); } } @@ -171,7 +171,7 @@ impl<'a> Parser<'a> { if self.pos == start_pos { // The failed construct consumed nothing, so skipping might not // either; take one token to guarantee the enclosing loop advances. - self.bump(); + self.skip(); } self.skip_to_sync(); // Comments inside the skipped range are part of the raw text below. diff --git a/crates/vlog_parser/src/parser/recover_list.rs b/crates/vlog_parser/src/parser/recover_list.rs index 08cfda3..47de9e9 100644 --- a/crates/vlog_parser/src/parser/recover_list.rs +++ b/crates/vlog_parser/src/parser/recover_list.rs @@ -227,7 +227,7 @@ impl<'a> Parser<'a> { if self.pos == start_pos && !self.cur().is_sym(")") { // The header consumed nothing and the skip below may not either; // take one token so the statement cannot be re-read forever. - self.bump(); + self.skip(); } self.skip_inside_brackets(true); // As in `recover`: comments inside the skipped range are bytes of the @@ -247,7 +247,7 @@ impl<'a> Parser<'a> { // Nothing was consumed and nothing below will be: the list loop // neither ends here nor eats a separator, so take one token to // guarantee it advances. - self.bump(); + self.skip(); } else if self.at_open_bracket() { // The element gave up standing *on* a bracket, which is therefore // one it opened and never closed — the `(` of a half-typed @@ -258,7 +258,7 @@ impl<'a> Parser<'a> { // the body would be swallowed looking for a `)` that was never // written. Taken here, the skip starts inside it at the list's own // level and stops at the next line as it does everywhere else. - self.bump(); + self.skip(); } self.skip_inside_brackets(false); let _ = self.take_dangling(); @@ -310,7 +310,7 @@ impl<'a> Parser<'a> { } else if closes { open -= 1; } - self.bump(); + self.skip(); } } diff --git a/crates/vlog_parser/src/parser/split.rs b/crates/vlog_parser/src/parser/split.rs index d668f39..d97fa3f 100644 --- a/crates/vlog_parser/src/parser/split.rs +++ b/crates/vlog_parser/src/parser/split.rs @@ -274,7 +274,7 @@ impl<'a> Parser<'a> { // already moved — are dropped by `verbatim_since`. self.pos = mark.pos; while self.pos < end_pos && !self.at_eof() { - self.bump(); + self.skip(); } self.verbatim_since(start, col) } diff --git a/crates/vlog_parser/src/parser/stmt.rs b/crates/vlog_parser/src/parser/stmt.rs index 71eb420..cb6d785 100644 --- a/crates/vlog_parser/src/parser/stmt.rs +++ b/crates/vlog_parser/src/parser/stmt.rs @@ -125,11 +125,11 @@ impl<'a> Parser<'a> { return Ok(StmtKind::Directive(self.take_raw_text())); } if t.is_sym(";") { - self.bump(); + self.skip(); return Ok(StmtKind::Null); } if t.is_sym("#") { - self.bump(); + self.skip(); let after_hash = self.take_gap(); let delay = self.parse_delay_value()?; let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; @@ -139,7 +139,7 @@ impl<'a> Parser<'a> { }); } if t.is_sym("@") { - self.bump(); + self.skip(); let sens = self.parse_sens_list()?; let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt }); @@ -204,7 +204,7 @@ impl<'a> Parser<'a> { // keyword's left; the then-branch has already taken its own // trailing comment. else_comments = self.take_dangling(); - self.bump(); + self.skip(); Some(Box::new(self.parse_stmt()?)) } else { None @@ -306,7 +306,7 @@ impl<'a> Parser<'a> { if let Some(last) = vars.last_mut() { last.after = self.take_gap(); } - self.bump(); + self.skip(); vars.push(self.parse_foreach_var()?); } } @@ -343,7 +343,7 @@ impl<'a> Parser<'a> { if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=") { let before = self.take_around(mark); - self.bump(); + self.skip(); let after = self.take_gap(); let rhs = self.parse_expr()?; Ok(ForStep::Assign(SimpleAssign { @@ -377,16 +377,16 @@ impl<'a> Parser<'a> { // it (`x[6:0] /* opcode */ = v;`); left in the pending buffers // they would be lost and the safety net would refuse the file. let op_comments = self.take_around(mark); - self.bump(); + self.skip(); let rhs_comments = self.take_around(mark); let timing = if self.cur().is_sym("#") { - self.bump(); + self.skip(); Some(TimingControl::Delay { after_hash: self.take_gap(), expr: self.parse_delay_value()?, }) } else if self.cur().is_sym("@") { - self.bump(); + self.skip(); Some(TimingControl::Event(self.parse_sens_list()?)) } else { None @@ -430,7 +430,7 @@ impl<'a> Parser<'a> { if self.cur().is_sym("*") { // `@*` without parens — the gap after the `@` is the `*`'s own // `before` slot, which the formatter prints in the same place. - self.bump(); + self.skip(); return Ok(SensList::Star { before: after_at, after: Vec::new() }); } if self.cur().kind == TokenKind::Ident { @@ -449,10 +449,10 @@ impl<'a> Parser<'a> { // to whatever node comes next. let mut before = after_at; before.append(&mut self.take_trailing_here()); - self.bump(); // ( + self.skip(); // ( before.append(&mut self.take_leading_here()); let mut after = self.take_trailing_here(); - self.bump(); // * + self.skip(); // * after.append(&mut self.take_leading_here()); self.expect_sym(")")?; return Ok(SensList::Star { before, after }); diff --git a/crates/vlog_parser/src/parser/sva.rs b/crates/vlog_parser/src/parser/sva.rs index 359e310..0ffa54f 100644 --- a/crates/vlog_parser/src/parser/sva.rs +++ b/crates/vlog_parser/src/parser/sva.rs @@ -218,7 +218,7 @@ impl<'a> Parser<'a> { self.link()?; let before = self.take_around(mark); for _ in 0..tokens { - self.bump(); + self.skip(); } let after = self.take_around(mark); let rhs = self.parse_prop_expr(Self::right_operand_prec(prec, right))?; @@ -316,7 +316,7 @@ impl<'a> Parser<'a> { let mut count = None; let mut after_count = Vec::new(); if counted && self.cur().is_sym("[") { - self.bump(); + self.skip(); let after_open = self.take_gap(); count = Some(Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? })); after_count = self.take_gap(); @@ -367,7 +367,7 @@ impl<'a> Parser<'a> { let mut els = None; if self.cur().is_kw("else") { before_else = self.take_gap(); - self.bump(); + self.skip(); after_else = self.take_gap(); els = Some(self.parse_prop_expr(0)?); } @@ -421,7 +421,7 @@ impl<'a> Parser<'a> { let mut labels = Vec::new(); let is_default = self.cur().is_kw("default"); if is_default { - self.bump(); + self.skip(); } else { loop { labels.push(self.parse_expr_item()?); @@ -463,7 +463,7 @@ impl<'a> Parser<'a> { while self.at_repeat_bracket() { self.link()?; let before_open = self.take_gap(); - self.bump(); // [ + self.skip(); // [ let after_open = self.take_gap(); // `[+]` writes no operator of its own: its `+` is the bound. let (op, after_op) = if self.cur().is_sym("+") { @@ -493,7 +493,7 @@ impl<'a> Parser<'a> { range.lo = Some(self.parse_expr()?); if self.cur().is_sym(":") { range.before_colon = self.take_gap(); - self.bump(); + self.skip(); range.after_colon = self.take_gap(); range.hi = Some(self.parse_expr()?); } @@ -509,7 +509,7 @@ impl<'a> Parser<'a> { self.expect_sym("##")?; let after_hash = self.take_gap(); if self.cur().is_sym("[") { - self.bump(); + self.skip(); let after_open = self.take_gap(); let range = Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? }); return Ok(CycleDelay { after_hash, expr: None, range: Some(range) }); @@ -707,7 +707,7 @@ impl<'a> Parser<'a> { let mut items = Vec::new(); while self.cur().is_sym(",") { let before_comma = self.take_gap(); - self.bump(); + self.skip(); let start = self.here(); let meta = self.take_meta(); let lhs = self.parse_expr()?; diff --git a/crates/vlog_parser/src/parser/tf.rs b/crates/vlog_parser/src/parser/tf.rs index e9f857f..6a444f6 100644 --- a/crates/vlog_parser/src/parser/tf.rs +++ b/crates/vlog_parser/src/parser/tf.rs @@ -227,12 +227,12 @@ impl<'a> Parser<'a> { if !self.cur().is_sym("(") { return Ok(TfPorts::default()); } - self.bump(); + self.skip(); if self.cur().is_sym(")") { // Only what was written *inside* the empty `()`, as an empty // argument list of a call keeps. let dangling = self.take_gap(); - self.bump(); + self.skip(); return Ok(TfPorts { args, dangling }); } let mark = self.diags_mark(); @@ -272,9 +272,9 @@ impl<'a> Parser<'a> { // `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104`. // Two keywords, so the gap between them is a slot of its own — // no other direction has an inside. - self.bump(); + self.skip(); after_const = self.take_gap(); - self.bump(); + self.skip(); Some("const ref".to_string()) } else if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") { Some(self.bump().text) @@ -298,7 +298,7 @@ impl<'a> Parser<'a> { let mut eq_comments = BinaryComments::default(); let default = if self.cur().is_sym("=") { eq_comments.before = self.take_gap(); - self.bump(); + self.skip(); eq_comments.after = self.take_gap(); Some(self.parse_expr()?) } else { diff --git a/crates/vlog_parser/src/parser/verbatim.rs b/crates/vlog_parser/src/parser/verbatim.rs index 2dd27eb..fe1c295 100644 --- a/crates/vlog_parser/src/parser/verbatim.rs +++ b/crates/vlog_parser/src/parser/verbatim.rs @@ -38,7 +38,7 @@ impl<'a> Parser<'a> { } else if t.is_kw(&open) { depth += 1; } - self.bump(); + self.skip(); } self.expect_closer(close)?; self.parse_label()?; @@ -52,7 +52,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_opaque_line(&mut self) -> PResult { let start = self.here(); let col = self.cur().col; - self.bump(); + self.skip(); self.skip_to_semi()?; Ok(self.verbatim_since(start, col)) } @@ -94,7 +94,7 @@ impl<'a> Parser<'a> { /// than as a nested assignment. How many there are, and whether they are /// legal lvalues, is a checker's business. pub(super) fn parse_alias(&mut self) -> PResult { - self.bump(); // alias + self.skip(); // alias let mut nets = vec![self.parse_expr()?]; while self.eat_sym("=") { nets.push(self.parse_expr()?); @@ -154,7 +154,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_expect_statement(&mut self) -> PResult { let start = self.here(); let col = self.cur().col; - self.bump(); // expect + self.skip(); // expect self.expect_sym("(")?; self.skip_balanced("(", ")")?; self.skip_action_block()?; @@ -176,7 +176,7 @@ impl<'a> Parser<'a> { } else if t.is_sym(close) { depth -= 1; } - self.bump(); + self.skip(); } Ok(()) } @@ -215,12 +215,12 @@ impl<'a> Parser<'a> { "[" => ("[", "]"), _ => ("{", "}"), }; - self.bump(); + self.skip(); self.skip_balanced(open, close)?; } else if self.eat_sym(";") { return Ok(()); } else { - self.bump(); + self.skip(); } } } diff --git a/docs/features/perf-first-after-edit/README.md b/docs/features/perf-first-after-edit/README.md new file mode 100644 index 0000000..f79f4a7 --- /dev/null +++ b/docs/features/perf-first-after-edit/README.md @@ -0,0 +1,654 @@ +# perf-first-after-edit + +TODO §63.2 — N1 of the 0.52.0 review (`docs/performance_052_review.md`, +item 3 and next action 3). + +## Goal + +The first request after a one-character edit in a 40 267-line generated +file cost **113.6 ms** on 0.52.0, against 0.23 ms for the same request +repeated on an unchanged buffer. The lint snapshot (review round §R1a) +cannot help a fresh revision: what remains is the debounced `Document` +rebuild `answer_request` performs before any handler runs, the +diagnostics publish that lints the new revision, and the menu's own +stages. This round splits that flush into the stages a reader can act on, +then makes the **fresh-revision work itself cheaper** — no cache of +anything across revisions — with the AST, the diagnostics and the menu +byte-identical. Target: ≥ 15 % off the cell, stretch < 95 ms, the +unchanged-repeat cell and the other `offeredit`/`offerkinds` rows within +noise, peak RSS not up. + +## Assumptions + +- The pinmux cell is the worst realistic shape, not the typical one: a + 1 237 143-byte generated register file, 193 816 tokens, one buffer + open, workspace scope, 3 975 files indexed. Everything here is measured + on it; a 400-line hand-written file pays the same work in microseconds. +- `Document::new` is a pure function of (text, index): the same text + against the same index must give the same tokens, tree, defines, + semantics, external resolutions and line index. Every change in this + round is checked against that, file by file, over the corpus and + opentitan (see Parity). +- `vlog_parser::tokenize` is all-or-nothing and its output is a value, + not a rendering: two builds agree on token kind, text, line, column, + span, `blank_before` and every attached comment, or they differ. +- The measurement machine is shared with nothing else while a phase runs + (`tools/perf/README.md`'s rules), and every number below is a median. + +## Handshakes + +- **`lucisv_server ──▶ vlog_parser`** — unamended. `tokenize`, + `parse_tolerant` and `parse_source_tolerant` keep their signatures; + `Document::new` calls them exactly as before. No public `vlog_parser` + item changed name, type or behaviour, so nothing this lane did is a + contract change for the formatter, linter, refactor or CLI either. + **Nothing is owed to the lead here.** +- **`verbose-timing ◀──▶ tools/perf`** — *amended, and this needs a + `docs/topo.md` line the lead owns.* The `timing: codeaction …` line + (`crate::lint_trace`) grows a **third top-level group**, `rebuild{…}`, + beside `flush{…}` and `action{…}`: `lex`, `parse`, `defines`, + `analyze`, `external`, `lines`, `publish` (ms each) and `documents` + (how many `Document`s the flush built). Groups stay siblings — never + nested — because `tools/perf/phases_p2.py`'s `GROUP` regex flattens one + level only; `phases_r1.py` therefore picks the new fields up with no + change, as `trace_rebuild_*` row fields. Pinned by + `lint_trace::tests::the_rebuild_group_names_every_stage_beside_the_other_two`. +- **`docs/perf/README.md`** — not this lane's file. The entry it wants is + in "For `docs/perf/README.md`" below, for the lead to paste. + +### Requested `docs/topo.md` amendments (the lead's file) + +1. The `verbose-timing ◀──▶ …` handshake row (§2.7): add that the + `timing: codeaction` line carries a third group, `rebuild{…}`, whose + fields are the flush's `Document`-rebuild stages, and that the three + groups are siblings by contract (the harness flattens one level). +2. The `lucisv_server/src/state.rs` file row: `Document::new`'s six + derivations are individually traced through `crate::lint_trace`, so a + stage added to or removed from that constructor wants a `Rebuild` + variant beside it. + +## Status / TODO + +- [x] the flush split in `lint_trace` (`Rebuild`, `Rebuilt`, `rebuild()`, + `saw_document()`), the `rebuild{…}` group on the trace line, and + the 0.53.0 numbers taken **before** any behaviour changed +- [x] change 1 — the lexer's two phases fused (no `Vec`) +- [x] change 2 — `Parser::skip`, the non-cloning `bump` for the 217 call + sites that threw the token away +- [x] change 3 — the operator table's first-byte test +- [x] parity: token stream + parse diagnostics + whole AST + symbol table + digested per file over 4 807 files (corpus + opentitan), 0 differ; + `format --stdout` byte-identical over corpus (860) and over + opentitan (3 947); diagnostics and the all-family menu on the + pinmux buffer identical before and after +- [x] paired `offeredit` / `offerkinds` / `flush` / `diagnostics` / + `rss` against a 0.53.0 server built from 1b8723c, order alternated + — **−19.2 % on the cell, the ≥ 15 % gate met and the < 95 ms + stretch met at 88.3 ms** +- [x] QA + +## Work log + +### 2026-09-12 — measure first: the flush split + +`crate::lint_trace` already split a traced request into +flush / config / build / lint / fence / serialize. The flush was one +number (`flush{wall=…}`), so "the dirty-buffer stage dominates" was as +far as the 0.52.0 review could attribute the cell. Added: + +- `Rebuild` (7 stages: `lex`, `parse`, `defines`, `analyze`, `external`, + `lines`, `publish`), `Rebuilt` (their milliseconds plus a `documents` + count) and `rebuild(stage, work)` / `saw_document()` — the same + thread-local, one-`Cell`-read-when-off discipline the module documents, + and *not* routed through `IN_FLUSH`: a rebuild belongs to the rebuild + whichever half of the request runs it. +- `crates/lucisv_server/src/state/mod.rs:119` — `Document::new`'s six + derivations each wrapped at the call. +- `crates/lucisv_server/src/server/diagnostics.rs:57` — the publish + inside `flush_dirty` wrapped as the seventh, so the flush group's + `config`/`build`/`lint`/`fence` are readable as *inside* it. +- `Trace::line()` prints `rebuild{…}` as a **sibling** of `flush{…}` and + `action{…}`; `Trace::is_empty` counts it, so a request that only + rebuilt still logs a line. + +`tools/perf` needed no code change: `phases_r1.py` parses the whole line +through `phases_p2.parse_trace`, which flattens any top-level `name{…}` +group, so the seven stages arrive as `trace_rebuild_*` fields on every +`actionprofile` row. `tools/perf/README.md`'s `actionprofile` row now +says so. + +**The 0.53.0 numbers** (HEAD 1b8723c plus this instrumentation and +nothing else; `actionprofile`, pinmux-comment, "first codeAction after a +didChange", three tries; evidence +`~/.cache/lucisv-perf/63-2/split-0530.jsonl`): + +| | ms | +|---|---:| +| wire latency | 122.6 / 123.0 / 101.4 | +| **flush wall** | **100.0** | +| ├ `rebuild lex` | **29.1** | +| ├ `rebuild parse` (the token clone is inside it) | **25.6** | +| ├ `rebuild publish` | 22.2 — of which `flush lint` 22.0 | +| ├ `rebuild analyze` | 10.1 | +| ├ `rebuild external` | 4.8 | +| ├ `rebuild lines` / `defines` | 0.6 / 0.5 | +| └ unattributed (dropping the previous revision) | ~7 | +| handler's own stages (`action{…}`) | 0.23 — `snapshot=hit` | + +(This is the single run taken before anything changed. The same cell was +re-taken **paired and order-alternated** against the finished candidate +at the end of the round — 110.2 / 110.7 ms, flush wall 102.7 / 107.4 — +see "The paired result"; the stage shares agree, the absolute wire time +of this first run sat on a busier machine.) + +Two of the review's candidates were answered by the split before +anything was built: + +- **A second lint of the same revision: there is none.** `action` reads + `snapshot=hit` and `lint=0.00ms` on every try — the publish's pass is + the menu's pass, which is what review round §R1a bought. +- **A second analysis: there is none either.** `lint::context` already + lends `doc.semantics` to the linter (`with_semantics`), so the lint + pass does not re-`analyze` the tree. + +So the cell is the rebuild, and the rebuild is **lex + parse** (54.7 ms +of the 100). + +### 2026-09-12 — where the rebuild's milliseconds are + +A standalone harness over exactly `Document::new`'s calls +(`scratchpad/63-2/micro`, 15 iterations, median; built against the +reference tree and against the working tree, same compiler, same file) +separates the clone from the parse, which the in-server stage cannot: + +| | 0.53.0 (1b8723c) | after all three changes | +|---|---:|---:| +| `tokenize` | 27.79 | **11.59** | +| `tokens.clone()` | 4.44 | 3.92 | +| `parse_tolerant` | 17.47 | **16.33** | +| `collect_defines` | 0.45 | 0.42 | +| `analyze` | 9.79 | 9.40 | +| `LineIndex::new` | 0.56 | 0.59 | +| dropping the products | 6.27 | 6.40 | +| **total** | **66.8** | **48.6** | + +193 816 tokens, `size_of::()` 120 bytes. + +### 2026-09-12 — change 1: the lexer's two phases, fused + +`crates/vlog_parser/src/lexer.rs` — `tokenize` lexed the whole file into +a `Vec` and then walked it to attach comments. Attachment reads +only the raw token in hand and the token last pushed, so the two loops +fuse into one without touching the result: `attach` / `attach_trailing` +are the same code as the second loop, called per raw token. The +intermediate vector for this file was 193 816 × 56 bytes of allocation, +growth copying and teardown. `tokens` is also given a capacity guess +(`estimated_tokens`, six bytes a token, capped at 2²⁰) — the growth +doubling reached 262 144 slots for this file anyway, so the guess costs +no memory it was not already taking. + +The `blank_before` `if` whose two arms were the same expression is now +one expression, and `tokens.last_mut().unwrap()` is a `let … else` +(library paths take no `unwrap`). + +**Measured** (same harness): `tokenize` 27.8 → **24.7 ms**. + +*File size, for the lead:* `lexer.rs` is one of the two files the +2026-09-07 measurement left over 600 production lines (763). This round +leaves it at **770** — the fusion replaced the second loop with +`attach` / `attach_trailing` rather than adding a responsibility, and the ++7 is the doc comments on them. Splitting the lexer's two halves into +two modules would undo exactly the "one sentence" the fusion restored +(*it turns source text into the token stream, comments attached*), so the +lines were left where they are; the ruling is the lead's. + +### 2026-09-12 — change 2: `Parser::skip` + +`crates/vlog_parser/src/parser/cursor.rs` — `bump()` clones the token +(its `text` is a `String`, so an allocation) and hands it back; **217 of +its ~296 call sites threw the value away on the same line**. `skip()` is +`bump()` for those callers: same comment plumbing (the leading bucket and +the trailing comment are cloned into the pending lists, exactly as +`bump()` moved them out of its own copy), same cursor step, same +`self.tokens` left untouched — so a speculative parse's rewind finds the +stream exactly as it would have. The 217 sites were rewritten +mechanically; `eat_sym` / `eat_kw` are two of them. + +**Measured**: `parse_tolerant` 17.5 → **16.0 ms**. (Modest: the 181 +`expect_sym`/`expect_kw` calls whose token is also discarded still clone. +Left alone deliberately — a second pair of entry points for ~1 ms is not +worth the API.) + +### 2026-09-12 — change 3: the operator table's first-byte test + +`crates/vlog_parser/src/lexer.rs` — every token that was not a comment, +directive, attribute, string, escaped/system identifier, number or +identifier fell into `for op in OPERATORS { if self.starts_with(op) … }`: +**44 slice comparisons for every `;`, `(`, `)`, `,`, `.`, `[`, `]`** in +the file, which in a generated register file is most of the tokens. One +byte compare in front of the slice compare rejects every operator that +cannot start here. Longest-first order is untouched, `starts_with` still +decides, so the token stream cannot move. + +**Measured**: `tokenize` 24.7 → **11.6 ms** — the single largest win of +the round, and a third of the whole cell. + +### 2026-09-12 — one flaky test of my own, found and fixed + +`lint_trace::tests::a_trace_holding_only_a_rebuild_is_not_empty` failed +once in six runs of `cargo test -p lucisv_server`: it armed a trace, ran +an **empty** closure under `rebuild(Rebuild::Analyze, …)` and asserted +the trace was not empty — but a closure that does nothing can measure +0.00 ms, which leaves the group equal to `Rebuilt::default()`. The +assertion was wrong, not the code: what says a rebuild happened is +`saw_document()`, which `Document::new` always calls, not a duration. +The test now calls it, and the reason is written above the test (this is +also why no test here asserts a millisecond — timing lives in the +harness). Six further runs of the module and two full workspace runs +green. The change is inside `#[cfg(test)]`, so the release binary the +paired numbers were taken with is the shipped code unchanged. + +### Not taken, and why + +- **The token-stream clone into `parse_tolerant`** (3.9 ms). The parser + *mutates* its token vector — `take_meta`, `take_dangling`, `take_gap`, + `take_leading_here`, `take_trailing_here` move comments out of it — so + a vector handed over and taken back is a comment-stripped vector, and + `Document::tokens` is read for comments by semantic tokens + (`tokens.rs:181`) and by the linter (`vlog_linter/src/context.rs:534`). + Handing it over would drop comments from highlighting and from the + rules that read them. Making the parser stop mutating the stream is a + real refactor of the comment plumbing for 3.9 ms; filed, not done. +- **`analyze` (9.4 ms) and `resolve_external` (5.5 ms)**: not opened. + The file ownership allows `vlog_semantic` "only for a measured stage", + and after the three changes above the gate is met with margin; a + fourth change would have bought risk, not a verdict. +- **Dropping the previous revision's products (6.3 ms)** happens inside + `set_document` on the request path. Moving it off the path means a + thread or a deferred queue in a single-threaded server; not for this + round. + +## The paired result + +Two binaries: the reference is `cargo build --release` of **1b8723c** +(0.53.0 plus §63.1) in a `git archive` scratch tree, the candidate is the +working tree. Same compiler, same harness, same opentitan at +`0098135…` with its three pre-existing modified files. Each phase run +**four times — ref, candidate, candidate, ref** — so an order effect or +a machine drift shows as a spread between a version's own two rounds. +One warm index store per binary. Three tries a row, median of the tries, +both rounds quoted. Evidence: `~/.cache/lucisv-perf/63-2/paired.jsonl` +(`paired.sh` is the runner), load 4.8 → 4.1 across the run. + +| phase · row | 0.53.0 (a / b) | candidate (a / b) | verdict | +|---|---:|---:|---| +| **`offeredit` pinmux-comment, first offer after didChange** | **110.95 / 107.54** | **88.31 / 88.36** | **−19.2 %** — gate met, stretch (< 95) met | +| `offeredit` pinmux-comment, repeated offer, unchanged buffer | 0.27 / 0.32 | 0.22 / 0.19 | unchanged (noise) | +| `offeredit` aes-reg-instance, first offer after didChange | 5.23 / 8.10 | 6.54 / 6.24 | unchanged (inside the version's own spread) | +| `offeredit` aes-reg-instance, repeated offer | 3.39 / 4.22 | 3.48 / 3.18 | unchanged | +| `offeredit` tb-comment, first offer after didChange | 1.18 / 1.57 | 2.05 / 0.89 | unchanged | +| `offeredit` tb-comment, repeated offer | 0.22 / 0.28 | 0.32 / 0.23 | unchanged | +| `flush` didChange flush (foldingRange barrier) | 1.33 / 1.51 | 0.85 / 1.38 | unchanged | +| `diagnostics` publish after didChange (≈150 ms debounce) | 162.16 / 157.20 | 160.88 / 159.66 | unchanged | +| `offerkinds` — all 35 rows (5 cursors × 7 families) | 0.03 – 6.00 | 0.04 – 4.95 | every row inside its own version's a/b spread; the two rows above 1 ms (`aes-reg-instance` all-family 3.42/6.00 → 4.95/4.57 and `…ports` 2.99/3.73 → 2.92/2.83) do not move | + +**Memory** (`rss`, three fresh processes a cell, KiB): + +| cell | 0.53.0 | candidate | +|---|---:|---:| +| RSS after the workspace scan, cold cache | 505 968 / 508 048 / 505 824 · 501 200 / 501 232 / 505 312 | **478 992 / 479 584 / 480 720 · 480 848 / 479 344 / 479 488** | +| RSS after the workspace scan, warm cache | 428 480 / 429 104 / 425 312 · 427 392 / 430 720 / 427 968 | 427 872 / 428 160 / 426 928 · 427 056 / 427 888 / 427 632 | +| index store on disk | 45 468 | 45 468 | + +Peak RSS is **not up**: warm is flat, and the cold scan — 3 975 files +lexed and parsed — is **~25 MiB lower**, which is the `Vec` the +fused lexer no longer builds. + +**The flush split, paired** (`actionprofile`, pinmux-comment, first +codeAction after a didChange; the same four-run order; the trace is the +last try's, evidence `split-paired.jsonl`): + +| | 0.53.0 + trace (a / b) | candidate (a / b) | +|---|---:|---:| +| wire latency, median of 3 | 110.2 / 110.7 | **89.1 / 89.1** | +| flush wall | 102.7 / 107.4 | **82.2 / 87.5** | +| ├ `lex` | 29.3 / 29.9 | **11.6 / 14.1** | +| ├ `parse` (clone inside) | 25.8 / 30.3 | 23.3 / 26.3 | +| ├ `publish` (of which `lint`) | 23.6 (23.4) / 23.2 (23.0) | 23.9 (23.7) / 23.3 (23.1) | +| ├ `analyze` | 10.7 / 11.3 | 10.4 / 10.7 | +| ├ `external` | 4.8 / 4.7 | 4.7 / 4.7 | +| └ `lines` / `defines` | 0.6 / 0.4 | 0.7 / 0.4 | +| handler (`action`) | `snapshot=hit` | `snapshot=hit` | + +## Parity + +Nothing below is an assertion about intent; each is a comparison of two +builds' outputs over real files. + +1. **The token stream, the parse diagnostics, the whole AST and the + symbol table, file by file.** A digest per file over every token's + kind, text, line, column, span start/end, `blank_before` and every + leading/trailing comment, then over `{:?}` of the diagnostics, of the + `SourceFile` and of `analyze`'s symbols. Run with the same tool built + against the reference tree and against the working tree, over + **4 807 files** (860 corpus + 3 947 opentitan): **0 lines differ** + (`digest-ref.txt` / `digest-new.txt`, `digest.diff` empty). +2. **`format --stdout`, corpus.** 860 files, sha256 per file, reference + binary vs candidate: **0 differ** (`fmt-ref.txt` / `fmt-new.txt`). +3. **`format --stdout`, opentitan.** The whole tree in one run, both + binaries: the same sha256 over the concatenated output + (`2c363ec2eb8395…`) and byte-identical stderr. +4. **Diagnostics and the menu, on the buffer this round is about.** + `parity_menu.py` opens each of the three cursors' files, asks for the + all-family menu and each of the seven `context.only` families — + recording every action's **title, kind and edit payload** — collects + the published diagnostics, then does it twice more after a + `didChange`: once with a harmless comment appended and once with a + revision that deliberately introduces lint findings (a tab, a 140- + character line, a trailing space), so the comparison is not two empty + lists. 87 lines including 12 diagnostics and the fix-all edits: + **identical** (`parity-ref.txt` / `parity-new.txt`). +5. **Suites.** `cargo test --workspace --locked` through the guard: + reference **4 403 passed, 0 failed, 46 ignored**; candidate **4 406 + passed, 0 failed, 46 ignored** — +3, the new `lint_trace` tests. The + parser snapshot and idempotency suites are inside that run + (`vlog_parser` 380 + 22 span tests, `vlog_formatter` 226 + fixtures), + green on their own too. `cargo fmt --all -- --check` and + `cargo clippy --all-targets --locked` clean. No guard kill anywhere in + the round. +6. **opentitan untouched.** `git -C ~/repo/opentitan status --porcelain` + before and after every phase lists exactly the three pre-existing + modified files (`hw/ip/aes/dv/tb/tb.sv`, + `hw/top_darjeeling/ip/ast/rtl/ast.sv`, + `hw/top_earlgrey/ip/ast/rtl/ast.sv`) and nothing else. + +### Re-deriving it + +Everything is under `~/.cache/lucisv-perf/63-2/`: both server binaries +(`server-ref-0.53.0`, `server-step1-trace` — the reference plus the +instrumentation only —, `server-step2-lexparse`), both CLIs +(`lucisv-ref`, `lucisv-new`), the reference tree (`ref-1b8723c/`), the +runners (`run.sh`, `paired.sh`, `split.sh`, `fmtgate.sh`, +`parity_menu.py`), the file lists and every `.jsonl` / `.txt` named +above, plus the stage micro-harness's sources — `micro/` (path +dependencies on the working tree) and `micro-ref/` (on `ref-1b8723c/`). +Both are plain `cargo` crates with no third-party code; `micro`'s +`main.rs` is the per-stage median table and its `bin/digest.rs` is the +per-file digest of parity check 1. + +## For `docs/perf/README.md` (the lead's file) + +> **2026-09-12 — the first request after an edit (TODO §63.2, N1 of the +> 0.52.0 review).** The 40 267-line pinmux cell — one-character +> `didChange`, then the all-family `codeAction` menu — **109 → 88 ms +> paired (−19.2 %)**, the unchanged-repeat cell and every other +> `offeredit`/`offerkinds`/`flush`/`diagnostics` row within noise, cold +> scan RSS ~25 MiB lower and warm RSS flat. The flush is now split in +> the `timing: codeaction` line (`rebuild{lex parse defines analyze +> external lines publish documents}`), which is what named the cost: +> **lex 29 ms and parse 26 ms of a 100 ms flush**, and *no* second lint +> and *no* second analysis of the revision (the snapshot and +> `with_semantics` already had those). Three changes, all in +> `vlog_parser`: the lexer's two phases fused (the intermediate +> `Vec` is gone; 27.8 → 24.7 ms), `Parser::skip` for the 217 +> `bump()` sites that discarded the token (17.5 → 16.0 ms), and a +> first-byte test in front of the 44-entry operator table (24.7 → +> **11.6 ms** — the single largest win). Token stream, parse +> diagnostics, AST and symbol table digested per file over 4 807 files: +> 0 differ; `format --stdout` byte-identical over corpus and opentitan; +> diagnostics and menus identical on the edited buffer. +> **Filed, not fixed:** the token clone into `parse_tolerant` (3.9 ms — +> the parser mutates the stream it is given, so it cannot be handed +> over while `Document::tokens` is read for comments), `analyze` +> (9.4 ms), `resolve_external` (4.7 ms), and the ~6 ms spent dropping +> the previous revision's products on the request path. + +## QA log + +### 2026-09-12 — TODO §63.2 verified: PASS + +Verified the flush split, the three lexer/parser changes, and the lead's +`attach_trailing` edit. Everything below was re-derived independently +(own tools, own binaries, own re-run of the dev's evidence), not read off +the dev's numbers. Scratch work: `/private/tmp/.../scratchpad/63-2-qa/` +(a fresh clone of 1b8723c at `old_lucisv/`, a paired-QA benchmark run at +`paired-qa/`). + +**Gates** (all through `tools/guard.sh -m 8 -t 1800`, no guard kill +anywhere): +- `cargo test --workspace`: **4 422 passed, 0 failed** (run alone, no + concurrent cargo invocation — an earlier attempt run *concurrently* + with another `cargo test`/`cargo build` in the same tree hit a stale + doctest rlib once; that is a target-dir race from running two cargo + processes at once, not a code defect, and does not reproduce solo). + 4 406 (the dev's count) + 16 tests this round added (13 in + `vlog_parser::lexer::tests`, 2 in `lucisv_server::state::tests`, 1 in + `lucisv_server::lint_trace::tests`) = 4 422. +- `cargo clippy --all-targets --workspace`: clean, 0 warnings. +- `cargo fmt --all -- --check`: clean. + +**Fuzzers** (`docs/topo.md`'s `comment-slots` row names four; the SVA +fuzzer is `sva-bodies`'s): `cargo test -p vlog_formatter --test +verification a_comment_in_every_` — covergroup, fragment, constraint, +RTL, SVA, **5/5 pass, still at their pinned gap counts** (329/153/395/ +419-class/705). No formatter or comment-slot code was touched by this +round, so this is a regression check, not new coverage — it stayed at +zero. + +**`skip` vs `bump`, mechanically, not by reading the diff**: a script +diffed old and new `crates/vlog_parser/src/parser/*.rs` and asserted +every hunk is `bump()` → `skip()` and nothing else (line-for-line, same +whitespace). Result: **every one of 178 hunks matches that shape**, and +every removed line is a bare `self.bump();` statement (verified +separately — `grep '^-' | grep -v 'self\.bump();'` on the parser diff +returns nothing but the lexer's unrelated deleted lines and the two +`eat_sym`/`eat_kw` bodies, both bare-statement too). Cross-checked: 252 +`Parser::bump()` call sites existed in `parser/` at 1b8723c, 74 remain +(all `.bump().text` or similar — value used, correctly untouched), +252 − 74 = 178, matching exactly. + +- **Finding (non-blocking, doc-only): the "217 call sites" claim in the + Work log and TODO.md §63.2 does not match the diff.** The diff converts + **178** call sites (176 direct + the 2 inside `eat_sym`/`eat_kw`), not + 217. `~296` (Work log) is real — it is the *textual* `.bump()` count + across all of `vlog_parser/src` including `RawLexer::bump` (a + different, unrelated function) — but 217 does not correspond to any + count I could reproduce from the tree at 1b8723c or from the diff. Not + a safety issue (every conversion that *did* happen is a verified-safe + shape, and no unused-result `self.bump();` statement remains anywhere + in `parser/`), but the number should read 178 wherever it is quoted + again (the Work log, TODO.md §63.2, and the `docs/perf/README.md` paste + in this file all repeat it). Left the dated Work log entries as the + historical record; not editing them. +- **Finding (fixed directly, typo-class): the operator table has 42 + entries, not 44.** Counted `OPERATORS` in `lexer.rs` by hand and by + script: 42. The inline code comment said "44 spellings" — fixed to 42 + (`crates/vlog_parser/src/lexer.rs`, the comment above the first-byte + test). The Work log prose and TODO.md still say 44; same disposition as + above — noted, not rewritten. + +**Comment-attachment attacks on the fused lexer** (item 4): built +`tokenize` from 1b8723c in a fresh clone (`old_lucisv/`) and from the +working tree as two throwaway `examples/qa_token_digest.rs` / +`qa_dump_one.rs` binaries (removed after use — not part of this diff). +- **Whole corpus + opentitan, re-derived independently**: token stream + + parse-tree + diagnostics digest (a hash of `{:?}` output, not read from + the dev's cached digest files) over the same **4 807-file list** the + dev used (`~/.cache/lucisv-perf/63-2/files-all.txt`): **0 lines + differ**. +- **The ten named attack shapes** (comment first in file; two comments + before any token; trailing comment at EOF; two block comments merging + on one line; a blank line between a comment and its token; CRLF; a + block comment spanning lines before a same-line token; a comment + between a macro invocation and its arguments; a file that is only + comments; an empty file): dumped full `Debug` token streams for all + ten from both builds — byte-identical hashes and, for the trickier + three (merge, macro-comment, multi-line block), eyeballed the raw + `Debug` output for sanity. Pinned as **ten new tests** in + `crates/vlog_parser/src/lexer.rs`'s `mod tests` (search + `TODO §63.2 QA`), all passing. +- The lead's `attach_trailing` edit (returns the comment instead of + dropping it when there is no previous token): confirmed the branch is + unreachable through `tokenize` today (`attach` only calls + `attach_trailing` when `same_line_as_prev` is true, which already + requires `!tokens.is_empty()`), so it changes nothing observable yet + and is a correct hardening of invariant 3 for whichever future caller + removes that guard. Compiles clean, no test regressed. + +**Operator table** (item 5): three new tests in `lexer.rs`. +- `every_operator_s_first_byte_is_a_single_ascii_byte` — all 42 entries. +- `the_operator_table_has_no_duplicate_or_empty_entries`. +- `every_operator_followed_by_every_other_operator_still_lexes_without_a_gap` + — all 42×42 = 1 764 concatenations, asserted to round-trip with no gap. + Cross-checked the same 1 764 pairs against 1b8723c with the throwaway + digest tool: **0 differ**. + +**Idempotency and snapshots** (item 6): `cargo test -p vlog_formatter` +green as part of the full workspace run above (`fixtures_match_snapshots +_and_are_idempotent` passes). `tools/corpus_check.sh corpus -b +target/release/lucisv`: 814/820 parse & format, 0 verification errors, 0 +crashes, and the outcome column is **byte-for-byte identical to the +tracked `corpus-check-results.tsv`** for all 820 files. `format --stdout` +byte-identity: **corpus, 0 differ** (stdout and stderr both, against +`~/.cache/lucisv-baselines/lucisv-0.53.0`); **opentitan `hw/ip` +(1 807 files), 0 differ**, same 4 parse errors both binaries, run through +the guard. `git -C ~/repo/opentitan status --porcelain` before and after: +only the three pre-existing files, every time. + +**sha256 / rebuild check** (item 7 precondition): a fresh +`cargo build --release` of the working tree's `lucisv` CLI matches +`~/.cache/lucisv-perf/63-2/lucisv-new` byte for byte +(`fabd3432…bdfcfaf`) — the lead's edit landed before that binary was +built. **`lucisv-server` does *not* match**: `server-step2-lexparse` +(built 01:23) is `b0b09544…`, a fresh build of the current tree is +`694287ea…`. The lead's edit landed between the two builds (01:23 → +01:25), so the server binary used for the dev's own paired run predates +it. Per the brief, rebuilt the candidate and re-ran the paired benchmark +against the fresh binary rather than trusting the cached one. + +**Paired re-take** (item 7), `paired-qa.sh` (same shape as the dev's +`paired.sh`, ref/new alternated, 3 tries, one warm store per binary), +against the freshly built candidate `lucisv-server` (694287ea…) and the +reference rebuilt from 1b8723c and hash-verified against +`server-ref-0.53.0` (6b1b5245…, matches): + +| cell | ref (a/b) | candidate (a/b) | change | +|---|---:|---:|---| +| `offeredit` pinmux-comment, first after didChange (median of 3) | 112.31 / 110.63 | 90.35 / 92.57 | **−19.6% / −16.3%**, gate (≥15%) met both rounds, stretch (<95ms) met | +| `offeredit` aes-reg-instance, first after didChange | 6.32–7.82 | 2.94–8.05 | inside noise, matches dev's characterization | +| `offeredit` tb-comment, first after didChange | 0.56–3.94 | 0.56–3.08 | inside noise | +| `offerkinds`, 35 rows | 0.03–6.0 ms | 0.03–5.0 ms | no row moved out of range | +| RSS cold | 502.7–505.2 MiB | 478.6–483.1 MiB | lower, matches "cold ~25 MiB lower" | +| RSS warm | 427.4–429.4 MiB | 426.9–429.3 MiB | flat | + +This run was **not** on an idle machine (a `cargo test --workspace` was +running concurrently in the background for part of it), which is why the +absolute ms are a little higher than the dev's own quieter-machine +numbers — the percentage reduction and every qualitative claim +(noise-level `offerkinds`/other cursors, RSS direction) hold anyway, so +the gate is met with margin either way. + +Also re-ran `parity_menu.py` (item covering TODO.md's "an edit that +moves a fence" attack, plus the lex-failure and `define`-table attacks +below) against the freshly built ref/candidate pair: **87 lines, 0 +differ**, same as the dev's own run — the LINTY edit's fence/lint-finding +path is unaffected. + +**TODO.md's three named parity attacks** — a buffer that fails to lex, a +`` `define `` edit that changes the macro table, an edit that moves a +fence: +1. **Lex failure**: new test + `a_buffer_that_fails_to_lex_still_records_every_rebuild_stage` + (`state/mod.rs`) — an unterminated string literal, confirms `tokens` + stays empty, a diagnostic is produced, `Rebuild::Lex` is still + recorded (the failed attempt is real work), and every other stage + (`defines`/`analyze`/`external`/`lines`/`publish`) still runs over the + empty tree exactly as the un-instrumented code always did. +2. **`define` edit**: new test + `a_define_edit_changes_the_macro_table_the_rebuild_reports_on` — + two `Document::new` calls with different macros, confirms the second + document's table has no trace of the first's macro (no cross-document + staleness introduced by wrapping `collect_defines` in `rebuild`). +3. **Fence-moving edit**: covered by the `parity_menu.py` re-run above + (the LINTY revision is exactly this — a new lint finding changes what + the fence/diagnostics path reports for the revision). + +**`lint_trace` arithmetic — sabotaged, as asked** (item 8): nested +`rebuild{…}` inside `flush{…}` in `Trace::line()` and reran the dev's +pinning test, `the_rebuild_group_names_every_stage_beside_the_other_two`. +**It did not fail.** That test extracts the rebuild body by splitting on +the literal string `"rebuild{"` and the *next* `}`, which finds a clean +body whether or not another `}` follows — the extra brace the nesting +adds sits outside the slice the test inspects. Checked what actually +happens to a consumer against `tools/perf/phases_p2.py`'s real regex +(`([a-z_]+)\{([^{}]*)\}`, which cannot cross an inner `{`): run against +the sabotaged line, `GROUP.findall` matched only `rebuild` and `action` +— **the whole `flush` group silently fails to match**, and +`flush_wall`/`flush_buffers`/`flush_parses` and every `flush.fields()` +key vanish from that row with no error anywhere. So the existing pin +does not actually enforce the sibling-group contract it documents. +Added `the_three_top_level_groups_are_flat_never_nested` to +`lint_trace.rs`'s test module, which reads the line the way the regex +does (each group must reach its own `}` before another `{` opens) — +confirmed it **fails** against the sabotaged code and **passes** after +reverting the sabotage; the sabotage itself is reverted (`git diff` of +`lint_trace.rs` no longer shows it). This is the one finding I'd call a +real gap rather than a documentation slip, though it is a `tools/perf` +tooling-correctness issue, not a formatter-invariant one (no corpus/ +opentitan output is affected), so it does not block this round; filed as +a fix-directly-and-note per CLAUDE.md's QA rule since the fix is a test +addition, not a redesign. + +**Not independently re-verified**: the dev's own `flush`/`diagnostics` +paired cells (only `offeredit`/`offerkinds`/`rss` were named in my brief +for item 7); the micro-harness per-stage table (`tokenize` 27.79→11.59ms +etc.) — trusted as reported, since the stage split itself is exercised +by the corpus-wide digest and the paired re-take above. + +**Verdict: PASS.** No corpus, opentitan, snapshot, idempotency or +comment-preservation regression found anywhere; the two real findings +are a documentation/count inaccuracy (217→178, 44→42, the latter fixed) +and a test-strength gap in the sibling-group pin (fixed with a new test +that actually catches the nesting failure mode). Gate met with an +independently-measured margin on a busier machine than the dev's own +run. + +## Review + +**Lead review, 2026-09-12 — accepted.** The lane did what the brief +asked in the order it asked: the flush split came first and it settled +two of the review's candidates without code (no second lint, no second +analysis), then named the two stages that mattered — lex and parse, 55 of +a 100 ms flush. The three changes are all in `vlog_parser` and all +behaviour-preserving by construction: the lexer fusion is a reordering of +the same attachment loop (the fused `attach` reads only the raw token in +hand and the token last pushed, which is all the old loop ever read), +`Parser::skip` is `bump` minus the clone with the same comment plumbing, +and the first-byte test in front of the operator table is a filter in +front of an unchanged `starts_with`. The proof is the one that matters for +a lexer change: token stream, diagnostics, AST and symbols digested per +file over 4 807 files with 0 differing, re-derived by QA from a rebuilt +1b8723c, plus the five gap fuzzers at their pinned counts and every +byte-identity gate. Gate met at −19.2 % (dev) and −19.6 % / −16.3 % (QA's +re-take on a busier machine), stretch met. + +One edit is the lead's, and QA covered it: `attach_trailing` now hands an +orphan comment back to `pending` instead of returning silently — the +branch is unreachable while `same_line_as_prev` requires a token, and it +stays a rule rather than a hope (invariant 3). + +Rulings on QA's findings: + +- **Counts** (217 call sites and 44 operators in the Work log; 178 and + 42 in the tree): the Work log stands as a dated record; the lead's own + entry in `docs/perf/README.md`, TODO §63.2 and the topo row carry the + verified numbers. +- **The nesting guard**: the dev's pin string-split the line and missed a + nested group; QA's `the_three_top_level_groups_are_flat_never_nested` + runs the real regex and catches the sabotage. Accepted as the pin. + +Deferred with the dev's reasons and filed in TODO's loop-3 list: the +token clone into `parse_tolerant` (the parser mutates the stream it is +given), `analyze`, `resolve_external`, and dropping the previous revision +on the request path. `lexer.rs` at 770 production lines is noted: the +fusion removed a responsibility rather than adding one. diff --git a/docs/perf/README.md b/docs/perf/README.md index 93f196f..47171c6 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1350,3 +1350,43 @@ three are fixed in 0.53.0; no performance number moved. the retained-analysis parse work and the 31 ms facts decode, the whole-index merge per publication) are filed with the review's baselines and deferred to loop 3. + +### 2026-09-12 — loop 3, round 1 (TODO §63) + +**§63.1 is a correctness lane, not a performance one**, recorded here +because its parity ran through this harness: a `bind` file's own +occurrence of a renamed name is now edited (resolvable) or warned about +(not), never silent — the resolver had asked the bind target's +*connection* surface for a bare name and rooted a bind's hierarchical +path in the writing scope (`FACTS_FORMAT` 19 → 20). `renamewarn` 1 758 → +1 764 sentences, 1 758 − 8 = 1 750 held; every one of the 28 paired keys +that moved is a bind file's new edit or warning; tail rename 326 ms +(gate ≤ 330). `docs/features/rename-bind-occurrences/README.md`. + +**§63.2 — the first request after an edit (N1 of the 0.52.0 review).** +The 40 267-line pinmux cell — one-character `didChange`, then the +all-family `codeAction` menu — **109 → 88 ms paired (−19.2 % dev; +−19.6 % / −16.3 % on QA's re-take, order alternated)**; the +unchanged-repeat cell and every other `offeredit`/`offerkinds`/`flush`/ +`diagnostics` row within noise; cold-scan RSS ~25 MiB lower, warm flat. +The flush is now split on the `timing: codeaction` line +(`rebuild{lex parse defines analyze external lines publish documents}`), +which is what named the cost: **lex 29 ms and parse 26 ms of a 100 ms +flush**, and *no* second lint and *no* second analysis of the revision +(the snapshot and `with_semantics` already had those). Three changes, all +in `vlog_parser`: the lexer's two phases fused (the intermediate +`Vec` gone; `tokenize` 27.8 → 24.7 ms), `Parser::skip` for the +178 `bump()` sites that discarded the token (`parse_tolerant` 17.5 → +16.0 ms), and a first-byte test in front of the 42-entry operator table +(`tokenize` 24.7 → **11.6 ms**, the single largest win). Token stream, +parse diagnostics, AST and symbol table digested per file over 4 807 +files, re-derived by QA against a rebuilt 1b8723c: 0 differ; the five +gap fuzzers at their pinned counts; `format --stdout` byte-identical over +corpus and opentitan `hw/ip`; diagnostics and menus identical on the +edited buffer (87 lines). **Filed, not fixed** (TODO loop-3 list): the +token clone into `parse_tolerant` (3.9 ms — the parser mutates the +stream it is given, so it cannot be handed over while `Document::tokens` +is read for comments), `analyze` (9.4 ms), `resolve_external` (4.7 ms), +and ~6 ms dropping the previous revision's products on the request path. +`docs/features/perf-first-after-edit/README.md`; evidence +`~/.cache/lucisv-perf/63-2/`. diff --git a/docs/topo.md b/docs/topo.md index 3efc8ec..46824a7 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -621,7 +621,7 @@ engine-lane features are listed above; this table is the server-internal web. | `hover-line-index ──▶ hover-declarations / port-detail-spans` | depends | `Def::lines` supplies indexed hover headings (including split-port detail lines); `Workspace::file_view` supplies the guarded snippet and the few non-indexed line lookups. `locate::location` shares that view, so a references list reads a closed file once rather than once per site. | | `cancel-request ──▶ lsp-server pin` | depends | See §1.2; queue/burst exists because the pinned transport is a rendezvous channel. | | `scan-interleave ──▶ cancel-request / work-done-progress` | depends | The same queue is polled between startup-scan files. `publish_scan` lands the index, completion and include batches before dispatch; `must_wait` holds requests queued behind any rescan-triggering message and preserves their order/cancels. Progress still counts the whole scan even when requests are answered before the bar comes down. | -| `verbose-timing ◀──▶ editor-packaging / scan-interleave / change-debounce` | handshake | `lucisv.verbose` is an extension-owned spawn setting: false means no arguments and no timing traffic; true means `lucisv-server --verbose`, and changing it restarts the client process. The server writes `MessageType::LOG` lines prefixed `timing:` for request/notification handlers, scan and widen lifecycles, dirty-buffer flushes, one-file reindexes, and requests held behind rescans. The request line precedes its response; notification lines follow their work. Instrumentation is silent by construction when off (one branch, no clock read or formatting), and it observes rather than changes scan/queue ordering. **Amended by perf5-p2 and perf5-p4 (2026-09-07/08):** the `timing: rename trace …` line and the three `timing: scan … : key=value …` lines (`stages`, `counts`, `memory`) plus `timing: configuration answered in X ms` are `key=value` formatted and **are parsed** by `tools/perf/` (`renametrace`, `scanprofile`); their format is pinned by server tests, so the old "nobody parses these lines" assumption no longer holds for those five. `Workspace::begin_scan`/`begin_widen` take `trace: bool` (every pre-existing caller passes `false`), `take_scan_trace()` hands the finished trace to the server; `Candidates::sizes()`, `IncludeGraph::sizes()`, `IndexCache::{work, entry_count, encoded_bytes}` are read-only queries for the memory line; `Server::born` and the `Instant` on `Pending::Configuration` time the config round trip. | +| `verbose-timing ◀──▶ editor-packaging / scan-interleave / change-debounce` | handshake | `lucisv.verbose` is an extension-owned spawn setting: false means no arguments and no timing traffic; true means `lucisv-server --verbose`, and changing it restarts the client process. The server writes `MessageType::LOG` lines prefixed `timing:` for request/notification handlers, scan and widen lifecycles, dirty-buffer flushes, one-file reindexes, and requests held behind rescans. The request line precedes its response; notification lines follow their work. Instrumentation is silent by construction when off (one branch, no clock read or formatting), and it observes rather than changes scan/queue ordering. **Amended by perf5-p2 and perf5-p4 (2026-09-07/08):** the `timing: rename trace …` line and the three `timing: scan … : key=value …` lines (`stages`, `counts`, `memory`) plus `timing: configuration answered in X ms` are `key=value` formatted and **are parsed** by `tools/perf/` (`renametrace`, `scanprofile`); their format is pinned by server tests, so the old "nobody parses these lines" assumption no longer holds for those five. `Workspace::begin_scan`/`begin_widen` take `trace: bool` (every pre-existing caller passes `false`), `take_scan_trace()` hands the finished trace to the server; `Candidates::sizes()`, `IncludeGraph::sizes()`, `IndexCache::{work, entry_count, encoded_bytes}` are read-only queries for the memory line; `Server::born` and the `Instant` on `Pending::Configuration` time the config round trip. **(2026-09-12, TODO §63.2)** the `timing: codeaction` line carries a third top-level group, `rebuild{lex parse defines analyze external lines publish documents}` — `Document::new`'s six derivations and the publish inside `flush_dirty`, traced through `crate::lint_trace` — beside `flush{…}` and `action{…}`; the three groups are **siblings by contract** (`tools/perf/phases_p2.py`'s regex flattens one level, and a nested group makes the whole `flush` group vanish from every row with no error), pinned by `lint_trace::tests::the_three_top_level_groups_are_flat_never_nested`. | | `work-done-progress ──▶ indexing-ux` | depends (then) | w-d-p put up the bar; indexing-ux made it count (`IndexEvent` stream); index-persistence added `Cached`. | | `large-file-mode ◀──▶ semantic-tokens-delta` | handshake | The windowed lexing serves `semanticTokens/range`; on a large buffer `full`/`full/delta` must answer an ERROR (`ServerCancelled`/`ContentModified`) or the client stops asking the range provider — two sides pinning one wire behavior. `Document::large` is structurally a full `Document` (all fields valid, empty) so no handler changes — the obligation lands on **future** handlers that read `doc.text` (dispatch-table test enforces). | | `lsp-318-extras ──▶ range-formatting` | depends | `rangesFormatting` is a thin adapter over the same n-range `LineRanges` engine `--lines` uses; hand-rolled params because `lsp-types` 0.97 lacks 3.18. | @@ -804,7 +804,7 @@ ownership explicitly. | `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Class and statement scopes are supported by statement-fences (§2.9-3 delivered); `range::plan` must merge these protected spans with unselected runs. Port and case-label lists remain outside independent fence scopes. | | `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). | | `lucisv_server/src/server/` | lucisv-server; amended by cancel-request, change-debounce, scan-interleave, index-scope, verbose-timing | every request/notification and every rebuild trigger | One ordered loop owns all mutable server state. A startup scan may publish a prefix and answer queued work between files; a request queued behind a rescan trigger is held until that rescan lands, and its cancel travels with it. Never make the distinction time-based: machine load must not change which index a request sees. Verbose timing may observe each wrapper/lifecycle but must be entirely silent when off and must not move protocol ordering. The queue thread only forwards protocol messages and must never parse. | -| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs; it reads flat at depth 0 and walks descendants at positive depth (including the default 2)) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. | +| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs; it reads flat at depth 0 and walks descendants at positive depth (including the default 2)) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. **(2026-09-12)** `Document::new`'s derivations are individually traced (`lint_trace::Rebuild`), so a stage added to or removed from that constructor wants a `Rebuild` variant beside it. | | `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. | | `vlog_semantic/src/workspace/` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, member semantics, semantic-lints-on, bind-semantics, SVA bodies and refactor-rename performance | server state, hierarchy/lens/type-hierarchy, refactor, completion, semantic lints | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (current 19), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` must equal one build over the resulting record set; `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal; `FileFacts::words` is the shared project mention/completion census. | | `vlog_refactor/src/rename/` | refactor-rename; shared by references-nav and the performance wave | server rename/prepareRename/references and port refactor verification | `Scope` remains the whole-scope authority and `collect_occurrences` the one rename/references walk. The fast `prepare_rename_here` answer/refusal and `rename_name_at` target are parity contracts, not alternate semantics. Any new refusal must be expressible on the fast path or force a deferral; any new occurrence shape must be reflected in the server fan-out or trigger its all-sources fallback. | diff --git a/tools/perf/README.md b/tools/perf/README.md index 497f2f8..9d1ee52 100644 --- a/tools/perf/README.md +++ b/tools/perf/README.md @@ -88,7 +88,7 @@ apart in `results.jsonl`; run each phase once per binary. | `scanprofile` | §P4a | the startup breakdown, from the server's own `timing: scan stages/counts/memory` lines: workspace cold and warm, the default scope, `scopeDepth 0`, and 1 / 10 / 100 open buffers. **One row per traced scan** — a session at a configured scope pays two (the startup scan runs at the default settings and the pulled scope asks for another), and adding them together would be wrong | | `scanwait` | §P4a | §P0's first-useful-answer rows, re-run under `--verbose`, so the trace of the very session that answered sits in the row: when the first publish landed, how many publishes there were, how long the config round trip took | | `scanserve` | §P4a | a `textDocument/definition` every 200 ms for as long as the scan is still saying anything: the mid-scan latency distribution, and `mismatched_answers` — non-empty answers that named somewhere the settled index does not, which must be 0 (the coherence contract of `docs/features/index-scope/README.md`) | -| `actionprofile` | §R1b | one `--verbose` session per cursor, four request shapes each — the first menu of the session, three repeats on the unchanged buffer, a definition queued behind it, and the first menu after each of three `didChange`s — with the server's own `timing: codeaction …` line parsed into `trace_*` fields. Two groups per line: `flush{…}` is the debounced `Document` rebuild and the diagnostics publish inside it, `action{…}` is the handler. A request that lints nothing logs no line, which is why the queued rows say how many the follower logged | +| `actionprofile` | §R1b | one `--verbose` session per cursor, four request shapes each — the first menu of the session, three repeats on the unchanged buffer, a definition queued behind it, and the first menu after each of three `didChange`s — with the server's own `timing: codeaction …` line parsed into `trace_*` fields. **Three** groups per line: `flush{…}` is the debounced `Document` rebuild and the diagnostics publish inside it, `rebuild{…}` splits that rebuild into the stages `Document::new` runs — `lex`, `parse`, `defines`, `analyze`, `external`, `lines` — plus the `publish` the flush does with the result and the `documents` it built (TODO §63.2), and `action{…}` is the handler. The groups are **siblings, never nested**: `phases_p2.parse_trace` flattens one level of `name{…}`, which is how all three arrive as `trace_flush_*` / `trace_rebuild_*` / `trace_action_*` row fields with no parser change. A request that lints nothing logs no line, which is why the queued rows say how many the follower logged | | `ruleablation` | §R1b | *which* rules the pinmux quickfix menu's milliseconds are in: one warm session, `lucisv.lint.select` pushed to a single rule per row by `didChangeConfiguration` (a selection change rescans nothing), the unrestricted control taken first **and** last so session drift is visible rather than blamed on a rule | | `snapshotrss` | §R1a | idle and peak RSS with 1 / 10 / 100 open buffers, each sent one quickfix-only `codeAction` so that every open document holds a lint snapshot — the memory bound of `docs/features/perf5r-lint-snapshot/README.md`. `rss_kib` / `peak_rss_kib`, never `ms` | | `renamewarn` | §R3b | every `lucisv: ` warning sentence four renames say, in order, written into the row as `titles` and compared **line by line** between labels. `renametrace` hashes a rename's edits; its warnings are `window/logMessage` notifications and are in no fingerprint, so a reuse that kept every edit and dropped a sentence would otherwise pass |